@hopeplayer/core 1.0.17 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/HopePlayerElement.d.ts +4 -0
  2. package/dist/HopePlayerElement.d.ts.map +1 -1
  3. package/dist/chunks/{adTriggers-4SueRFgK.js → adTriggers-DXmtF4t2.js} +112 -117
  4. package/dist/chunks/adTriggers-DXmtF4t2.js.map +1 -0
  5. package/dist/chunks/{ads-DPL7m9PV.js → ads-BZYADoen.js} +2 -2
  6. package/dist/chunks/{ads-DPL7m9PV.js.map → ads-BZYADoen.js.map} +1 -1
  7. package/dist/chunks/{cast-DCAT2agI.js → cast-BGgfNj37.js} +70 -66
  8. package/dist/chunks/cast-BGgfNj37.js.map +1 -0
  9. package/dist/chunks/hls-DAtZkTUi.js +45 -0
  10. package/dist/chunks/{hls-BOHE_fg_.js.map → hls-DAtZkTUi.js.map} +1 -1
  11. package/dist/chunks/hlsLight-CCe_8eOw.js +28 -0
  12. package/dist/chunks/hlsLight-CCe_8eOw.js.map +1 -0
  13. package/dist/chunks/{markers-DE4O8xbw.js → markers-u2bpLu30.js} +2 -2
  14. package/dist/chunks/{markers-DE4O8xbw.js.map → markers-u2bpLu30.js.map} +1 -1
  15. package/dist/chunks/{player-C886oKP-.js → player-B_e_Nnvb.js} +510 -435
  16. package/dist/chunks/player-B_e_Nnvb.js.map +1 -0
  17. package/dist/chunks/{playlist-CI3mRZjo.js → playlist-ClnEXcRy.js} +24 -24
  18. package/dist/chunks/playlist-ClnEXcRy.js.map +1 -0
  19. package/dist/chunks/{qrResume-BNy8XCp_.js → qrResume-DXwD3oSA.js} +29 -30
  20. package/dist/chunks/{qrResume-BNy8XCp_.js.map → qrResume-DXwD3oSA.js.map} +1 -1
  21. package/dist/chunks/{redirectScreen-CJ3q9OX4.js → redirectScreen-DZwpVYWk.js} +2 -2
  22. package/dist/chunks/{redirectScreen-CJ3q9OX4.js.map → redirectScreen-DZwpVYWk.js.map} +1 -1
  23. package/dist/chunks/{rewardedUnlock-EyGMB9PK.js → rewardedUnlock-DoRVfTlV.js} +2 -2
  24. package/dist/chunks/{rewardedUnlock-EyGMB9PK.js.map → rewardedUnlock-DoRVfTlV.js.map} +1 -1
  25. package/dist/chunks/seekWhenReady-Clzne3-S.js +32 -0
  26. package/dist/chunks/seekWhenReady-Clzne3-S.js.map +1 -0
  27. package/dist/chunks/{segments-C2HKU6XK.js → segments-DERcwNUG.js} +2 -2
  28. package/dist/chunks/{segments-C2HKU6XK.js.map → segments-DERcwNUG.js.map} +1 -1
  29. package/dist/chunks/skipSegments-XjblXCGo.js +122 -0
  30. package/dist/chunks/skipSegments-XjblXCGo.js.map +1 -0
  31. package/dist/chunks/{sponsorship-DyFwGmEb.js → sponsorship-BT21uwN5.js} +36 -41
  32. package/dist/chunks/sponsorship-BT21uwN5.js.map +1 -0
  33. package/dist/chunks/{spriteThumbnails-D0NQ5CCp.js → spriteThumbnails-y_JaE9LE.js} +2 -2
  34. package/dist/chunks/{spriteThumbnails-D0NQ5CCp.js.map → spriteThumbnails-y_JaE9LE.js.map} +1 -1
  35. package/dist/chunks/{story-D5Got6-6.js → story-UpOGg7Ch.js} +27 -15
  36. package/dist/chunks/story-UpOGg7Ch.js.map +1 -0
  37. package/dist/chunks/trackingPixel-D2wxdCEz.js +20 -0
  38. package/dist/chunks/trackingPixel-D2wxdCEz.js.map +1 -0
  39. package/dist/controls/SeekBar.d.ts.map +1 -1
  40. package/dist/controls/SettingsMenu.d.ts +16 -0
  41. package/dist/controls/SettingsMenu.d.ts.map +1 -1
  42. package/dist/hls/SourceManager.d.ts +2 -0
  43. package/dist/hls/SourceManager.d.ts.map +1 -1
  44. package/dist/hope-player.js +1 -1
  45. package/dist/i18n/locales/en.d.ts.map +1 -1
  46. package/dist/i18n/locales/tr.d.ts.map +1 -1
  47. package/dist/i18n/types.d.ts +5 -0
  48. package/dist/i18n/types.d.ts.map +1 -1
  49. package/dist/keyboard/KeyboardController.d.ts.map +1 -1
  50. package/dist/plugins/ad-triggers/AdTriggers.d.ts.map +1 -1
  51. package/dist/plugins/cast/CastController.d.ts.map +1 -1
  52. package/dist/plugins/playlist/PlaylistRunner.d.ts.map +1 -1
  53. package/dist/plugins/qr-resume/QrResume.d.ts.map +1 -1
  54. package/dist/plugins/shared/seekWhenReady.d.ts +22 -0
  55. package/dist/plugins/shared/seekWhenReady.d.ts.map +1 -0
  56. package/dist/plugins/shared/trackingPixel.d.ts +8 -0
  57. package/dist/plugins/shared/trackingPixel.d.ts.map +1 -0
  58. package/dist/plugins/skip-segments/SkipSegments.d.ts +40 -0
  59. package/dist/plugins/skip-segments/SkipSegments.d.ts.map +1 -0
  60. package/dist/plugins/skip-segments/index.d.ts +6 -0
  61. package/dist/plugins/skip-segments/index.d.ts.map +1 -0
  62. package/dist/plugins/sponsorship/SponsorshipLayer.d.ts.map +1 -1
  63. package/dist/plugins/story/HopeStory.d.ts +2 -0
  64. package/dist/plugins/story/HopeStory.d.ts.map +1 -1
  65. package/dist/screens/ErrorScreen.d.ts +7 -0
  66. package/dist/screens/ErrorScreen.d.ts.map +1 -1
  67. package/dist/types/index.d.ts +60 -0
  68. package/dist/types/index.d.ts.map +1 -1
  69. package/dist/utils/media-error.d.ts +10 -0
  70. package/dist/utils/media-error.d.ts.map +1 -0
  71. package/dist/utils/seek-by.d.ts +8 -0
  72. package/dist/utils/seek-by.d.ts.map +1 -1
  73. package/package.json +2 -1
  74. package/dist/chunks/adTriggers-4SueRFgK.js.map +0 -1
  75. package/dist/chunks/cast-DCAT2agI.js.map +0 -1
  76. package/dist/chunks/hls-BOHE_fg_.js +0 -24791
  77. package/dist/chunks/player-C886oKP-.js.map +0 -1
  78. package/dist/chunks/playlist-CI3mRZjo.js.map +0 -1
  79. package/dist/chunks/sponsorship-DyFwGmEb.js.map +0 -1
  80. package/dist/chunks/story-D5Got6-6.js.map +0 -1
@@ -0,0 +1,45 @@
1
+ const $=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},Rl=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=bl},bl=Number.MAX_SAFE_INTEGER||9007199254740991;let Y=(function(n){return n.NETWORK_ERROR="networkError",n.MEDIA_ERROR="mediaError",n.KEY_SYSTEM_ERROR="keySystemError",n.MUX_ERROR="muxError",n.OTHER_ERROR="otherError",n})({}),R=(function(n){return n.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",n.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",n.KEY_SYSTEM_NO_SESSION="keySystemNoSession",n.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",n.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",n.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",n.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",n.MANIFEST_LOAD_ERROR="manifestLoadError",n.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",n.MANIFEST_PARSING_ERROR="manifestParsingError",n.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",n.LEVEL_EMPTY_ERROR="levelEmptyError",n.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",n.LEVEL_LOAD_ERROR="levelLoadError",n.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",n.LEVEL_PARSING_ERROR="levelParsingError",n.LEVEL_SWITCH_ERROR="levelSwitchError",n.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",n.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",n.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",n.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",n.FRAG_LOAD_ERROR="fragLoadError",n.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",n.FRAG_DECRYPT_ERROR="fragDecryptError",n.FRAG_PARSING_ERROR="fragParsingError",n.FRAG_GAP="fragGap",n.REMUX_ALLOC_ERROR="remuxAllocError",n.KEY_LOAD_ERROR="keyLoadError",n.KEY_LOAD_TIMEOUT="keyLoadTimeOut",n.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",n.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",n.BUFFER_APPEND_ERROR="bufferAppendError",n.BUFFER_APPENDING_ERROR="bufferAppendingError",n.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",n.BUFFER_STALLED_ERROR="bufferStalledError",n.BUFFER_FULL_ERROR="bufferFullError",n.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",n.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",n.ASSET_LIST_LOAD_ERROR="assetListLoadError",n.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",n.ASSET_LIST_PARSING_ERROR="assetListParsingError",n.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",n.INTERNAL_EXCEPTION="internalException",n.INTERNAL_ABORTED="aborted",n.ATTACH_MEDIA_ERROR="attachMediaError",n.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",n.UNKNOWN="unknown",n})({}),m=(function(n){return n.MEDIA_ATTACHING="hlsMediaAttaching",n.MEDIA_ATTACHED="hlsMediaAttached",n.MEDIA_DETACHING="hlsMediaDetaching",n.MEDIA_DETACHED="hlsMediaDetached",n.MEDIA_ENDED="hlsMediaEnded",n.STALL_RESOLVED="hlsStallResolved",n.BUFFER_RESET="hlsBufferReset",n.BUFFER_CODECS="hlsBufferCodecs",n.BUFFER_CREATED="hlsBufferCreated",n.BUFFER_APPENDING="hlsBufferAppending",n.BUFFER_APPENDED="hlsBufferAppended",n.BUFFER_EOS="hlsBufferEos",n.BUFFERED_TO_END="hlsBufferedToEnd",n.BUFFER_FLUSHING="hlsBufferFlushing",n.BUFFER_FLUSHED="hlsBufferFlushed",n.MANIFEST_LOADING="hlsManifestLoading",n.MANIFEST_LOADED="hlsManifestLoaded",n.MANIFEST_PARSED="hlsManifestParsed",n.LEVEL_SWITCHING="hlsLevelSwitching",n.LEVEL_SWITCHED="hlsLevelSwitched",n.LEVEL_LOADING="hlsLevelLoading",n.LEVEL_LOADED="hlsLevelLoaded",n.LEVEL_UPDATED="hlsLevelUpdated",n.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",n.LEVELS_UPDATED="hlsLevelsUpdated",n.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",n.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",n.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",n.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",n.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",n.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",n.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",n.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",n.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",n.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",n.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",n.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",n.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",n.CUES_PARSED="hlsCuesParsed",n.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",n.INIT_PTS_FOUND="hlsInitPtsFound",n.FRAG_LOADING="hlsFragLoading",n.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",n.FRAG_LOADED="hlsFragLoaded",n.FRAG_DECRYPTED="hlsFragDecrypted",n.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",n.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",n.FRAG_PARSING_METADATA="hlsFragParsingMetadata",n.FRAG_PARSED="hlsFragParsed",n.FRAG_BUFFERED="hlsFragBuffered",n.FRAG_CHANGED="hlsFragChanged",n.FPS_DROP="hlsFpsDrop",n.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",n.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",n.ERROR="hlsError",n.DESTROYING="hlsDestroying",n.KEY_LOADING="hlsKeyLoading",n.KEY_LOADED="hlsKeyLoaded",n.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",n.BACK_BUFFER_REACHED="hlsBackBufferReached",n.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",n.ASSET_LIST_LOADING="hlsAssetListLoading",n.ASSET_LIST_LOADED="hlsAssetListLoaded",n.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",n.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",n.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",n.INTERSTITIAL_STARTED="hlsInterstitialStarted",n.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",n.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",n.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",n.INTERSTITIAL_ENDED="hlsInterstitialEnded",n.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",n.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",n.EVENT_CUE_ENTER="hlsEventCueEnter",n})({});function Dl(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var xr={exports:{}},Fr;function kl(){return Fr||(Fr=1,(function(n,t){(function(e){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,h,d){if(d=d||{},l=l.trim(),h=h.trim(),!h){if(!d.alwaysNormalize)return l;var c=o.parseURL(l);if(!c)throw new Error("Error trying to parse base URL.");return c.path=o.normalizePath(c.path),o.buildURLFromParts(c)}var u=o.parseURL(h);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return d.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):h;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(p.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)p.path=f.path,u.params||(p.params=f.params,u.query||(p.query=f.query));else{var v=f.path,E=v.substring(0,v.lastIndexOf("/")+1)+u.path;p.path=o.normalizePath(E)}return p.path===null&&(p.path=d.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(p)},parseURL:function(l){var h=s.exec(l);return h?{scheme:h[1]||"",netLoc:h[2]||"",path:h[3]||"",params:h[4]||"",query:h[5]||"",fragment:h[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};n.exports=o})()})(xr)),xr.exports}var ai=kl();class us{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}}}let st=(function(n){return n.MANIFEST="manifest",n.LEVEL="level",n.AUDIO_TRACK="audioTrack",n.SUBTITLE_TRACK="subtitleTrack",n.MEDIA_FRAGMENT="media-fragment",n.KEY="key",n.STEERING_MANIFEST="steering-manifest",n.SERVER_CERTIFICATE="server-certificate",n.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",n})({}),K=(function(n){return n.MAIN="main",n.AUDIO="audio",n.SUBTITLE="subtitle",n})({});var ut={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class oi{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof t=="string"&&(t={url:t}),this.base=t,Pl(this,"stats")}setByteRange(t,e){const s=t.split("@",2);let i;s.length===1?i=e?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[ut.AUDIO]:null,[ut.VIDEO]:null,[ut.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new us),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.relurl&&(this._url=ai.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[ut.AUDIO]=null,t[ut.VIDEO]=null,t[ut.AUDIOVIDEO]=null,this.url=null}}function Et(n){return n.sn!=="initSegment"}function Ue(n,t){return n.sn===t?.sn&&n.level===t.level}function li(n,t){return n.sn===t?.sn&&n.level===t.level&&n.cc===t.cc}class Be extends oi{constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],e=this.byteRange[1];if($(t)&&$(e))return e-t}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(!((t=this._decryptdata)!=null&&t.keyId)){const s=Object.keys(e);if(s.length===1){const i=this._decryptdata=e[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const t=$(this.duration)?this.duration:0;return this.programDateTime+t*1e3}get encrypted(){var t;if((t=this._decryptdata)!=null&&t.encrypted)return!0;if(this.levelkeys){var e;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(e=this.levelkeys[s[0]])!=null&&e.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){if(!$(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return Et(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var s;const i=e[t];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,e))}}abortRequests(){var t,e;(t=this.loader)==null||t.abort(),(e=this.keyLoader)==null||e.abort()}setElementaryStreamInfo(t,e,s,i,r,a=!1){const{elementaryStreams:o}=this,l=o[t];if(!l){o[t]={startPTS:e,endPTS:s,startDTS:i,endDTS:r,partial:a};return}l.startPTS=Math.min(l.startPTS,e),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,i),l.endDTS=Math.max(l.endDTS,r)}}class Nr extends oi{constructor(t,e,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=i;const a=t.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo||this.fragment.type===K.SUBTITLE&&this.stats.loading.end>0)}}function $r(n,t){const e=Object.getPrototypeOf(n);if(e)return Object.getOwnPropertyDescriptor(e,t)||$r(e,t)}function Pl(n,t){const e=$r(n,t);e&&(e.enumerable=!0,Object.defineProperty(n,t,e))}function _l(n,t,e){return(t=Ol(t))in n?Object.defineProperty(n,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[t]=e,n}function ht(){return ht=Object.assign?Object.assign.bind():function(n){for(var t=1;t<arguments.length;t++){var e=arguments[t];for(var s in e)({}).hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},ht.apply(null,arguments)}function Ur(n,t){var e=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);t&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),e.push.apply(e,s)}return e}function W(n){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?Ur(Object(e),!0).forEach(function(s){_l(n,s,e[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(e)):Ur(Object(e)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(e,s))})}return n}function fs(n,t){if(n==null)return{};var e,s,i=Cl(n,t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);for(s=0;s<r.length;s++)e=r[s],t.indexOf(e)===-1&&{}.propertyIsEnumerable.call(n,e)&&(i[e]=n[e])}return i}function Cl(n,t){if(n==null)return{};var e={};for(var s in n)if({}.hasOwnProperty.call(n,s)){if(t.indexOf(s)!==-1)continue;e[s]=n[s]}return e}function wl(n,t){if(typeof n!="object"||!n)return n;var e=n[Symbol.toPrimitive];if(e!==void 0){var s=e.call(n,t);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(n)}function Ol(n){var t=wl(n,"string");return typeof t=="symbol"?t:t+""}function gs(n){switch(n.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:case R.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function Br(n){return n.details.startsWith("key")}function Gr(n){return Br(n)&&!!n.frag&&!n.frag.decryptdata}function Kr(n,t){const e=gs(t);return n.default[`${e?"timeout":"error"}Retry`]}function hi(n,t){const e=n.backoff==="linear"?1:Math.pow(2,t);return Math.min(e*n.retryDelayMs,n.maxRetryDelayMs)}function Vr(n){return W(W({},n),{errorRetry:null,timeoutRetry:null})}function Ge(n,t,e,s){if(!n)return!1;const i=s?.code,r=t<n.maxNumRetry&&(Ml(i)||!!e);return n.shouldRetry?n.shouldRetry(n,t,e,s,r):r}function Ml(n){return Ke(n)||!!n&&(n<400||n>499)}function Ke(n){return n===0&&navigator.onLine===!1}function Hr(n,t){return t>0&&n.loadError>0&&n.loadErrorTime!==0&&self.performance.now()-n.loadErrorTime>t}class be{constructor(t,e=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=s}sample(t,e){const s=Math.pow(this.alpha_,t);this.estimate_=e*(1-s)+s*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class xl{constructor(t,e,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new be(t),this.fast_=new be(e),this.defaultTTFB_=i,this.ttfb_=new be(t)}update(t,e){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==t&&(this.slow_=new be(t,s.getEstimate(),s.getTotalWeight())),i.halfLife!==e&&(this.fast_=new be(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new be(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){if(e<=0)return;const s=Math.min(this.minDelayMs_,e/1e5),i=8*e,r=Math.max(t,s)/1e3,a=i/r;this.fast_.sample(r,a),this.slow_.sample(r,a)}sampleTTFB(t){const e=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(s,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class xt{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${t}]:`;this.trace=fe,this.debug=e.debug.bind(null,s),this.log=e.log.bind(null,s),this.warn=e.warn.bind(null,s),this.info=e.info.bind(null,s),this.error=e.error.bind(null,s)}}const fe=function(){},Fl={trace:fe,debug:fe,log:fe,warn:fe,info:fe,error:fe};function di(){return ht({},Fl)}function Nl(n,t){const e=self.console[n];return e?e.bind(self.console,`${t?"["+t+"] ":""}[${n}] >`):fe}function Yr(n,t,e){return t[n]?t[n].bind(t):Nl(n,e)}const ci=di();function $l(n,t,e){const s=di();if(typeof console=="object"&&n===!0||typeof n=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=Yr(r,n,e)});try{s.log(`Debug logs enabled for "${t}" in hls.js version 1.7.4`)}catch{return di()}i.forEach(r=>{ci[r]=Yr(r,n)})}else ht(ci,s);return s}const at=ci;function le(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ul(n){return typeof self<"u"&&n===self.ManagedMediaSource}function Wr(n,t){const e=Object.keys(n),s=Object.keys(t),i=e.length,r=s.length;return!i||!r||i===r&&!e.some(a=>s.indexOf(a)===-1)}function Bl(n){return btoa(String.fromCharCode(...n))}function ms(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}const Gl="utf-16",ui="utf-16be",jr="utf-16le",ps="utf-8";function Kl(n,t={}){let e;ms(n)?e=new DataView(n):e=new DataView(n.buffer,n.byteOffset,n.byteLength);let s=0,{encoding:i}=t;if(!i){const h=e.getUint8(0),d=e.getUint8(1);h==239&&d==187&&e.getUint8(2)==191?(i=ps,s=3):h==254&&d==255?(i=ui,s=2):h==255&&d==254?(i=jr,s=2):i=ps}if(typeof TextDecoder<"u")return new TextDecoder(i).decode(e);const{byteLength:r}=e,a=i!==ui;let o="",l;for(;s<r;){switch(i){case ps:if(l=e.getUint8(s),l<128)s++;else if(l>=194&&l<=223)if(s+1<r){const h=e.getUint8(s+1);h>=128&&h<=191?(l=(l&31)<<6|h&63,s+=2):s++}else s++;else if(l>=224&&l<=239)if(s+2<=r-1){const h=e.getUint8(s+1),d=e.getUint8(s+2);h>=128&&h<=191&&d>=128&&d<=191?(l=(l&15)<<12|(h&63)<<6|d&63,s+=3):s++}else s++;else if(l>=240&&l<=244)if(s+3<=r-1){const h=e.getUint8(s+1),d=e.getUint8(s+2),c=e.getUint8(s+3);h>=128&&h<=191&&d>=128&&d<=191&&c>=128&&c<=191?(l=(l&7)<<18|(h&63)<<12|(d&63)<<6|c&63,s+=4):s++}else s++;else s++;break;case ui:case Gl:case jr:l=e.getUint16(s,a),s+=2;break}o+=String.fromCodePoint(l)}return o}function Vl(n){const t=typeof n=="string"?new URL(n):n;return t.origin+t.pathname.substring(0,t.pathname.lastIndexOf("/")+1)}function qr(n,t){if(n<0)return-qr(-n,t);const e=Math.pow(10,t);if(Math.abs(n*e%1-.5)<Number.EPSILON){const s=Math.floor(n*e);return(s%2===0?s:s+1)/e}else return Math.round(n*e)/e}function Hl(n,t){let e;try{e=new URL(n)}catch{return n}const s=new URL(t);if(e.origin!==s.origin)return n;const i=e.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1),a=Math.min(i.length,r.length);for(let o=0;o<a&&i[o]===r[o];o++)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+e.search+e.hash}function Xr(){try{return crypto.randomUUID()}catch{try{const n=URL.createObjectURL(new Blob),t=n.toString();return URL.revokeObjectURL(n),t.slice(t.lastIndexOf("/")+1)}catch{let n=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=(n+Math.random()*16)%16|0;return n=Math.floor(n/16),(t=="x"?e:e&3|8).toString(16)})}}}function fi(n,t){return t+10<=n.length&&n[t]===73&&n[t+1]===68&&n[t+2]===51&&n[t+3]<255&&n[t+4]<255&&n[t+6]<128&&n[t+7]<128&&n[t+8]<128&&n[t+9]<128}function vs(n,t){let e=0;return e=(n[t]&127)<<21,e|=(n[t+1]&127)<<14,e|=(n[t+2]&127)<<7,e|=n[t+3]&127,e}function Yl(n,t){return fi(n,t)&&vs(n,t+6)+10<=n.length-t}function zr(n,t){return t+10<=n.length&&n[t]===51&&n[t+1]===68&&n[t+2]===73&&n[t+3]<255&&n[t+4]<255&&n[t+6]<128&&n[t+7]<128&&n[t+8]<128&&n[t+9]<128}function Ve(n,t){const e=t;let s=0;for(;fi(n,t);){s+=10;const i=vs(n,t+6);s+=i,zr(n,t+10)&&(s+=10),t+=s}if(s>0)return n.subarray(e,e+s)}function Wl(n){return ms(n)?n:n.byteOffset==0&&n.byteLength==n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer}function gi(n,t=0,e=1/0){return jl(n,t,e,Uint8Array)}function jl(n,t,e,s){const i=ql(n);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const a=Xl(n)?n.byteOffset:0,o=(a+n.byteLength)/r,l=(a+t)/r,h=Math.floor(Math.max(0,Math.min(l,o)));return new s(i,h,Math.floor(Math.min(h+Math.max(e,0),o))-h)}function ql(n){return ms(n)?n:n.buffer}function Xl(n){return n&&ms(n.buffer)&&n.byteLength!==void 0&&n.byteOffset!==void 0}function Ft(n,t=!1){const e=t?n.indexOf(0):n.length,s=Kl(new DataView(n.buffer,n.byteOffset,e),{encoding:ps});return t?s:s.replace(/\0/g,"")}function zl(n){const t={key:n.type,description:"",data:"",mimeType:null,pictureType:null},e=3;if(n.size<2)return;if(n.data[0]!==e){console.log("Ignore frame with unrecognized character encoding");return}const s=n.data.subarray(1).indexOf(0);if(s===-1)return;const i=Ft(gi(n.data,1,s)),r=n.data[2+s],a=n.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=Ft(gi(n.data,3+s,a));let l;return i==="-->"?l=Ft(gi(n.data,4+s+a)):l=Wl(n.data.subarray(4+s+a)),t.mimeType=i,t.pictureType=r,t.description=o,t.data=l,t}function Ql(n){if(n.size<2)return;const t=Ft(n.data,!0),e=new Uint8Array(n.data.subarray(t.length+1));return{key:n.type,info:t,data:e.buffer}}function Jl(n){if(n.size<2)return;if(n.type==="TXXX"){let e=1;const{data:s}=n,i=Ft(s.subarray(e),!0);e+=i.length+1;const r=Ft(s.subarray(e));return{key:n.type,info:i,data:r}}const t=Ft(n.data.subarray(1));return{key:n.type,info:"",data:t}}function Zl(n){if(n.type==="WXXX"){if(n.size<2)return;let e=1;const s=Ft(n.data.subarray(e),!0);e+=s.length+1;const i=Ft(n.data.subarray(e));return{key:n.type,info:s,data:i}}const t=Ft(n.data);return{key:n.type,info:"",data:t}}function th(n){return n.type==="PRIV"?Ql(n):n.type[0]==="W"?Zl(n):n.type==="APIC"?zl(n):Jl(n)}function eh(n){const t=String.fromCharCode(n[0],n[1],n[2],n[3]),e=vs(n,4),s=10;return{type:t,size:e,data:n.subarray(s,s+e)}}const ys=10,sh=10;function Qr(n){let t=0;const e=[];for(;fi(n,t);){const s=vs(n,t+6);n[t+5]>>6&1&&(t+=ys),t+=ys;const i=t+s;for(;t+sh<i;){const r=eh(n.subarray(t)),a=th(r);a&&e.push(a),t+=r.size+ys}zr(n,t)&&(t+=ys)}return e}function Jr(n){return n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp"}function ih(n){if(n.data.byteLength===8){const t=new Uint8Array(n.data),e=t[3]&1;let s=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return s/=45,e&&(s+=4772185884e-2),Math.round(s)}}function mi(n){const t=Qr(n);for(const e of t)if(Jr(e))return ih(e)}function It(n){let t="";for(let e=0;e<n.length;e++){let s=n[e].toString(16);s.length<2&&(s="0"+s),t+=s}return t}function Zr(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function pi(n){return Uint8Array.from(atob(n),t=>t.charCodeAt(0))}function Vt(n){return String.fromCharCode.apply(null,n)}const Zt=Math.pow(2,32)-1,Q={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},tn={video:1,audio:2,id3:3,text:4};function en(n,t){const e=n[t]<<8|n[t+1];return e<0?65536+e:e}function V(n,t){const e=n[t]<<24|n[t+1]<<16|n[t+2]<<8|n[t+3];return e<0?4294967296+e:e}function sn(n,t){let e=V(n,t);return e*=Math.pow(2,32),e+=V(n,t+4),e}function Es(n,t){let e="";for(let s=t;s<n.length;s++)if(e+=String.fromCharCode(n[s]),n[s]===0)return e;return null}function vi(n,t){return n[t]<<24|n[t+1]<<16|n[t+2]<<8|n[t+3]}function Tt(n,t,e){n[t]=e>>24,n[t+1]=e>>16&255,n[t+2]=e>>8&255,n[t+3]=e&255}function rn(n,t,e){const s=t.byteOffset-n.byteOffset-8,i=8+e,r=t.byteLength+8-i;r<8||(Tt(n,s,i),Tt(n,s+i,r),Tt(n,s+i+4,Q.free))}function yi(n,t){return[n.byteOffset-t-8,n.byteOffset-t+n.byteLength]}function nn(n,t){t.sort((a,o)=>a[0]-o[0]);const e=t.reduce((a,[o,l])=>a+l-o,0),s=new Uint8Array(n.byteLength-e);let i=0,r=0;for(let a=0;a<t.length;a++){const[o,l]=t[a];s.set(n.subarray(i,o),r),r+=o-i,i=l}return s.set(n.subarray(i),r),{result:s,dropped:e,droppedBefore:a=>t.reduce((o,[l,h])=>h<=a?o+h-l:o,0)}}function rh(n){const t=J(n,["moov"]);if(t.length!==1||J(n,["moof"]).length)return null;const e=n.byteOffset,s=[],i=[];let r=!1;const a=J(t[0],["trak"]);for(let f=0;f<a.length;f++){const g=a[f],p=J(g,["mdia","hdlr"])[0];if((p?Vt(p.subarray(8,12)):"")==="vide"){r=!0;continue}const v=J(g,["tkhd"])[0];if(!v)return null;const E=v[0];i.push(V(v,E===0?12:20)),s.push(yi(g,e))}if(!r||!s.length)return null;const o=J(t[0],["mvex"])[0];let l=0;if(o){const f=J(o,["trex"]);for(let g=0;g<f.length;g++){const p=f[g];i.indexOf(V(p,4))!==-1&&(s.push(yi(p,e)),l+=p.byteLength+8)}}const{result:h,dropped:d,droppedBefore:c}=nn(n,s),u=t[0].byteOffset-e-8;if(Tt(h,u,t[0].byteLength+8-d),o&&l){const f=o.byteOffset-e-8;Tt(h,f-c(f),o.byteLength+8-l)}return h}function nh(n,t,e,s,i){if(e<1)return null;const r=J(n,["moof"]);if(r.length!==1)return null;const a=r[0],o=n.byteOffset,l=[],h=[],d=J(a,["traf"]);let c=!0;for(let p=0;p<d.length;p++){const v=d[p],E=J(v,["tfhd"])[0];if(!E)return null;V(E,4)===t?(l.push(v),V(E,0)&131072||(c=!1)):h.push(yi(v,o))}if(!l.length||h.length&&!c)return null;if(s!==void 0){let p=e;for(let E=0;E<l.length;E++){const y=l[E];let T=0;const S=J(y,["trun"]);for(let I=0;I<S.length;I++){const b=S[I],k=Math.min(p,V(b,4));if(k){Tt(n,b.byteOffset-o+4,k);const D=V(b,0)&16777215,C=(D&256?4:0)+(D&512?4:0)+(D&1024?4:0)+(D&2048?4:0);rn(n,b,8+(D&1?4:0)+(D&4?4:0)+k*C)}else Tt(n,b.byteOffset-o-4,Q.free);p-=k,T+=k}const A=J(y,["senc"])[0];A&&Tt(n,A.byteOffset-o+4,T);const L=J(y,["saiz"])[0];if(L){const I=L[1]<<16|L[2]<<8|L[3];let b=4;I&1&&(b+=8);const k=L[b];b+=1,Tt(n,L.byteOffset-o+b,T),rn(n,L,b+4+(k===0?T:0))}}const v=J(n,["mdat"]);if(v.length===1){const E=v[0].byteOffset-o-8;Tt(n,E,s-E)}}let u=n,f=0,g=()=>0;if(h.length){({result:u,dropped:f,droppedBefore:g}=nn(n,h)),Tt(u,a.byteOffset-o-8,a.byteLength+8-f);for(let p=0;p<l.length;p++){const v=l[p],E=g(v.byteOffset-o),y=J(v,["trun"]);for(let T=0;T<y.length;T++){const S=y[T];V(S,0)&1&&Tt(u,S.byteOffset-o-E+8,V(S,8)-f)}if(E){const T=J(v,["saio"]);for(let S=0;S<T.length;S++){const A=T[S],L=A[0]===0?4:8;let I=V(A,0)&1?12:4,b=V(A,I);for(I+=4;b--;I+=L){const k=I+L-4;Tt(u,A.byteOffset-o-E+k,V(A,k)-E)}}}}}if(i){const{durationOffset:p,value:v}=i;Tt(u,p-g(p),v)}return s!==void 0?u.subarray(0,s-f):u}function ah(n,t){const e=n.byteLength;for(let s=0;s<e;){const i=V(n,s);if(i>8&&V(n,s+4)===Q[t])return!0;s=i>1?s+i:e}return!1}function J(n,t){const e=[];return t.length&&an(n,t,0,0,n.byteLength,e),e}function an(n,t,e,s,i,r){const a=t[e];if(a?.length!==4)return;const o=a.charCodeAt(0),l=a.charCodeAt(1),h=a.charCodeAt(2),d=a.charCodeAt(3),c=t.length-1;for(let u=s;u<i;){const f=u+8<=i,g=u+4<=i?n[u]*16777216+(n[u+1]<<16|n[u+2]<<8|n[u+3]):V(n,u),p=g>1?u+g:i;if(f&&n[u+4]===o&&n[u+5]===l&&n[u+6]===h&&n[u+7]===d){const v=Math.min(p,i);e===c?r.push(n.subarray(u+8,v)):an(n,t,e+1,u+8,v,r)}u=p}}function oh(n){const t=[],e=n[0];let s=8;const i=V(n,s);s+=4;let r=0,a=0;e===0?(r=V(n,s),a=V(n,s+4),s+=8):(r=sn(n,s),a=sn(n,s+8),s+=16),s+=2;let o=n.length+a;const l=en(n,s);s+=2;for(let h=0;h<l;h++){let d=s;const c=V(n,d);d+=4;const u=c&2147483647;if((c&2147483648)>>>31===1)return at.warn("SIDX has hierarchical references (not supported)"),null;const f=V(n,d);d+=4,t.push({referenceSize:u,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+u-1}}),o+=u,d+=4,s=d}return{earliestPresentationTime:r,timescale:i,version:e,referencesCount:l,references:t}}function on(n){const t=[],e=J(n,["moov","trak"]);for(let s=0;s<e.length;s++){const i=e[s],r=J(i,["tkhd"])[0];if(r){let a=r[0];const o=V(r,a===0?12:20),l=J(i,["mdia","mdhd"])[0];if(l){a=l[0];const h=V(l,a===0?12:20),d=J(i,["mdia","hdlr"])[0];if(d){const c=Vt(d.subarray(8,12)),u={soun:ut.AUDIO,vide:ut.VIDEO}[c],f=J(i,["mdia","minf","stbl","stsd"])[0],g=lh(f);u?(t[o]={timescale:h,type:u,stsd:g},t[u]=W({timescale:h,id:o},g)):t[o]={timescale:h,type:c,stsd:g}}}}}return J(n,["moov","mvex","trex"]).forEach(s=>{const i=V(s,4),r=t[i];r&&(r.default={duration:V(s,12),sampleSize:V(s,16),flags:V(s,20)})}),t}function lh(n){const t=n.subarray(8),e=t.subarray(86),s=Vt(t.subarray(4,8));let i=s,r;const a=s==="enca"||s==="encv";if(a){const l=J(t,[s])[0].subarray(s==="enca"?28:78);J(l,["sinf"]).forEach(h=>{const d=J(h,["schm"])[0];if(d){const c=Vt(d.subarray(4,8));if(c==="cbcs"||c==="cenc"){const u=J(h,["frma"])[0];u&&(i=Vt(u))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const l=J(e,["avcC"])[0];l&&l.length>3&&(i+="."+Ss(l[1])+Ss(l[2])+Ss(l[3]),r=Ts(o==="avc1"?"dva1":"dvav",e));break}case"mp4a":{const l=J(t,[s])[0],h=J(l.subarray(28),["esds"])[0];if(h&&h.length>7){let d=4;if(h[d++]!==3)break;d=Ei(h,d),d+=2;const c=h[d++];if(c&128&&(d+=2),c&64&&(d+=h[d++]),h[d++]!==4)break;d=Ei(h,d);const u=h[d++];if(u===64)i+="."+Ss(u);else break;if(d+=12,h[d++]!==5)break;d=Ei(h,d);const f=h[d++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((h[d]&224)>>5)),i+="."+g}break}case"hvc1":case"hev1":{const l=J(e,["hvcC"])[0];if(l&&l.length>12){const h=l[1],d=["","A","B","C"][h>>6],c=h&31,u=V(l,2),f=(h&32)>>5?"H":"L",g=l[12],p=l.subarray(6,12);i+="."+d+c,i+="."+hh(u).toString(16).toUpperCase(),i+="."+f+g;let v="";for(let E=p.length;E--;){const y=p[E];(y||v)&&(v="."+y.toString(16).toUpperCase()+v)}i+=v}r=Ts(o=="hev1"?"dvhe":"dvh1",e);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=Ts(i,e)||i;break}case"vp09":{const l=J(e,["vpcC"])[0];if(l&&l.length>6){const h=l[4],d=l[5],c=l[6]>>4&15;i+="."+te(h)+"."+te(d)+"."+te(c)}break}case"av01":{const l=J(e,["av1C"])[0];if(l&&l.length>2){const h=l[1]>>>5,d=l[1]&31,c=l[2]>>>7?"H":"M",u=(l[2]&64)>>6,f=(l[2]&32)>>5,g=h===2&&u?f?12:10:u?10:8,p=(l[2]&16)>>4,v=(l[2]&8)>>3,E=(l[2]&4)>>2,y=l[2]&3;i+="."+h+"."+te(d)+c+"."+te(g)+"."+p+"."+v+E+y+"."+te(1)+"."+te(1)+"."+te(1)+".0",r=Ts("dav1",e)}break}}return{codec:i,encrypted:a,supplemental:r}}function Ts(n,t){const e=J(t,["dvvC"]),s=e.length?e[0]:J(t,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return n+"."+te(i)+"."+te(r)}}function hh(n){let t=0;for(let e=0;e<32;e++)t|=(n>>e&1)<<31-e;return t>>>0}function Ei(n,t){const e=t+5;for(;n[t++]&128&&t<e;);return t}function Ss(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function te(n){return(n<10?"0":"")+n}function dh(n,t){if(!n||!t)return;const e=t.keyId;e?.byteLength===16&&t.isCommonEncryption&&ln(n,(s,i)=>{const r=s.subarray(8,24);r.some(a=>a!==0)||(at.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${It(r)} -> ${It(e)}`),s.set(e,8))})}function ch(n){const t=[];return ln(n,e=>t.push(e.subarray(8,24))),t}function ln(n,t){J(n,["moov","trak"]).forEach(e=>{const s=J(e,["mdia","minf","stbl","stsd"])[0];if(!s)return;const i=s.subarray(8);let r=J(i,["enca"]);const a=r.length>0;a||(r=J(i,["encv"])),r.forEach(o=>{const l=a?o.subarray(28):o.subarray(78);J(l,["sinf"]).forEach(h=>{const d=hn(h);d&&t(d,a)})})})}function hn(n){const t=J(n,["schm"])[0];if(t){const e=Vt(t.subarray(4,8));if(e==="cbcs"||e==="cenc"){const s=J(n,["schi","tenc"])[0];if(s)return s}}}let dn;function uh(n){return typeof TextDecoder>"u"?Ft(n):(dn||(dn=new TextDecoder("utf-8"))).decode(n).replace(/\0/g,"")}function fh(n){const t=n.byteLength,e=[];for(let s=0;s<t;){const i=s+8<=t,r=s+4<=t?n[s]*16777216+(n[s+1]<<16|n[s+2]<<8|n[s+3]):V(n,s),a=r>1?s+r:t;if(i&&n[s+4]===109&&n[s+5]===111&&n[s+6]===111&&n[s+7]===102){const o=Math.min(a,t);for(let l=s+8;l<o;){const h=l+8<=o,d=l+4<=o?n[l]*16777216+(n[l+1]<<16|n[l+2]<<8|n[l+3]):V(n,l),c=d>1?l+d:o;if(h&&n[l+4]===116&&n[l+5]===114&&n[l+6]===97&&n[l+7]===102){const u=Math.min(c,o);let f,g;const p=[];for(let v=l+8;v<u;){const E=v+8<=u,y=v+4<=u?n[v]*16777216+(n[v+1]<<16|n[v+2]<<8|n[v+3]):V(n,v),T=y>1?v+y:u;if(E&&n[v+4]===116){const S=Math.min(T,u);n[v+5]===102&&n[v+6]===104&&n[v+7]===100?g||(g=n.subarray(v+8,S)):n[v+5]===102&&n[v+6]===100&&n[v+7]===116?f||(f=n.subarray(v+8,S)):n[v+5]===114&&n[v+6]===117&&n[v+7]===110&&p.push(n.subarray(v+8,S))}v=T}e.push({moofOffset:n.byteOffset+s,tfdt:f,tfhd:g,truns:p})}l=c}}s=a}return e}function gh(n,t,e,s,i=!0){return cn(n,t,s,i)}function mh(n,t,e,s,i=!1){const r=[],a=t.samples,o=cn(a,e,s,i,{isHEVCFlavor:He(t.codec),samples:r,timeOffset:n,timescale:t.timescale,trackId:t.id});return{samples:r,sampleData:{includeSampleDetails:i,tracks:o}}}function cn(n,t,e,s,i){const r={};let a=!1;const o=fh(n),l=n.byteLength;for(let c=0;c<o.length;c++){const{moofOffset:u,tfdt:f,tfhd:g,truns:p}=o[c],v=V(g,4),E=t[v];if(!E)continue;const y=r[v]||(r[v]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:E.timescale,type:E.type});let T;if(f){const F=f[0];T=V(f,4),F===1&&(T===Zt?e.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(T*=Zt+1,T+=V(f,8))),$(T)&&(!$(y.start)||T<y.start)&&(y.start=T),i&&$(T)&&(i.timeOffset=T/i.timescale)}const S=i?.trackId===v&&E.type===ut.VIDEO,A=E.default,L=V(g,0)&16777215;let I=A?.duration||0,b,k=A?.sampleSize||0,D=8;L&1&&(D+=8),L&2&&(D+=4),L&8&&(I=V(g,D),b=g.byteOffset-n.byteOffset+D,D+=4),L&16&&(k=V(g,D));let C=0;const w=(L&1)!==0,N=!w&&(L&131072)!==0;w?(C=V(g,8),C*=Math.pow(2,32),C+=V(g,12)):N&&(C=u);let U=T||0,G=0,M=I;for(let F=0;F<p.length;F++){const x=p[F],_=V(x,4),O=y.sampleCount;y.sampleCount+=_;const H=x[3]&1;let j=0;const tt=x[3]&4,X=x[2]&1,Z=x[2]&2,rt=x[2]&4,Rt=x[2]&8;let et=8;H&&(j=vi(x,et),et+=4),tt&&(!(x[et+1]&1)&&y.keyFrameIndex===void 0&&(y.keyFrameIndex=O),et+=4);let dt=C+j;if(!s&&x[1]===0&&x[2]===6&&x[3]===1){var h,d;const it=U,St=dt,At=et;let nt=-1,yt=0,ct=0,$t=(h=i?.timeOffset)!=null?h:0;const Jt=I/((d=i?.timescale)!=null?d:1),ue=i?.isHEVCFlavor===!0,ni=ue?2:1;for(let Ut=0;Ut<_;Ut++){const Bt=x[et]===0?x[et+1]<<16|x[et+2]<<8|x[et+3]:V(x,et),Kt=nt===-1&&y.keyFrameIndex===void 0&&(x[et+5]&1)===0;et+=8;const Ee=dt+Bt;if(S){if(Bt>0){let Ct=dt;do{const Re=n[Ct]===0?n[Ct+1]<<16|n[Ct+2]<<8|n[Ct+3]:V(n,Ct);Ct+=4;const cs=n[Ct],$e=ue?cs>>1&63:cs&31;(ue?$e===39||$e===40:$e===6)&&Ye(n.subarray(Ct,Ct+Re),ni,$t,i.samples),Ct+=Re}while(Ct<Ee)}$t+=Jt}dt=Ee,Kt&&(nt=Ut,yt=dt)}if(dt<=l)ct=_;else{let Ut=St,Bt=At;for(let Kt=0;Kt<_;Kt++){const Ee=x[Bt]===0?x[Bt+1]<<16|x[Bt+2]<<8|x[Bt+3]:V(x,Bt);if(Ut+=Ee,Ut>l)break;ct=Kt+1,Bt+=8}}if(S&&(i.timeOffset=$t),nt!==-1&&yt<=l&&y.keyFrameIndex===void 0&&(y.keyFrameIndex=nt,y.keyFrameStart=it+nt*I),ct){(!$(y.ptsMin)||it<y.ptsMin)&&(y.ptsMin=it);const Ut=it+ct*I;(!$(y.ptsMax)||Ut>y.ptsMax)&&(y.ptsMax=Ut)}const ds=I*_;U=it+ds,G+=ds;continue}let Qt,z;s&&(Qt=[],z={sampleOffset:dt,samples:Qt,defaultSampleDurationOffset:b},dt<=l&&y.trun.push(z));let pt;for(let it=0;it<_;it++){let St;X?(s&&(St=x.byteOffset-n.byteOffset+et),M=V(x,et),et+=4):M=I,Z?(pt=V(x,et),et+=4):pt=k;let At,nt;rt&&(nt=x[et+1]&1?1:0,s&&(At={isNonSync:nt,dependsOn:(x[et]&3)===1?1:2}),et+=4);let yt=0;if(Rt&&(yt=x[0]===0?V(x,et):vi(x,et),et+=4),S){let ct=dt,$t=0;for(;$t<pt;){const Jt=V(n,ct);ct+=4,un(i.isHEVCFlavor,n[ct])&&Ye(n.subarray(ct,ct+Jt),i.isHEVCFlavor?2:1,i.timeOffset+yt/i.timescale,i.samples),ct+=Jt,$t+=Jt+4}i.timeOffset+=M/i.timescale}if(dt+=pt,dt<=l){z&&St!==void 0&&(z.lastSampleDurationOffset=St),nt===0&&y.keyFrameIndex===void 0&&(y.keyFrameIndex=it,y.keyFrameStart=U);const ct=U+yt;(!$(y.ptsMin)||ct<y.ptsMin)&&(y.ptsMin=ct),(!$(y.ptsMax)||ct+M>y.ptsMax)&&(y.ptsMax=ct+M),Qt&&(Qt[it]={cts:yt,duration:M,flags:At,size:pt})}U+=M,G+=M}!G&&I&&(G+=I*_)}y.duration+=G,y.duration&&(a=!0)}if(!a){let c=1/0,u=0;const f=J(n,["sidx"]);for(let g=0;g<f.length;g++){const p=oh(f[g]);if(p!=null&&p.references){c=Math.min(c,p.earliestPresentationTime/p.timescale);const v=p.references.reduce((E,y)=>E+y.info.duration||0,0);u=Math.max(u,v+p.earliestPresentationTime/p.timescale)}}u&&$(u)&&Object.keys(r).forEach(g=>{r[g].duration||(r[g].duration=u*r[g].timescale-r[g].start)})}return r}function ph(n){const t={valid:null,remainder:null},e=J(n,["moof"]);if(e.length<2)return t.remainder=n,t;const s=e[e.length-1];return t.valid=n.slice(0,s.byteOffset-8),t.remainder=n.slice(s.byteOffset-8),t}function Gt(n,t){const e=new Uint8Array(n.length+t.length);return e.set(n),e.set(t,n.length),e}function vh(n,t){const e=[],s=t.samples,i=t.timescale,r=t.id;let a=!1;return J(s,["moof"]).map(o=>{const l=o.byteOffset-8;J(o,["traf"]).map(h=>{const d=J(h,["tfdt"]).map(c=>{const u=c[0];let f=V(c,4);return u===1&&(f*=Math.pow(2,32),f+=V(c,8)),f/i})[0];return d!==void 0&&(n=d),J(h,["tfhd"]).map(c=>{const u=V(c,4),f=V(c,0)&16777215,g=(f&1)!==0;let p=0;const v=(f&2)!==0,E=(f&8)!==0;let y=0;const T=(f&16)!==0;let S=0;const A=(f&32)!==0,L=!g&&(f&131072)!==0;let I=8;u===r&&(g?(p=V(c,I),I+=4,p*=Math.pow(2,32),p+=V(c,I),I+=4):L&&(p=l),v&&(I+=4),E&&(y=V(c,I),I+=4),T&&(S=V(c,I),I+=4),A&&(I+=4),t.type==="video"&&(a=He(t.codec)),J(h,["trun"]).map(b=>{const k=b[0],D=V(b,0)&16777215,C=(D&1)!==0;let w=0;const N=(D&4)!==0,U=(D&256)!==0;let G=0;const M=(D&512)!==0;let F=0;const x=(D&1024)!==0,_=(D&2048)!==0;let O=0;const H=V(b,4);let j=8;C&&(w=V(b,j),j+=4),N&&(j+=4);let tt=p+w;for(let X=0;X<H;X++){if(U?(G=V(b,j),j+=4):G=y,M?(F=V(b,j),j+=4):F=S,x&&(j+=4),_&&(k===0?O=V(b,j):O=vi(b,j),j+=4),t.type===ut.VIDEO){let Z=0;for(;Z<F;){const rt=V(s,tt);if(tt+=4,un(a,s[tt])){const Rt=s.subarray(tt,tt+rt);Ye(Rt,a?2:1,n+O/i,e)}tt+=rt,Z+=rt+4}}n+=G/i}}))})})}),e}function He(n){if(!n)return!1;const t=n.substring(0,4);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function un(n,t){if(n){const e=t>>1&63;return e===39||e===40}else return(t&31)===6}function Ye(n,t,e,s){const i=fn(n);let r=0;r+=t;let a=0,o=0,l=0;for(;r<i.length;){a=0;do{if(r>=i.length)break;l=i[r++],a+=l}while(l===255);o=0;do{if(r>=i.length)break;l=i[r++],o+=l}while(l===255);const h=i.length-r;let d=r;if(o<h)r+=o;else if(o>h){at.error(`Malformed SEI payload. ${o} is too small, only ${h} bytes left to parse.`);break}if(a===4){if(i[d++]===181){const c=en(i,d);if(d+=2,c===49){const u=V(i,d);if(d+=4,u===1195456820){const f=i[d++];if(f===3){const g=i[d++],p=31&g,v=64&g,E=v?2+p*3:0,y=new Uint8Array(E);if(v){y[0]=g;for(let T=1;T<E;T++)y[T]=i[d++]}s.push({type:f,payloadType:a,pts:e,bytes:y})}}}}}else if(a===5&&o>16){const c=[];for(let g=0;g<16;g++){const p=i[d++].toString(16);c.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&c.push("-")}const u=o-16,f=new Uint8Array(u);for(let g=0;g<u;g++)f[g]=i[d++];s.push({payloadType:a,pts:e,uuid:c.join(""),userData:uh(f),userDataBytes:f})}}}function fn(n){const t=n.byteLength;let e,s=n.indexOf(3,3);for(;s!==-1;)n[s-1]===0&&n[s-2]===0&&(e||(e=[])).push(s),s=n.indexOf(3,s+1);if(!e)return n;const i=t-e.length,r=new Uint8Array(i);let a=0,o=0;for(let l=0;l<i;o++,l++)o===e[a]&&(o++,a++),r[l]=n[o];return r}function yh(n){const t=n[0];let e="",s="",i=0,r=0,a,o=0,l=0,h=4;if(t===0){const c=Es(n,h),u=c!==null?Es(n,h+c.length):null;c!==null&&u!==null?(e=c,s=u,h+=c.length+u.length,i=V(n,h),h+=4,r=V(n,h),h+=4,o=V(n,h),h+=4,l=V(n,h),h+=4):(at.warn(`Unterminated ${c===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),h=n.length)}else if(t===1){i=V(n,h),h+=4;const c=V(n,h);h+=4;const u=V(n,h);h+=4,a=2**32*c+u,Rl(a)||(a=Number.MAX_SAFE_INTEGER,at.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=V(n,h),h+=4,l=V(n,h),h+=4;const f=Es(n,h),g=f!==null?Es(n,h+f.length):null;f!==null&&(e=f,h+=f.length),g!==null?(s=g,h+=g.length):(at.warn(`Unterminated ${f===null?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${f===null?"strings and payload":"value and payload"}`),h=n.length)}const d=n.subarray(h,n.byteLength);return{schemeIdUri:e,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:l,payload:d}}function Eh(n,...t){const e=t.length;let s=8,i=e;for(;i--;)s+=t[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(n,4),i=0,s=8;i<e;i++)r.set(t[i],s),s+=t[i].byteLength;return r}function Th(n,t,e){if(n.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),t.length>0&&new DataView(r.buffer).setUint32(0,t.length,!1)):r=new Uint8Array;const a=new Uint8Array(4);return e.byteLength>0&&new DataView(a.buffer).setUint32(0,e.byteLength,!1),Eh([112,115,115,104],new Uint8Array([s,0,0,0]),n,r,i,a,e)}function gn(n){const t=[];if(n instanceof ArrayBuffer){const e=n.byteLength;let s=0;for(;s+32<e;){const i=new DataView(n,s),r=Ah(i);t.push(r),s+=r.size}}return t}function Sh(n){const t=[];for(let e=0;e<n.length;){const s=n[e++],i=s&7;if(i===0){for(;n[e++]&128;);continue}if(i!==2){e+=i===1?8:4;continue}let r=0;for(let a=0,o=128;o&128;a+=7)r|=((o=n[e++])&127)<<a;if(s>>3===2)if(r===32){const a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=parseInt(String.fromCharCode(n[e+o*2],n[e+o*2+1]),16);t.push(a)}else r===16&&t.push(n.subarray(e,e+16));e+=r}return t}function Ah(n){const t=n.getUint32(0),e=n.byteOffset,s=n.byteLength;if(s<t)return{offset:e,size:s};if(n.getUint32(4)!==1886614376)return{offset:e,size:t};const i=n.getUint32(8)>>>24;if(i!==0&&i!==1)return{offset:e,size:t};const r=n.buffer,a=It(new Uint8Array(r,e+12,16));let o=null,l=null,h=0;if(i===0)h=28;else{const c=n.getUint32(28);if(!c||s<32+c*16)return{offset:e,size:t};o=[];for(let u=0;u<c;u++)o.push(new Uint8Array(r,e+32+u*16,16));h=32+c*16}if(!h)return{offset:e,size:t};const d=n.getUint32(h);return t-32<d?{offset:e,size:t}:(l=new Uint8Array(r,e+h+4,d),i===0&&(o=Sh(l)),{version:i,systemId:a,kids:o,data:l,offset:e,size:t})}const De=mn("userAgent"),Ih=mn("vendor");let Ti,Si,Ai;function mn(n){try{return navigator[n]||""}catch{}return""}function Lh(){if(Ai===void 0){const n=De.match(/Safari\/(\d+)/i);Ai=n?parseInt(n[1]):0}return Ai}function We(){if(Ti===void 0){const n=De.match(/Chrome\/(\d+)/i);Ti=n?parseInt(n[1]):0}return Ti}function Rh(){if(Si===void 0){const n=De.match(/Firefox\/(\d+)/i);Si=n?parseInt(n[1]):0}return Si}function pn(){return/\(Windows.+Firefox\//i.test(De)}function bh(){return Ih.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(De)}function Dh(){return/Android/.test(De)}const ke={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},image:{mjpg:1}};function Ii(n,t){const e=ke[t];return!!e&&!!e[n.slice(0,4)]}function je(n,t,e=!0){return!n.split(",").some(s=>!Li(s,t,e))}function Li(n,t,e=!0){var s;const i=le(e);return(s=i?.isTypeSupported(qe(n,t)))!=null?s:!1}function qe(n,t){return`${t}/mp4;codecs=${n}`}function vn(n){if(n){const t=n.substring(0,4);return ke.video[t]}return 2}function As(n){const t=pn();return n.split(",").reduce((e,s)=>{const i=t&&He(s)?9:ke.video[s];return i?(i*2+e)/(e?3:2):(ke.audio[s]+e)/(e?2:1)},0)}const Ri={};function kh(n,t=!0){if(Ri[n])return Ri[n];const e={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[n];for(let i=0;i<e.length;i++){var s;if(Li(e[i],"audio",t))return Ri[n]=e[i],e[i];if(e[i]==="mp3"&&(s=le(t))!=null&&s.isTypeSupported("audio/mpeg"))return""}return n}const Ph=/flac|opus|mp4a\.40\.34/i;function Is(n,t=!0){return n.replace(Ph,e=>kh(e.toLowerCase(),t))}function _h(n,t){const e=[];if(n){const s=n.split(",");for(let i=0;i<s.length;i++)Ii(s[i],"video")||e.push(s[i])}return t&&e.push(t),e.join(",")}function Ls(n,t){if(n&&(n.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(n)!==-1)&&(yn(n,"audio")||yn(n,"video")))return n;if(t){const e=t.split(",");if(e.length>1){if(n){for(let s=e.length;s--;)if(e[s].substring(0,4)===n.substring(0,4))return e[s]}return e[0]}}return t||n}function yn(n,t){return Ii(n,t)&&Li(n,t)}function Ch(n){const t=n.split(",");for(let e=0;e<t.length;e++){const s=t[e].split(".");s.length>2&&s[0]==="avc1"&&(t[e]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return t.join(",")}function wh(n){if(n.startsWith("av01.")){const t=n.split("."),e=["0","111","01","01","01","0"];for(let s=t.length;s>4&&s<10;s++)t[s]=e[s-4];return t.join(".")}return n}function En(n){const t=le(n)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function bi(n){return n.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Oh={supported:!0,powerEfficient:!0,smooth:!0},Mh={supported:!1,smooth:!1,powerEfficient:!1},Tn={supported:!0,configurations:[],decodingInfoResults:[Oh]};function Sn(n,t){return{supported:!1,configurations:t,decodingInfoResults:[Mh],error:n}}function xh(n,t,e,s,i,r){const a=n.videoCodec,o=n.audioCodec?n.audioGroups:null,l=r?.audioCodec,h=r?.channels,d=h?parseInt(h):l?1/0:2;let c=null;if(o!=null&&o.length)try{o.length===1&&o[0]?c=t.groups[o[0]].channels:c=o.reduce((u,f)=>{if(f){const g=t.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(p=>{u[p]=(u[p]||0)+g.channels[p]})}return u},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(u=>He(u))||n.width>1920&&n.height>1088||n.height>1920&&n.width>1088||n.frameRate>Math.max(s,30)||n.videoRange!=="SDR"&&n.videoRange!==e||n.bitrate>Math.max(i,8e6))||!!c&&$(d)&&Object.keys(c).some(u=>parseInt(u)>d)}function An(n,t,e,s={}){const i=n.videoCodec;if(!i&&!n.audioCodec||!e)return Promise.resolve(Tn);const r=[],a=Fh(n),o=a.length,l=Nh(n,t,o>0),h=l.length;for(let d=o||1*h||1;d--;){const c={type:"media-source"};if(o&&(c.video=a[d%o]),h){c.audio=l[d%h];const u=c.audio.bitrate;c.video&&u&&(c.video.bitrate-=u)}r.push(c)}if(i){const d=navigator.userAgent;if(i.split(",").some(c=>He(c))&&pn())return Promise.resolve(Sn(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${d})`),r))}return Promise.all(r.map(d=>{const c=$h(d);return s[c]||(s[c]=e.decodingInfo(d))})).then(d=>({supported:!d.some(c=>!c.supported),configurations:r,decodingInfoResults:d})).catch(d=>({supported:!1,configurations:r,decodingInfoResults:[],error:d}))}function Fh(n){var t;const e=(t=n.videoCodec)==null?void 0:t.split(","),s=Ln(n),i=n.width||640,r=n.height||480,a=n.frameRate||30,o=n.videoRange.toLowerCase();return e?e.map(l=>{const h={contentType:qe(wh(l),"video"),width:i,height:r,bitrate:s,framerate:a};return o!=="sdr"&&(h.transferFunction=o),h}):[]}function Nh(n,t,e){var s;const i=(s=n.audioCodec)==null?void 0:s.split(","),r=Ln(n);return i&&n.audioGroups?n.audioGroups.reduce((a,o)=>{var l;const h=o?(l=t.groups[o])==null?void 0:l.tracks:null;return h?h.reduce((d,c)=>{if(c.groupId===o){const u=parseFloat(c.channels||"");i.forEach(f=>{const g={contentType:qe(f,"audio"),bitrate:e?In(f,r):r};u&&(g.channels=""+u),d.push(g)})}return d},a):a},[]):[]}function In(n,t){if(t<=1)return 1;let e=128e3;return n==="ec-3"?e=768e3:n==="ac-3"&&(e=64e4),Math.min(t/2,e)}function Ln(n){return Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)/1e3)*1e3||1}function $h(n){let t="";const{audio:e,video:s}=n;if(s){const i=bi(s.contentType);t+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(e){const i=bi(e.contentType);t+=`${s?"_":""}${i}_c${e.channels}`}return t}function ge(n,t,e){const s=encodeURIComponent(t),i=`${s}=${encodeURIComponent(e)}`;let r=!1;const a=[];n.search.substring(1).split("&").forEach(o=>{o===s||o.startsWith(s+"=")?r||(a.push(i),r=!0):o&&a.push(o)}),r||a.push(i),n.search=a.join("&")}const Di=["NONE","TYPE-0","TYPE-1",null];function Uh(n){return Di.indexOf(n)>-1}const Rs=["SDR","PQ","HLG"];function Bh(n){return!!n&&Rs.indexOf(n)>-1}var Xe={No:"",Yes:"YES",v2:"v2"};function Rn(n){const{canSkipUntil:t,canSkipDateRanges:e,age:s}=n,i=s<t/2;return t&&i?e?Xe.v2:Xe.Yes:Xe.No}class ki{constructor(t,e,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=s}addDirectives(t){const e=new self.URL(t);return this.msn!==void 0&&ge(e,"_HLS_msn",this.msn.toString()),this.part!==void 0&&ge(e,"_HLS_part",this.part.toString()),this.skip&&ge(e,"_HLS_skip",this.skip),e.href}}class Pe{constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,"imageCodec"in t&&(this.imageCodec=t.imageCodec),this.codecSet=[t.videoCodec,t.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const s=(e=t.supplemental)==null?void 0:e.videoCodec;s&&s!==t.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}"iframes"in t&&t.iframes?this.iframes=!0:(this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return bn(this._audioGroups,t)}hasSubtitleGroup(t){return bn(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e){if(t==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(e)===-1&&s.push(e)}else if(t==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(e)===-1&&s.push(e)}}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return(t=this.audioGroups)==null?void 0:t[0]}get textGroupId(){var t;return(t=this.subtitleGroups)==null?void 0:t[0]}addFallback(){}}function bn(n,t){return!t||!n?!1:n.indexOf(t)!==-1}function Gh(){if(typeof matchMedia=="function"){const n=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(n.media!==t.media)return n.matches===!0}return!1}function Kh(n,t){let e=!1,s=[];if(n&&(e=n!=="SDR",s=[n]),t){s=t.allowedVideoRanges||Rs.slice(0);const i=s.join("")!=="SDR"&&!t.videoCodec;e=t.preferHDR!==void 0?t.preferHDR:i&&Gh(),e||(s=["SDR"])}return{preferHDR:e,allowedVideoRanges:s}}const Vh=n=>{const t=new WeakSet;return(e,s)=>{if(n&&(s=n(e,s)),typeof s=="object"&&s!==null){if(t.has(s))return;t.add(s)}return s}},ft=(n,t)=>JSON.stringify(n,Vh(t));function Hh(n,t,e,s,i){const r=Object.keys(n),a=s?.channels,o=s?.audioCodec,l=i?.videoCodec,h=a&&parseInt(a)===2;let d=!1,c=!1,u=1/0,f=1/0,g=1/0,p=1/0,v=0,E=[];const{preferHDR:y,allowedVideoRanges:T}=Kh(t,i);for(let I=r.length;I--;){const b=n[r[I]];d||(d=b.channels[2]>0),u=Math.min(u,b.minHeight),f=Math.min(f,b.minFramerate),g=Math.min(g,b.minBitrate),T.filter(k=>b.videoRanges[k]>0).length>0&&(c=!0)}u=$(u)?u:0,f=$(f)?f:0;const S=Math.max(1080,u),A=Math.max(30,f);g=$(g)?g:e,e=Math.max(g,e),c||(t=void 0);const L=r.length>1;return{codecSet:r.reduce((I,b)=>{const k=n[b];if(b===I)return I;if(E=c?T.filter(D=>k.videoRanges[D]>0):[],L){if(k.minBitrate>e)return ee(b,`min bitrate of ${k.minBitrate} > current estimate of ${e}`),I;if(!k.hasDefaultAudio)return ee(b,"no renditions with default or auto-select sound found"),I;if(o&&b.indexOf(o.substring(0,4))%5!==0)return ee(b,`audio codec preference "${o}" not found`),I;if(a&&!h){if(!k.channels[a])return ee(b,`no renditions with ${a} channel sound found (channels options: ${Object.keys(k.channels)})`),I}else if((!o||h)&&d&&k.channels[2]===0)return ee(b,"no renditions with stereo sound found"),I;if(k.minHeight>S)return ee(b,`min resolution of ${k.minHeight} > maximum of ${S}`),I;if(k.minFramerate>A)return ee(b,`min framerate of ${k.minFramerate} > maximum of ${A}`),I;if(!E.some(D=>k.videoRanges[D]>0))return ee(b,`no variants with VIDEO-RANGE of ${ft(E)} found`),I;if(l&&b.indexOf(l.substring(0,4))%5!==0)return ee(b,`video codec preference "${l}" not found`),I;if(k.maxScore<v)return ee(b,`max score of ${k.maxScore} < selected max of ${v}`),I}return I&&(As(b)>=As(I)||k.fragmentError>n[I].fragmentError)?I:(p=k.minIndex,v=k.maxScore,b)},void 0),videoRanges:E,preferHDR:y,minFramerate:f,minBitrate:g,minIndex:p}}function ee(n,t){at.log(`[abr] start candidates with "${n}" ignored because ${t}`)}function Dn(n){return n.reduce((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(e);const i=e.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Yh(n,t,e,s){return n.slice(e,s+1).reduce((i,r,a)=>{if(!r.codecSet)return i;const o=r.audioGroups;let l=i[r.codecSet];l||(i[r.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,r.bitrate);const h=Math.min(r.height,r.width);return l.minHeight=Math.min(l.minHeight,h),l.minFramerate=Math.min(l.minFramerate,r.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,r.score),l.fragmentError+=r.fragmentError,l.videoRanges[r.videoRange]=(l.videoRanges[r.videoRange]||0)+1,o&&o.forEach(d=>{if(!d)return;const c=t.groups[d];c&&(l.hasDefaultAudio=l.hasDefaultAudio||t.hasDefaultAudio?c.hasDefault:c.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(c.channels).forEach(u=>{l.channels[u]=(l.channels[u]||0)+c.channels[u]}))}),i},{})}function kn(n){if(!n)return n;const{lang:t,assocLang:e,characteristics:s,channels:i,audioCodec:r}=n;return{lang:t,assocLang:e,characteristics:s,channels:i,audioCodec:r}}function se(n,t,e){if("attrs"in n){const s=t.indexOf(n);if(s!==-1)return s}for(let s=0;s<t.length;s++){const i=t[s];if(Te(n,i,e))return s}return-1}function Te(n,t,e){const{groupId:s,name:i,lang:r,assocLang:a,default:o}=n,l=n.forced;return(s===void 0||t.groupId===s)&&(i===void 0||t.name===i)&&(r===void 0||Wh(r,t.lang))&&(a===void 0||t.assocLang===a)&&(o===void 0||t.default===o)&&(l===void 0||t.forced===l)&&(!("characteristics"in n)||jh(n.characteristics||"",t.characteristics))&&(e===void 0||e(n,t))}function Wh(n,t="--"){return n.length===t.length?n===t:n.startsWith(t)||t.startsWith(n)}function jh(n,t=""){const e=n.split(","),s=t.split(",");return e.length===s.length&&!e.some(i=>s.indexOf(i)===-1)}function Se(n,t){const{audioCodec:e,channels:s}=n;return(e===void 0||(t.audioCodec||"").substring(0,4)===e.substring(0,4))&&(s===void 0||s===(t.channels||"2"))}function qh(n,t,e,s,i){const r=t[s],a=t.reduce((c,u,f)=>{const g=u.uri;return(c[g]||(c[g]=[])).push(f),c},{})[r.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=r.videoRange,l=r.frameRate,h=r.codecSet.substring(0,4),d=Pn(t,s,c=>{if(c.videoRange!==o||c.frameRate!==l||c.codecSet.substring(0,4)!==h)return!1;const u=c.audioGroups,f=e.filter(g=>ze(g.groupId,u));return se(n,f,i)>-1});return d>-1?d:Pn(t,s,c=>{const u=c.audioGroups,f=e.filter(g=>ze(g.groupId,u));return se(n,f,i)>-1})}function Pn(n,t,e){for(let s=t;s>-1;s--)if(e(n[s]))return s;for(let s=t+1;s<n.length;s++)if(e(n[s]))return s;return-1}function bs(n,t){var e;return!!n&&n!==((e=t.loadLevelObj)==null?void 0:e.uri)}function ze(n,t){return t?t.indexOf(n)!==-1:!0}function _n(n,t){if(t||n){const e=ht({},t);return n&&(n.videoCodec&&(e.videoCodec=n.videoCodec),n.videoRange&&(e.allowedVideoRanges=[n.videoRange])),e}}class Cn extends xt{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var s;const{fragCurrent:i,partCurrent:r,hls:a}=this;if(!a)return;const{autoLevelEnabled:o,media:l}=a;if(!i||!l)return;const h=performance.now(),d=r?r.stats:i.stats,c=r?r.duration:i.duration,u=h-d.loading.start,f=a.minAutoLevel,g=i.level,p=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const v=p>-1&&p!==g,E=!!e||v;if(!E&&(l.paused||!l.playbackRate||!l.readyState))return;const y=a.mainForwardBufferInfo;if(!E&&y===null)return;const T=this.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(u<=Math.max(T,1e3*(c/(S*2))))return;const A=y?y.len/S:0,L=d.loading.first?d.loading.first-d.loading.start:-1,I=d.loaded&&L>-1,b=this.getBwEstimate(),k=a.levels,D=k[g],C=Math.max(d.loaded,Math.round(c*(i.bitrate||D.averageBitrate)/8));let w=I?u-L:u;w<1&&I&&(w=Math.min(u,d.loaded*8/b));const N=I?d.loaded*1e3/w:0,U=T/1e3,G=N?(C-d.loaded)/N:C*8/b+U;if(G<=A)return;const M=N?N*8:b,F=((s=e?.details||a.latestLevelDetails)==null?void 0:s.live)===!0,x=a.config.abrBandWidthUpFactor;let _=Number.POSITIVE_INFINITY,O;for(O=g-1;O>f;O--){const X=k[O].maxBitrate,Z=!k[O].details||F;if(_=this.getTimeToLoadFrag(U,M,c*X,Z),_<Math.min(A,c+U))break}if(_>=G||_>c*10)return;I?this.bwEstimator.sample(u-Math.min(T,L),d.loaded):this.bwEstimator.sampleTTFB(u);const H=k[O].maxBitrate;this.getBwEstimate()*x>H&&(this.firstAutoFloor=Math.min(O,a.firstLevel),this.resetEstimator(H));const j=this.findBestLevel(H,f,O,0,A,1,1);j>-1&&(O=j),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;
2
+ Fragment duration: ${i.duration.toFixed(3)}
3
+ Time to underbuffer: ${A.toFixed(3)} s
4
+ Estimated load time for current fragment: ${G.toFixed(3)} s
5
+ Estimated load time for down switch fragment: ${_.toFixed(3)} s
6
+ TTFB estimate: ${L|0} ms
7
+ Current BW estimate: ${$(b)?b|0:"Unknown"} bps
8
+ New BW estimate: ${this.getBwEstimate()|0} bps
9
+ Switching to level ${O} @ ${H|0} bps`),a.nextLoadLevel=a.nextAutoLevel=O,this.clearTimer();const tt=()=>{this.clearTimer();const X=this.hls;if(this.fragCurrent===i&&X.loadLevel===O&&O>0){const Z=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}
10
+ Fragment duration: ${i.duration.toFixed(3)} s
11
+ Time to underbuffer: ${Z.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,O>f){let rt=this.findBestLevel(X.levels[f].bitrate,f,O,0,Z,1,1);rt===-1&&(rt=f),X.nextLoadLevel=X.nextAutoLevel=rt,this.firstAutoFloor=Math.min(rt,X.firstLevel),this.resetEstimator(X.levels[rt].bitrate)}}};v||G>_*2?tt():this.timer=self.setInterval(tt,_*1e3),a.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:d})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){this.hls&&(t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const t=this.hls.config;return new xl(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const t=this.hls;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.FRAG_LOADING,this.onFragLoading,this),t.on(m.FRAG_LOADED,this.onFragLoaded,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this),t.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(m.LEVEL_LOADED,this.onLevelLoaded,this),t.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.FRAG_LOADING,this.onFragLoading,this),t.off(m.FRAG_LOADED,this.onFragLoaded,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this),t.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(m.LEVEL_LOADED,this.onLevelLoaded,this),t.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(m.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const s=e.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=e.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:{const s=e.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&li(s,i)){const a=performance.now(),o=r?r.stats:s.stats,l=a-o.loading.start,h=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&h>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(d,h),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(t,e,s,i){const r=t+s/e,a=i?t+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(t,e){const s=this.hls.config,{loading:i}=e.stats,r=i.end-i.first;$(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,e){var s;const{frag:i,part:r}=e,a=r?r.stats:i.stats;if(i.type===K.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,(s=this.hls)!=null&&s.config.abrMaxWithRealBitrate){const o=r?r.duration:i.duration,l=this.hls.levels[i.level],h=(l.loaded?l.loaded.bytes:0)+a.loaded,d=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:h,duration:d},l.realBitrate=Math.round(8*h/d)}if(i.bitrateTest){const o={stats:a,frag:i,part:r,id:i.type};this.onFragBuffered(m.FRAG_BUFFERED,o),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}onFragBuffered(t,e){const{frag:s,part:i}=e,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const a=((s.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=a/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(t){return t.type!==K.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:t}=this;if(!t)return 0;const{maxAutoLevel:e,minAutoLevel:s}=t,i=this.getBwEstimate(),r=this.getStarvationDelay(),a=t.config.maxStarvationDelay,o=this.findBestLevel(i,s,e,r/2,a,1,1);if(o>-1)return o;const l=t.firstLevel,h=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,d=Math.min(Math.max(l,s),e,h);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${d}`),d}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(t!==-1&&(!e||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const i=e&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const r=this.hls.levels;if(r.length>Math.max(t,i)&&r[t].loadError<=r[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this;if(!s)return-1;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:a}=s,o=e?e.duration:t?t.duration:0,l=this.getBwEstimate(),h=this.getStarvationDelay();let d=r.abrBandWidthFactor,c=r.abrBandWidthUpFactor;if(h){const v=this.findBestLevel(l,a,i,h,0,d,c);if(v>=0)return this.rebufferNotice=-1,v}let u=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!h){const v=this.bitrateTestDelay;v&&(u=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-v,this.info(`bitrate test took ${Math.round(1e3*v)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),d=c=1)}const f=this.findBestLevel(l,a,i,h,u,d,c);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${h?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=s.levels[a],p=s.loadLevelObj;return p&&g?.bitrate<p.bitrate?a:s.loadLevel}getStarvationDelay(){const t=this.hls,e=t?.media;if(!e)return 1/0;const s=e&&e.playbackRate!==0?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(t,e,s,i,r,a,o){const{hls:l,lastLoadedFragLevel:h,fragCurrent:d,partCurrent:c}=this;if(!l)return-1;const u=i+r,f=h===-1?l.firstLevel:h,{levels:g,allAudioTracks:p,loadLevel:v,latestLevelDetails:E,config:y}=l;if(g.length===1)return 0;const T=g[f],S=!!(E!=null&&E.live),A=v===-1||h===-1;let L,I="SDR",b=T?.frameRate||0;const{audioPreference:k,videoPreference:D}=y,C=this.audioTracksByGroup||(this.audioTracksByGroup=Dn(p));let w=-1;if(A){if(this.firstSelection!==-1)return this.firstSelection;const F=this.codecTiers||(this.codecTiers=Yh(g,C,e,s)),x=Hh(F,I,t,k,D),{codecSet:_,videoRanges:O,minFramerate:H,minBitrate:j,minIndex:tt,preferHDR:X}=x;w=tt,L=_,I=X?O[O.length-1]:O[0],b=H,t=Math.max(t,j),this.log(`picked start tier ${ft(x)}`)}else L=T?.codecSet,I=T?.videoRange;const N=c?c.duration:d?d.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,G=[];for(let F=s;F>=e;F--){var M;const x=g[F],_=F>f;if(!x)continue;if(y.useMediaCapabilities&&!x.supportedResult&&!x.supportedPromise){const Z=navigator.mediaCapabilities;typeof Z?.decodingInfo=="function"&&xh(x,C,I,b,t,k)?(x.supportedPromise=An(x,C,Z,this.supportedCache),x.supportedPromise.then(rt=>{if(!this.hls)return;x.supportedResult=rt;const Rt=this.hls.levels,et=Rt.indexOf(x);rt.error?this.warn(`MediaCapabilities decodingInfo error: "${rt.error}" for level ${et} ${ft(rt)}`):rt.supported?rt.decodingInfoResults.some(dt=>dt.smooth===!1||dt.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${et} not smooth or powerEfficient: ${ft(rt)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${et} ${ft(rt)}`),et>-1&&Rt.length>1&&(this.log(`Removing unsupported level ${et}`),this.hls.removeLevel(et),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(rt=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${rt}`)})):x.supportedResult=Tn}if((L&&x.codecSet!==L||I&&x.videoRange!==I||_&&b>x.frameRate||!_&&b>0&&b<x.frameRate||(M=x.supportedResult)!=null&&(M=M.decodingInfoResults)!=null&&M.some(Z=>Z.smooth===!1))&&(!A||F!==w)){G.push(F);continue}const O=x.details,H=(c?O?.partTarget:O?.averagetargetduration)||N||1;let j;_?j=o*t:j=a*t;const tt=N&&i>=N*2&&r===0?x.averageBitrate:x.maxBitrate,X=this.getTimeToLoadFrag(U,j,tt*H,!O||O.live);if(j>=tt&&(F===h||x.loadError===0&&x.fragmentError===0||Hr(x,y.errorPenaltyExpireMs))&&(X<=U||!$(X)||S&&!this.bitrateTestDelay||X<u)){const Z=this.forcedAutoLevel;return F!==v&&(Z===-1||Z!==v)&&(G.length&&this.trace(`Skipped level(s) ${G.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[G[0]].codecs}" ${g[G[0]].videoRange}; not compatible with "${L}" ${I}`),this.info(`switch candidate:${f}->${F} adjustedbw(${Math.round(j)})-bitrate=${Math.round(j-tt)} ttfb:${U.toFixed(1)} avgDuration:${H.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${X.toFixed(1)} firstSelection:${A} codecSet:${x.codecSet} videoRange:${x.videoRange} hls.loadLevel:${v}`)),A&&(this.firstSelection=F),F}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){if(!this.hls)return-1;const{maxAutoLevel:e,minAutoLevel:s}=this.hls;return Math.min(Math.max(t,s),e)}}class Xh{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[e];i.push(t),i.length===1&&!s&&this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const s={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const s={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const s=(e=t[0])==null?void 0:e.label;s==="async-blocker"||s==="async-blocker-prepend"?(t[0].execute(),t.splice(0,1)):s==="block-audio"&&t.splice(0,1)})}insertNext(t,e){this.queues!==null&&this.queues[e].splice(1,0,...t)}unblockAudio(){var t;this.queues!==null&&((t=this.current("audio"))==null?void 0:t.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return this.queues===null?!1:this.queues.audio.some(t=>t.label==="block-audio")}executeNext(t){if(this.queues===null||this.tracks===null)return;const e=this.queues[t];if(e.length){const i=e[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const a=(s=this.tracks[t])==null?void 0:s.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues!==null&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return((e=this.queues)==null?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return t===null||e===null?"<destroyed>":`
12
+ ${this.list("video")}
13
+ ${this.list("audio")}
14
+ ${this.list("audiovideo")}}`}list(t){var e,s;return(e=this.queues)!=null&&e[t]||(s=this.tracks)!=null&&s[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const s=(e=this.tracks)==null?void 0:e[t],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(t){var e;return((e=this.queues)==null?void 0:e[t].map(s=>s.label).join(", "))||""}}const wn={search:function(n,t){let e=0,s=n.length-1,i=null,r=null;for(;e<=s;){i=(e+s)/2|0,r=n[i];const a=t(r);if(a>0)e=i+1;else if(a<0)s=i-1;else return r}return null}};function zh(n,t,e){if(t===null||!Array.isArray(n)||!n.length||!$(t))return null;const s=n[0].programDateTime;if(t<(s||0))return null;const i=n[n.length-1].endProgramDateTime;if(t>=(i||0))return null;for(let r=0;r<n.length;++r){const a=n[r];if(Jh(t,e,a))return a}return null}function _e(n,t,e=0,s=0,i=.005){let r=null;if(n){r=t[1+n.sn-t[0].sn]||null;const o=n.endDTS-e;o>0&&o<15e-7&&(e+=15e-7),r&&n.level!==r.level&&r.end<=n.end&&(r=t[2+n.sn-t[0].sn]||null)}else e===0&&t[0].start===0&&(r=t[0]);if(r&&((!n||n.level===r.level)&&On(e,s,r)===0||Qh(r,n,Math.min(i,s))))return r;const a=wn.search(t,On.bind(null,e,s));return a&&(a!==n||!r)?a:r}function Qh(n,t,e){if(t?.start===0&&t.level<n.level&&(t.endPTS||0)>0){const s=t.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),e);return n.start<=s}return!1}function On(n=0,t=0,e){if(e.start<=n&&e.start+e.duration>n)return 0;const s=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0));return e.start+e.duration-s<=n?1:e.start-s>n&&e.start?-1:0}function Jh(n,t,e){const s=Math.min(t,e.duration+(e.deltaPTS?e.deltaPTS:0))*1e3;return(e.endProgramDateTime||0)-s>n}function Mn(n,t,e){if(n&&n.startCC<=t&&n.endCC>=t){let s=n.fragments;const{fragmentHint:i}=n;i&&(s=s.concat(i));let r;return wn.search(s,a=>a.cc<t?1:a.cc>t?-1:(r=a,a.end<=e?1:a.start>e?-1:0)),r||null}return null}function xn(n,t){return t===n.endSN&&n.fragmentHint?n.fragmentHint:n.fragments[1+t-n.startSN]||null}var Dt={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},bt={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};class Fn extends xt{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(m.ERROR,this.onError,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(m.ERROR,this.onError,this),t.off(m.ERROR,this.onErrorOut,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return t?.type===K.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,s=e.currentLevel;return(t=e.loadLevelObj)!=null&&t.details||s===-1?e.loadLevel:s}variantHasKey(t,e){if(t){var s;if((s=t.details)!=null&&s.hasKey(e))return!0;const i=t.audioGroups;if(i)return this.hls.allAudioTracks.filter(r=>i.indexOf(r.groupId)>=0).some(r=>{var a;return(a=r.details)==null?void 0:a.hasKey(e)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var s;if(e.fatal)return;const i=this.hls,r=e.context;switch(e.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:e.errorAction=this.getFragRetryOrSwitchAction(e);return;case R.FRAG_PARSING_ERROR:if((s=e.frag)!=null&&s.gap){e.errorAction=Qe();return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{e.errorAction=this.getFragRetryOrSwitchAction(e),e.errorAction.action=Dt.SendAlternateToPenaltyBox;return}case R.PLAYLIST_UNCHANGED_ERROR:case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var a;const o=e.parent===K.MAIN?e.level:i.loadLevel;e.details===R.LEVEL_EMPTY_ERROR&&(a=e.context)!=null&&(a=a.levelDetails)!=null&&a.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,o):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,o))}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level));return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const o=i.loadLevelObj;if(o&&(r.type===st.AUDIO_TRACK&&o.hasAudioGroup(r.groupId)||r.type===st.SUBTITLE_TRACK&&o.hasSubtitleGroup(r.groupId))){e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.loadLevel),e.errorAction.action=Dt.SendAlternateToPenaltyBox,e.errorAction.flags=bt.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:e.errorAction={action:Dt.SendAlternateToPenaltyBox,flags:bt.MoveAllAlternatesMatchingHDCP};return;case R.KEY_SYSTEM_SESSION_UPDATE_FAILED:case R.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case R.KEY_SYSTEM_NO_SESSION:e.errorAction={action:Dt.SendAlternateToPenaltyBox,flags:bt.MoveAllAlternatesMatchingKey};return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level));return;case R.MEDIA_SOURCE_REQUIRES_RESET:e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)),e.errorAction.flags|=bt.ResetMediaSource|bt.SwitchToSDR;return;case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_APPEND_NO_PROGRESS:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:e.errorAction=Qe();return}e.type===Y.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=Qe())}getPlaylistRetryOrSwitchAction(t,e){const s=this.hls,i=Kr(s.config.playlistLoadPolicy,t),r=this.playlistError++;if(Ge(i,r,gs(t),t.response))return{action:Dt.RetryRequest,flags:bt.None,retryConfig:i,retryCount:r};const a=this.getLevelSwitchAction(t,e);return i&&(a.retryConfig=i,a.retryCount=r),a}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),i=e.levels[s],{fragLoadPolicy:r,keyLoadPolicy:a}=e.config,o=Kr(Br(t)?a:r,t),l=e.levels.reduce((d,c)=>d+c.fragmentError,0);if(i&&(t.details!==R.FRAG_GAP&&i.fragmentError++,!Gr(t)&&Ge(o,l,gs(t),t.response)))return{action:Dt.RetryRequest,flags:bt.None,retryConfig:o,retryCount:l};const h=this.getLevelSwitchAction(t,s);return o&&(h.retryConfig=o,h.retryCount=l),h}getLevelSwitchAction(t,e){const s=this.hls;e==null&&(e=s.loadLevel);const i=this.hls.levels[e];if(i){var r,a;const h=t.details;i.loadError++,i.loadErrorTime=self.performance.now(),h===R.BUFFER_APPEND_ERROR&&i.fragmentError++;let d=-1;const{levels:c,loadLevel:u,minAutoLevel:f,maxAutoLevel:g}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(r=t.frag)==null?void 0:r.type,v=(p===K.AUDIO&&h===R.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&Nn(t))&&c.some(({audioCodec:S})=>i.audioCodec!==S),E=t.sourceBufferName==="video"&&Nn(t)&&c.some(({codecSet:S,audioCodec:A})=>i.codecSet!==S&&i.audioCodec===A),{type:y,groupId:T}=(a=t.context)!=null?a:{};for(let S=c.length;S--;){const A=(S+u)%c.length;if(A!==u&&A>=f&&A<=g&&(c[A].loadError===0||Hr(c[A],s.config.errorPenaltyExpireMs))){var o,l;const L=c[A];if(h===R.FRAG_GAP&&p===K.MAIN&&t.frag){const I=c[A].details;if(I){const b=_e(t.frag,I.fragments,t.frag.start);if(b!=null&&b.gap)continue}}else if(y===st.AUDIO_TRACK&&L.hasAudioGroup(T)||y===st.SUBTITLE_TRACK&&L.hasSubtitleGroup(T)||p===K.AUDIO&&(o=i.audioGroups)!=null&&o.some(I=>L.hasAudioGroup(I))||p===K.SUBTITLE&&(l=i.subtitleGroups)!=null&&l.some(I=>L.hasSubtitleGroup(I))||v&&i.audioCodec===L.audioCodec||E&&i.codecSet===L.codecSet||!v&&i.audioCodec!==L.audioCodec)continue;d=A;break}}if(d>-1&&s.loadLevel!==d)return t.levelRetry=!0,this.playlistError=0,{action:Dt.SendAlternateToPenaltyBox,flags:bt.None,nextAutoLevel:d}}return{action:Dt.SendAlternateToPenaltyBox,flags:bt.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var s,i;switch((s=e.errorAction)==null?void 0:s.action){case Dt.DoNothing:break;case Dt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),!e.errorAction.resolved&&e.details!==R.FRAG_GAP&&e.details!==R.PLAYLIST_UNCHANGED_ERROR&&!$n(e)&&(e.fatal=!0);break}if((((i=e.errorAction)==null?void 0:i.flags)||0)&bt.ResetMediaSource&&this.hls.recoverMediaError(),e.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;let i=s.nextAutoLevel;if(s.flags===bt.None)this.switchLevel(t,i);else if(s.flags&bt.SwitchToSDR){const o=this.hls.levels,l=o.length;for(let h=l;h--;)o[h].videoRange!=="SDR"?(o[h].fragmentError++,o[h].loadError++):i===void 0&&(i=h)}else if(s.flags&bt.MoveAllAlternatesMatchingHDCP){const o=this.getVariantLevelIndex(t.frag),l=e.levels[o],h=l?.attrs["HDCP-LEVEL"];s.hdcpLevel=h;const d=h==="NONE";h&&!d?(e.maxHdcpLevel=Di[Di.indexOf(h)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)):(d&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),s.flags|=bt.MoveAllAlternatesMatchingKey)}if(s.flags&bt.MoveAllAlternatesMatchingKey){const o=t.decryptdata;if(o){const l=this.hls.levels,h=l.length;for(let c=h;c--;)if(this.variantHasKey(l[c],o)){var r,a;this.log(`Banned key found in level ${c} (${l[c].bitrate}bps) or audio group "${(r=l[c].audioGroups)==null?void 0:r.join(",")}" (${(a=t.frag)==null?void 0:a.type} fragment) ${It(o.keyId||[])}`),l[c].fragmentError++,l[c].loadError++,this.log(`Removing level ${c} with key error (${t.error})`),this.hls.removeLevel(c)}const d=t.frag;if(this.hls.levels.length<h)s.resolved=!0;else if(d&&d.type!==K.MAIN){const c=d.decryptdata;c&&!o.matches(c)&&(s.resolved=!0)}}}s.resolved||this.switchLevel(t,i)}switchLevel(t,e){if(e!==void 0&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===R.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&t.sourceBufferName!=="audiovideo")){const s=bi(t.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${t.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${t.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}}function Nn(n){const t=n.details;return t===R.BUFFER_ADD_CODEC_ERROR||t===R.MEDIA_SOURCE_REQUIRES_RESET||t===R.BUFFER_APPEND_ERROR&&!$n(n)}function $n(n){return n.details===R.BUFFER_APPEND_ERROR&&(n.error.name==="QuotaExceededError"||n.error.name==="InvalidStateError")}function Qe(n){const t={action:Dt.DoNothing,flags:bt.None};return n&&(t.resolved=!0),t}const Un=10;class Bn{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}const e=this.lastPartSn-t.lastPartSn,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||e===0&&s>0,this.updated||this.advanced?this.misses=0:this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let s=e.decryptdata;return s||(e.setKeyFormat(t.keyFormat),s=e.decryptdata),!!s&&t.matches(s)})}get hasProgramDateTime(){return this.fragments.length?$(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Un}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?(this.driftEnd-this.driftStart)*1e3/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(e!==-1){for(let s=t.length;s--;)if(t[s].index>e)return t[s].index;return e}}return 0}get lastPartSn(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.advancedDateTime!==void 0&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}get partsExpired(){return this.live&&this.partTarget&&this.advancedDateTime!==void 0&&this.misses<3?this.age>(this.partHoldBack||this.partTarget*3)*1.5:!1}}const Gn={length:0,start:()=>0,end:()=>0};class q{static isBuffered(t,e){if(t){const s=q.getBuffered(t);for(let i=s.length;i--;)if(e>=s.start(i)&&e<=s.end(i))return!0}return!1}static bufferedRanges(t){if(t){const e=q.getBuffered(t);return q.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let s=0;s<t.length;s++)e.push({start:t.start(s),end:t.end(s)});return e}static bufferInfo(t,e,s){if(t){const i=q.bufferedRanges(t);if(i.length)return q.bufferedInfo(i,e,s)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,s){e=Math.max(0,e),t.length>1&&t.sort((d,c)=>d.start-c.start||c.end-d.end);let i=-1,r=[];if(s)for(let d=0;d<t.length;d++){e>=t[d].start&&e<=t[d].end&&(i=d);const c=r.length;if(c){const u=r[c-1].end;t[d].start-u<s?t[d].end>u&&(r[c-1].end=t[d].end):r.push(t[d])}else r.push(t[d])}else r=t;let a=0,o,l=e,h=e;for(let d=0;d<r.length;d++){const c=r[d].start,u=r[d].end;if(i===-1&&e>=c&&e<=u&&(i=d),e+s>=c&&e<u)l=c,h=u,a=h-e;else if(e+s<c){o=c;break}}return{len:a,start:l||0,end:h||0,nextStart:o,buffered:t,bufferedIndex:i}}static getBuffered(t){try{return t.buffered||Gn}catch(e){return at.log("failed to get media.buffered",e),Gn}}}function lt(n,t,e){ot(n,t,e),n.addEventListener(t,e)}function ot(n,t,e){n.removeEventListener(t,e)}function Ds(n){let t="";const e=n.length;for(let s=0;s<e;s++)t+=`[${n.start(s).toFixed(3)}-${n.end(s).toFixed(3)}]`;return t}const Kn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Vn="HlsJsTrackRemovedError",Hn="HlsJsSourceBufferError",Zh=.25,td=.001;class ed extends Error{constructor(t){super(t),this.name=Vn}}class Yn extends xt{constructor(t,e){super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=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.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(ot(r,"sourceopen",this._onMediaSourceOpen),ot(i,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){if(this.isMediaSourceReplaced()){const{currentSrc:l}=this.media,h=l&&l!==this._objectUrl?l:this.mediaSrc;this.warn(`MediaSource closed after media element switched to another source (${this._objectUrl} > ${h}) - detaching media`),this.hls.detachMedia();return}const s=this.media.error,{appendError:i,appendErrors:r}=this;let a=!1;!i&&s&&(a=Math.max(++r.audio,++r.video,++r.audiovideo)>=this.hls.config.appendErrorMaxRetry);const o=new Error(`MediaSource closed while media attached${jn(a,s)}`);this.warn(o),this.hls.trigger(m.ERROR,ht({fatal:a},i,{type:Y.MEDIA_ERROR,details:R.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this._onMediaError=()=>{const{media:s}=this;if(s){var i,r;this.log(`Media error (code: ${(i=s.error)==null?void 0:i.code}): ${(r=s.error)==null?void 0:r.message}`)}},this.hls=t,this.fragmentTracker=e,this.appendSource=Ul(le(t.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=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,this._onMediaEmptied=this._onMediaError=null}registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.BUFFER_RESET,this.onBufferReset,this),t.on(m.BUFFER_APPENDING,this.onBufferAppending,this),t.on(m.BUFFER_CODECS,this.onBufferCodecs,this),t.on(m.BUFFER_EOS,this.onBufferEos,this),t.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(m.FRAG_PARSED,this.onFragParsed,this),t.on(m.FRAG_CHANGED,this.onFragChanged,this),t.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.BUFFER_RESET,this.onBufferReset,this),t.off(m.BUFFER_APPENDING,this.onBufferAppending,this),t.off(m.BUFFER_CODECS,this.onBufferCodecs,this),t.off(m.BUFFER_EOS,this.onBufferEos,this),t.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(m.FRAG_PARSED,this.onFragParsed,this),t.off(m.FRAG_CHANGED,this.onFragChanged,this),t.off(m.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return i&&!this.sourceBufferCount&&i.mediaSource===e?ht(s,i.tracks):this.sourceBuffers.forEach(r=>{const[a]=r;a&&(s[a]=ht({},this.tracks[a]),this.removeBuffer(a)),r[0]=r[1]=null}),{media:t,mediaSource:e,tracks:s}}initTracks(){const t={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=t,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(t,e){var s;let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(t,e){const s=this.media=e.media;this.transferData=this.overrides=void 0;const i=le(this.appendSource);if(i){const a=!!e.mediaSource;(a||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const o=this.mediaSource=e.mediaSource||new i;if(this.assignMediaSource(o),a)this._objectUrl=s.src,this.attachTransferred();else{var r;const l=this._objectUrl=self.URL.createObjectURL(o),h=this.hls.config,d=h.emeEnabled&&s.mediaKeys?(r=h.emeController)==null?void 0:r.CDMCleanupPromise:null;d?d.then(()=>{this.hls&&this.setSource(s,o,l)}).catch(()=>{}):this.setSource(s,o,l)}lt(s,"emptied",this._onMediaEmptied),lt(s,"error",this._onMediaError),this.appendSource&&lt(s,"seeking",this._onStartStreaming)}}setSource(t,e,s){if(this.appendSource)try{t.removeAttribute("src");const i=self.ManagedMediaSource;t.disableRemotePlayback=t.disableRemotePlayback||i&&e instanceof i,Wn(t),sd(t,s),t.load()}catch{t.src=s}else t.src=s}assignMediaSource(t){var e,s;this.log(`${((e=this.transferData)==null?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${(s=t.constructor)==null?void 0:s.name}`),lt(t,"sourceopen",this._onMediaSourceOpen),lt(t,"sourceended",this._onMediaSourceEnded),lt(t,"sourceclose",this._onMediaSourceClose),this.appendSource&&(lt(t,"startstreaming",this._onStartStreaming),lt(t,"endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const s=this.tracks,i=e.tracks,r=i?Object.keys(i):null,a=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
15
+ required tracks: ${ft(s,(l,h)=>l==="initSegment"?void 0:h)};
16
+ transfer tracks: ${ft(i,(l,h)=>l==="initSegment"?void 0:h)}}`),!Wr(i,s)){e.mediaSource=null,e.tracks=void 0;const l=t.currentTime,h=this.details,d=Math.max(l,h?.fragments[0].start||0);if(d-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${d}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${d} currentTime: ${l}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,e),t.currentTime=d;return}this.transferData=void 0,r.forEach(l=>{const h=l,d=i[h];if(d){const c=d.buffer;if(c){const u=this.fragmentTracker,f=d.id;if(u.hasFragments(f)||u.hasParts(f)){const v=q.getBuffered(c);u.detectEvictedFragments(h,v,f,null,null,!0)}const g=Pi(h),p=[h,c];this.sourceBuffers[g]=p,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(h),this.trackSourceBuffer(h,d)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const e=(t=this.mediaSource)==null?void 0:t.readyState;return e==="open"||e==="ended"}onMediaDetaching(t,e){const s=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:a}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const l=r.sourceBuffers;for(let h=l.length;h--;)o&&l[h].abort(),r.removeSourceBuffer(l[h]);o&&r.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}ot(r,"sourceopen",this._onMediaSourceOpen),ot(r,"sourceended",this._onMediaSourceEnded),ot(r,"sourceclose",this._onMediaSourceClose),this.appendSource&&(ot(r,"startstreaming",this._onStartStreaming),ot(r,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(ot(i,"emptied",this._onMediaEmptied),ot(i,"error",this._onMediaError),ot(i,"seeking",this._onStartStreaming),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a&&!this.isMediaSourceReplaced(a)?(i.removeAttribute("src"),this.appendSource&&Wn(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const s=(e=this.tracks[t])==null?void 0:e.buffer;if(this.removeBuffer(t),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${t}`,r)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Pi(t)]=[null,null];const e=this.tracks[t];e&&(this.clearBufferAppendTimeoutId(e),e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Xh(this.tracks)}onBufferCodecs(t,e){var s;const i=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in e&&(i.audio||i.video)||i.audiovideo&&("audio"in e||"video"in e),o=!a&&this.sourceBufferCount&&this.media&&r.some(l=>!i[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(l=>{var h,d;const c=e[l],{id:u,codec:f,levelCodec:g,container:p,metadata:v,supplemental:E}=c;let y=i[l];const T=(h=this.transferData)==null||(h=h.tracks)==null?void 0:h[l],S=T!=null&&T.buffer?T:y,A=S?.pendingCodec||S?.codec,L=S?.levelCodec;y||(y=i[l]={buffer:void 0,listeners:[],codec:f,supplemental:E,container:p,levelCodec:g,metadata:v,id:u});const I=Ls(A,L),b=I?.replace(Kn,"$1");let k=Ls(f,g);const D=(d=k)==null?void 0:d.replace(Kn,"$1");k&&I&&b!==D&&(l.slice(0,5)==="audio"&&(k=Is(k,this.appendSource)),this.log(`switching codec ${A} to ${k}`),k!==(y.pendingCodec||y.codec)&&(y.pendingCodec=k),y.container=p,this.appendChangeType(l,p,k))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&((s=e.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{const s=this.tracks[e];return t[e]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},t},{})}appendChangeType(t,e,s){const i=`${e};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const a=this.tracks[t];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${t} sourceBuffer type to ${i}`),o.changeType(i),a.codec=s,a.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${t} SourceBuffer type`,a)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const s=t.start,i=s+t.duration*.05;if(((e=this.fragmentTracker.getAppendedFrag(s,K.MAIN))==null?void 0:e.gap)===!0)return;const r={label:"block-audio",execute:()=>{var a,o;(this.lastVideoAppendEnd>i||q.isBuffered((a=this.tracks.video)==null?void 0:a.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,K.MAIN))==null?void 0:o.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn("Error executing block-audio operation",a)}};this.append(r,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(t,e){const{tracks:s}=this,{data:i,type:r,parent:a,frag:o,part:l,chunkMeta:h,offset:d}=e,c=h.buffering[r],u=Et(o)&&!l&&!o.gap&&!h.partial&&!h.iframe;let f=null,g=!1;const{sn:p,cc:v}=o,E=self.performance.now();c.start=E;const y=o.stats.buffering,T=l?l.stats.buffering:null;y.start===0&&(y.start=E),T?.start===0&&(T.start=E);const S=s.audio;let A=!1;r==="audio"&&S?.container==="audio/mpeg"&&(A=!this.lastMpegAudioChunk||h.id===1||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const L=s.video,I=L?.buffer;if(I&&p!=="initSegment"&&d!==void 0){const D=S?.buffer,C=l||o;if(r==="audio"&&a!=="main"&&!(L.ending||L.ended)&&D&&q.getBuffered(D).length){const w=C.start+C.duration*.05,N=q.getBuffered(I),U=this.currentOp("video");!N.length&&!U?this.blockAudio(C):!q.isBuffered(I,w)&&this.lastVideoAppendEnd<w&&this.blockAudio(C)}else if(r==="video"){const w=C.end,N=this.lastVideoAppendEnd-w;this.lastVideoAppendEnd=w,N<0||N>C.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const b=(l||o).start,k={label:`append-${r}`,execute:()=>{var D;c.executeStart=self.performance.now();const C=(D=this.tracks[r])==null?void 0:D.buffer;C&&(u&&(f=q.timeRangesToArray(q.getBuffered(C)),g=Xn(_i(f,o),o)),A?this.updateTimestampOffset(C,b,.1,r,p,v):d!==void 0&&$(d)&&this.updateTimestampOffset(C,d,1e-6,r,p,v)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[r]);const D=self.performance.now();c.executeEnd=c.end=D,y.first===0&&(y.first=D),T?.first===0&&(T.first=D);const C={};if(this.sourceBuffers.forEach(([w,N])=>{w&&(C[w]=q.getBuffered(N))}),u){const w=this.getFragmentAppendProgress(o),N=C[r];if(N&&f){const U=q.timeRangesToArray(N),G=_i(U,o);w.progressed||(w.progressed=G-_i(f,o)>td);const M=g&&Xn(G,o);w.fullyBuffered[r]=(w.fullyBuffered[r]===void 0||w.fullyBuffered[r])&&M}}this.hls.trigger(m.BUFFER_APPENDED,{type:r,frag:o,part:l,chunkMeta:h,parent:a,timeRanges:C})},onError:D=>{var C;this.clearBufferAppendTimeoutId(this.tracks[r]);const w=D.code===DOMException.QUOTA_EXCEEDED_ERR||D.name=="QuotaExceededError"||"quota"in D;if(w&&!this._quotaEvictionPending[r]){const M=this.getBackBufferEvictionTarget(r,i.byteLength,o.type);if(M>0){this._quotaEvictionPending[r]=!0,this.log(`QuotaExceededError on "${r}" append sn: ${p} - evicting back buffer to ${M.toFixed(3)}s and retrying`);const F=this.getFlushOp(r,0,M),x=this.getClearEvictionPendingOp(r);this.insertNext([F,k,x],r);return}this.warn(`QuotaExceededError on "${r}" sn: ${p} - no back buffer available to evict`)}u&&(this.getFragmentAppendProgress(o).errored=!0);const N={type:Y.MEDIA_ERROR,parent:a,details:R.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:l,chunkMeta:h,error:D,err:D,fatal:!1},U=(C=this.media)==null?void 0:C.error;if(D.name===Vn&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))N.errorAction=Qe(!0);else{var G;w&&(N.details=R.BUFFER_FULL_ERROR);const M=++this.appendErrors[r],F=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${M}/${F+1} times to append segment in "${r}" sourceBuffer with error: ${D.message}`),M>=F&&(N.fatal=!w);const x=(G=this.mediaSource)==null?void 0:G.readyState;(x==="ended"||x==="closed"||U)&&!this.isMediaSourceReplaced()&&(this.warn(`MediaSource readyState "${x}" during SourceBuffer${jn(N.fatal,U)}`),N.details=R.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=N,this.hls.trigger(m.ERROR,N),w&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${r}" append sn: ${p}${l?" p: "+l.index:""} of ${a} playlist ${o.level} cc: ${v} offset: ${d} bytes: ${i.byteLength}`),this.append(k,r,this.isPending(this.tracks[r]))}getClearEvictionPendingOp(t){return{label:"clear",execute:()=>{this._quotaEvictionPending[t]=!1,this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(t,e,s){return this.log(`queuing "${t}" remove ${e}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,s)},onStart:()=>{},onComplete:()=>{var i;const r=(i=this.tracks[t])==null?void 0:i.buffer;this.log(`Remove request ${e}-${s} from ${t} Source Buffer complete > buffer: ${r?Ds(q.getBuffered(r)):"(detached)"}`),this.hls.trigger(m.BUFFER_FLUSHED,{type:t,start:e,end:s})},onError:i=>{this.warn(`Failed to remove ${e}-${s} from "${t}" SourceBuffer`,i),this.hls.trigger(m.BUFFER_FLUSHED,{type:t,start:0,end:0,error:i})}}}onBufferFlushing(t,e){const{type:s,startOffset:i,endOffset:r}=e;(!s||s==="audio")&&this.unblockAudio(),s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,i,r),a)})}onFragParsed(t,e){const{frag:s,part:i,chunkMeta:r}=e,a=[],o=i?i.elementaryStreams:s.elementaryStreams;o[ut.AUDIOVIDEO]?a.push("audiovideo"):(o[ut.AUDIO]&&a.push("audio"),o[ut.VIDEO]&&a.push("video"));const l=()=>{const h=self.performance.now();s.stats.buffering.end=h,i&&(i.stats.buffering.end=h);const d=i?i.stats:s.stats;this.checkAppendProgress(s,i,r,a),this.hls&&(this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:d,id:s.type,chunkMeta:r}),!i&&s.gap&&d.retry&&this.log(`Nothing buffered for ${s.type} level: ${s.level} sn: ${s.sn} retries ${d.retry}`))};a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${s.type} ${s.level} ${i?`part: ${i.index} of `:""}sn: ${s.sn}`),this.blockBuffers(l,a).catch(h=>{this.warn(`Fragment buffered callback ${h.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){var s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const{backBufferLength:a,frontBufferFlushThreshold:o}=r;this.trimBuffers(o,a,e.frag,e.previousFrag);const l=e.frag.elementaryStreams,{appendErrors:h}=this,d=(i=this.appendError)==null?void 0:i.sourceBufferName;Object.keys(l).forEach(c=>{l[c]&&(h[c]=0,c===d&&(this.appendError=void 0),c==="audio"||c==="video"?(h.audiovideo=0,d==="audiovideo"&&(this.appendError=void 0)):(h.audio=0,h.video=0,d!=="audiovideo"&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var s;this.sourceBuffers.forEach(([r])=>{if(r){const a=this.tracks[r];(!e.type||e.type===r)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${r} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.allTracksEnding?(this.unblockAudio(),i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{if(this.tracksEnded(),!this.allTracksEnding){this.log("EOS cancelled");return}const{mediaSource:r}=this;if(r?.readyState!=="open"){r&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${r.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),r.endOfStream(),this.hls.trigger(m.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(m.BUFFERED_TO_END,void 0))):e.type==="video"&&this.unblockAudio()}get allTracksEnding(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!((e=this.tracks[t])!=null&&e.ended)})}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(t!==null){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,e){if(e.details===R.BUFFER_APPEND_ERROR&&e.frag){var s;const i=(s=e.errorAction)==null?void 0:s.nextAutoLevel;$(i)&&i!==e.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(t,e,s){const{media:i}=this;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,s,e):0}getFragmentAppendProgress(t){var e;const s=qn(t);let i=this.fragmentAppendProgress[s];return((e=i)==null?void 0:e.stats)!==t.stats&&(i={stats:t.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[s]=i),i}checkAppendProgress(t,e,s,i){if(e||!Et(t)||t.gap||s.iframe||s.partial)return;const r=qn(t),a=this.fragmentAppendProgress[r];delete this.fragmentAppendProgress[r];const o=t.stats.buffering;if(o.start&&!o.first)return;const l=a?.stats===t.stats?a:void 0;if(l!=null&&l.errored)return;const h=i.length>0&&i.every(u=>l?.fullyBuffered[u]===!0);if(l!=null&&l.progressed||h){delete this.appendsWithoutProgress[r];return}if(!l&&i.length===0)return;const d=(this.appendsWithoutProgress[r]||0)+1,c=this.hls;d>=c.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[r]:this.appendsWithoutProgress[r]=d,this.warn(`Fragment ${t.sn} of ${t.type} playlist ${t.level} appended ${d} time${d>1?"s":""} without buffered range growth`),c.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:t,chunkMeta:s,parent:t.type,appendsWithoutProgress:d,error:new Error(`Fragment append did not increase buffered coverage (${d})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(t,e,s,i){const{hls:r,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;const l=r.config,h=o.currentTime,d=a.levelTargetDuration;e=a.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:e;let c=-1/0;if($(e)&&e>=0){const u=Math.max(e,d);c=Math.floor(h/d)*d-u}if(s){const u=this.getLoopBackBufferFlushEnd(s,i??null);u>0&&(c=Math.max(c,u))}if(c>0&&this.flushBackBuffer(h,d,c),$(t)&&t>0){const u=Math.max(l.maxBufferLength,t),f=Math.max(u,d),g=Math.floor(h/d)*d+f;this.flushFrontBuffer(h,d,g)}}getLoopBackBufferFlushEnd(t,e){var s;const{media:i}=this;if(((s=this.hls)==null?void 0:s.config.loopBackBufferFlush)===!1||!(i!=null&&i.loop)||!e||t.level<=e.level)return 0;const{video:r,audiovideo:a}=t.elementaryStreams;if(r!=null&&r.partial||a!=null&&a.partial)return 0;const o=this.getEarliestElementaryStreamStart(t)-Zh;return o<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${t.level}, range [0-${o.toFixed(3)}]`),o)}getEarliestElementaryStreamStart(t){const{audio:e,video:s,audiovideo:i}=t.elementaryStreams;let r=t.start;return i?r=Math.min(r,i.startDTS):(e&&(r=Math.min(r,e.startDTS)),s&&(r=Math.min(r,s.startDTS))),r}flushBackBuffer(t,e,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const h=q.getBuffered(r);if(h.length>0&&s>h.start(0)){var a,o,l;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});const d=this.tracks[i];if((a=this.details)!=null&&a.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(d!=null&&d.ended&&!((o=this.media)!=null&&o.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(t,e,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const a=q.getBuffered(r),o=a.length;if(o<2)return;const l=a.start(o-1),h=a.end(o-1);if(s>l||t>=l&&t<=h)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:i})}})}getDurationAndRange(){var t;const{details:e,mediaSource:s}=this;if(!e||!this.media||s?.readyState!=="open")return null;const i=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&s.setLiveSeekableRange){const l=Math.max(0,e.fragmentStart),h=Math.max(l,i);return{duration:1/0,start:l,end:h}}return{duration:1/0}}const r=(t=this.overrides)==null?void 0:t.duration;if(r)return $(r)?{duration:r}:null;const a=this.media.duration,o=$(s.duration)?s.duration:0;return i>o&&i>a||!$(a)?{duration:i}:null}updateMediaSource({duration:t,start:e,end:s}){const i=this.mediaSource;!i||!this.media||i.readyState!=="open"||(i.duration!==t&&($(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),i.duration=t),e!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${e}-${s}.`),i.setLiveSeekableRange(e,s)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${ft(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,s])=>{if(e){const i=this.tracks[e];t[e]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(m.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in t){const a=r,o=t[a];if(this.isPending(o)){const l=this.getTrackCodec(o,a),h=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${h})${this.currentOp(a)?" Queued":""} ${ft(o)}`);try{const d=s.addSourceBuffer(h),c=Pi(a),u=[a,d];e[c]=u,o.buffer=d}catch(d){var i;this.error(`error while trying to add sourceBuffer: ${d.message}`),this.shiftAndExecuteNext(a),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[a],this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:d,sourceBufferName:a,mimeType:h,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}clearBufferAppendTimeoutId(t){t&&(self.clearTimeout(t.bufferAppendTimeoutId),t.bufferAppendTimeoutId=void 0)}getTrackCodec(t,e){const s=t.supplemental;let i=t.codec;s&&(e==="video"||e==="audiovideo")&&je(s,"video")&&(i=_h(i,s));const r=Ls(i,t.levelCodec);return r?e.slice(0,5)==="audio"?Is(r,this.appendSource):r:""}trackSourceBuffer(t,e){const s=e.buffer;if(!s)return;const i=this.getTrackCodec(e,t);this.tracks[t]={buffer:s,codec:i,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(r,a)=>{const o=a.removedRanges;o!=null&&o.length&&(this.log(`${r} buffer removed ${Ds(o)}`),this.hls.trigger(m.BUFFER_FLUSHED,{type:r,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var t;const e=this.media;return e?(e.src?e:((t=e.querySelector)==null?void 0:t.call(e,"source"))||e).src:void 0}isMediaSourceReplaced(t=this._objectUrl){var e;if(!t)return!1;const s=(e=this.media)==null?void 0:e.currentSrc,i=this.mediaSrc;return!!s&&s!==t||!!i&&i!==t}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e,s;if(((e=this.mediaSource)==null?void 0:e.readyState)==="closed"){this.resetBuffer(t);return}const i=this.currentOp(t);if(i){if(i.onComplete(),(s=this.tracks[t])==null||(s=s.buffer)==null?void 0:s.updating){this.log(`${t} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(t)});return}this.shiftAndExecuteNext(t)}}onSBUpdateError(t,e){var s;const i=(s=this.mediaSource)==null?void 0:s.readyState,r=new Error(`${t} SourceBuffer error. MediaSource readyState: ${i}`);r.name=Hn,this.error(`${r.message}`,e),this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});const a=this.currentOp(t);a&&a.onError(r)}updateTimestampOffset(t,e,s,i,r,a){const o=e-t.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${a})`),t.timestampOffset=e)}removeExecutor(t,e,s){const{media:i,mediaSource:r}=this,a=this.tracks[t],o=a?.buffer;if(!i||!r||!o)throw new Error(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`);const l=$(i.duration)?i.duration:1/0,h=$(r.duration)?r.duration:1/0,d=Math.max(0,e);if(d>=h){var c;(c=this.currentOp(t))==null||c.onComplete(),this.shiftAndExecuteNext(t);return}const u=Math.min(s,l,h);if(u>d&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${d},${u}] from the ${t} SourceBuffer`),o.remove(d,u);else throw new Error(`Cannot remove ${u<=d?`invalid range (${d} >= ${u}) `:""}from the ${t} SourceBuffer${a.ending?" while track ending":""}`)}appendExecutor(t,e){const s=this.tracks[e],i=s?.buffer;if(!i)throw new ed(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);if(s.ending=!1,s.ended=!1,this.hls.config.appendTimeout!==1/0){const r=this.calculateAppendTimeoutTime(i);s.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(e,i,r),r)}i.appendBuffer(t)}appendTimeoutHandler(t,e,s){this.log(`Received timeout after ${s}ms for append on ${t} source buffer. Aborting and triggering error.`);try{e.abort()}catch{this.log(`Failed to abort append on ${t} source buffer after timeout.`)}const i=this.currentOp(t);i&&i.onError(new Error(`${t}-append-timeout`))}calculateAppendTimeoutTime(t){let e=Un;this.details&&(e=this.details.levelTargetDuration);let s=2*e*1e3;if(this.media===null)return s;const i=q.bufferInfo(t,this.media.currentTime,0);return i.len?(s=Math.max(i.len*1e3,s),Math.max(this.hls.config.appendTimeout,s)):s}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}isAudioBlocked(){var t;return((t=this.currentOp("audio"))==null?void 0:t.label)==="block-audio"}isAudioBlocking(){return this.operationQueue?this.operationQueue.audioBlocking():!1}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:s}=this,i=e.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:e.map(r=>this.appendBlocker(r));return Promise.all(i).then(r=>{s===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(e=>{var s;const i=(s=this.tracks[e])==null?void 0:s.buffer;!i||i.updating||e==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(e)})}append(t,e,s){this.operationQueue&&this.operationQueue.append(t,e,s)}insertNext(t,e){this.operationQueue&&this.operationQueue.insertNext(t,e)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,s){const i=this.tracks[t];if(!i)return;const r=i.buffer;if(!r)return;const a=s.bind(this,t);i.listeners.push({event:e,listener:a}),lt(r,e,a)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const s=e.buffer;s&&(e.listeners.forEach(i=>{ot(s,i.event,i.listener)}),e.listeners.length=0)}}function Wn(n){const t=n.querySelectorAll("source");[].slice.call(t).forEach(e=>{n.removeChild(e)})}function sd(n,t){const e=self.document.createElement("source");e.type="video/mp4",e.src=t,n.appendChild(e)}function Pi(n){return n==="audio"?1:0}function jn(n,t){return`${n?"":" - triggering recovery"}${t?" with HTMLMediaElement Error: "+t.message:""}`}function qn(n){return`${n.type}_${n.sn}_${n.level}`}function _i(n,t){const{start:e,end:s}=t;let i=0;for(let r=0;r<n.length;r++){const a=n[r];if(a.start>=s)break;const o=Math.max(e,a.start),l=Math.min(s,a.end);l>o&&(i+=l-o)}return i}function Xn(n,t){return t.duration-n<=.05}var mt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class id{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.BUFFER_APPENDED,this.onBufferAppended,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this),t.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.BUFFER_APPENDED,this.onBufferAppended,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this),t.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const s=this.activePartLists[e];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;if(r.start<=t&&t<=r.end&&r.loaded)return r}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,s){const{fragments:i}=this,r=Object.keys(i);for(let a=r.length;a--;){const o=i[r[a]];if(o?.body.type===e&&(!s||o.buffered)){const l=o.body;if(l.start<=t&&t<=l.end)return l}}return null}detectEvictedFragments(t,e,s,i,r,a){this.timeRanges&&(this.timeRanges[t]=e);const o=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(l=>{const h=this.fragments[l];if(!h||!this.hls)return;const d=h.body;if(o>=d.sn)return;if(!h.buffered&&(!h.loaded||a)){d.type===s&&this.removeFragment(d);return}const c=h.range[t];if(c){if(c.time.length===0){this.removeFragment(d);return}if(c.time.some(u=>{const f=!this.isTimeBuffered(u.startPTS,u.endPTS,e);return f&&this.removeFragment(d),f}),i&&i!==d&&We()){const u=i.endPTS,f=d.startPTS;if(u&&f&&h.range.video){const g=f-u;g<0&&g>-.1&&(this.removeFragment(d),this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:u+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(t){const e=this.timeRanges,{frag:s,part:i,id:r}=t;if(!e||!Et(s))return;const a=Ce(s),o=this.fragments[a];if(!o||o.buffered&&s.gap)return;const l=!s.relurl;Object.keys(e).forEach(d=>{const c=s.elementaryStreams[d];if(!c)return;const u=e[d],f=l||c.partial===!0;o.range[d]=this.getBufferedTimes(s,i,f,u),this.detectEvictedFragments(d,u,r,s,i)}),o.loaded=null;const h=Object.keys(o.range);if(h.length){if(this.bufferedEnd(o,s),ks(o)||this.removeParts(s.sn-1,s.type),!i){const d=Math.min(.004,s.duration);h.some(c=>{var u;const f=(u=o.range[c])==null?void 0:u.time,g=f.length===0||f.length===1&&f[0].endPTS-f[0].startPTS<d;return g&&this.addAsGap(s),g})}}else this.removeFragment(s)}addAsGap(t){t.gap=!0,this.removeFragment(t),this.fragBuffered(t,!0)}bufferedEnd(t,e){t.buffered=!0,(t.body.endList=e.endList||t.body.endList)&&!e.gap&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const s=this.activePartLists[e];s&&(this.activePartLists[e]=zn(s,i=>i.fragment.sn>=t))}fragBuffered(t,e){const s=Ce(t);let i=this.fragments[s];return!i&&e&&(i=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,t)),i}getBufferedTimes(t,e,s,i){const r={time:[],partial:s},a=t.start,o=t.end,l=t.minEndPTS||o,h=t.maxStartPTS||a;for(let d=0;d<i.length;d++){const c=i.start(d)-this.bufferPadding,u=i.end(d)+this.bufferPadding;if(h>=c&&l<=u){r.time.push({startPTS:Math.max(a,i.start(d)),endPTS:Math.min(o,i.end(d))});break}else if(a<u&&o>c){const f=Math.max(a,i.start(d)),g=Math.min(o,i.end(d));g>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:g}))}else if(o<=c)break}return r}getPartialFragment(t){let e=null,s,i,r,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(h=>{const d=l[h];d&&ks(d)&&(i=d.body.start-o,r=d.body.end+o,t>=i&&t<=r&&(s=Math.min(t-i,r-t),a<=s&&(e=d.body,a=s)))}),e}isEndListAppended(t){const e=this.endListFragments[t];return e!==void 0&&(e.buffered||ks(e))}getState(t){const e=Ce(t),s=this.fragments[e];return s?s.buffered?ks(s)?mt.PARTIAL:mt.OK:mt.APPENDING:mt.NOT_LOADED}isTimeBuffered(t,e,s){let i,r;for(let a=0;a<s.length;a++){if(i=s.start(a)-this.bufferPadding,r=s.end(a)+this.bufferPadding,t>=i&&e<=r)return!0;if(e<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if(!Et(e.frag)||e.frag.bitrateTest)return;const s=e.frag,i=e.part?null:e,r=Ce(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:i,timeRanges:r}=e;if(!Et(s))return;const a=s.type;if(i){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(i)}this.timeRanges=r}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Ce(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,s=Object.keys(e);if(!t)return s.length>0;for(let i=s.length;i--;){const r=e[s[i]];if(r?.body.type===t)return!0}return!1}hasParts(t){var e;return!!((e=this.activePartLists[t])!=null&&e.length)}getBackBufferEvictionEnd(t,e,s){const{fragments:i}=this;let r=0,a=0;const o=Object.keys(i);for(let l=0;l<o.length;l++){const h=i[o[l]];if(!h||!h.buffered||h.body.type!==e)continue;const d=h.body;if(d.gap)return 0;const c=d.hasStats&&d.stats.loaded||d.byteLength||d.bitrate&&d.bitrate*8*d.duration;if(d.end<=t&&c&&(r+=c,a=Math.max(a,d.end),r>=s))return a}return a>0?a:0}removeFragmentsInRange(t,e,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==s||i&&!l.gap||l.start<e&&l.end>t&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(t){const e=Ce(t);t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const i=t.sn;this.activePartLists[t.type]=zn(s,r=>r.fragment.sn!==i)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}gapFragments(){return this.hasGaps?Object.keys(this.fragments).map(t=>{var e;return(e=this.fragments[t])==null?void 0:e.body}).filter(t=>!!(t!=null&&t.gap)):[]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=(t=this.hls)==null||(t=t.latestLevelDetails)==null?void 0:t.partList;e&&e.forEach(s=>s.clearElementaryStreamInfo())}}function ks(n){var t,e,s,i;return n.buffered&&!!(n.body.gap||(t=n.range.video)!=null&&t.partial||(e=n.range.audio)!=null&&e.partial||(s=n.range.audiovideo)!=null&&s.partial||(i=n.range.subs)!=null&&i.partial)}function Ce(n){return`${n.type}_${n.level}_${n.sn}`}function zn(n,t){return n.filter(e=>{const s=t(e);return s||e.clearElementaryStreamInfo(),s})}var me={cbc:0,ctr:1};class rd{constructor(t,e,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=s}decrypt(t,e){switch(this.aesMode){case me.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case me.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function nd(n){const t=n.byteLength,e=t&&new DataView(n.buffer).getUint8(t-1);return e?n.slice(0,t-e):n}class ad{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=e.getUint32(i*4);return s}initTable(){const t=this.sBox,e=this.invSBox,s=this.subMix,i=s[0],r=s[1],a=s[2],o=s[3],l=this.invSubMix,h=l[0],d=l[1],c=l[2],u=l[3],f=new Uint32Array(256);let g=0,p=0,v=0;for(v=0;v<256;v++)v<128?f[v]=v<<1:f[v]=v<<1^283;for(v=0;v<256;v++){let E=p^p<<1^p<<2^p<<3^p<<4;E=E>>>8^E&255^99,t[g]=E,e[E]=g;const y=f[g],T=f[y],S=f[T];let A=f[E]*257^E*16843008;i[g]=A<<24|A>>>8,r[g]=A<<16|A>>>16,a[g]=A<<8|A>>>24,o[g]=A,A=S*16843009^T*65537^y*257^g*16843008,h[E]=A<<24|A>>>8,d[E]=A<<16|A>>>16,c[E]=A<<8|A>>>24,u[E]=A,g?(g=y^f[f[f[S^y]]],p^=f[f[p]]):g=p=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,i=0;for(;i<e.length&&s;)s=e[i]===this.key[i],i++;if(s)return;this.key=e;const r=this.keySize=e.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const a=this.ksRows=(r+6+1)*4;let o,l;const h=this.keySchedule=new Uint32Array(a),d=this.invKeySchedule=new Uint32Array(a),c=this.sBox,u=this.rcon,f=this.invSubMix,g=f[0],p=f[1],v=f[2],E=f[3];let y,T;for(o=0;o<a;o++){if(o<r){y=h[o]=e[o];continue}T=y,o%r===0?(T=T<<8|T>>>24,T=c[T>>>24]<<24|c[T>>>16&255]<<16|c[T>>>8&255]<<8|c[T&255],T^=u[o/r|0]<<24):r>6&&o%r===4&&(T=c[T>>>24]<<24|c[T>>>16&255]<<16|c[T>>>8&255]<<8|c[T&255]),h[o]=y=(h[o-r]^T)>>>0}for(l=0;l<a;l++)o=a-l,l&3?T=h[o]:T=h[o-4],l<4||o<=4?d[l]=T:d[l]=g[c[T>>>24]]^p[c[T>>>16&255]]^v[c[T>>>8&255]]^E[c[T&255]],d[l]=d[l]>>>0}networkToHostOrderSwap(t){return t<<24|(t&65280)<<8|(t&16711680)>>8|t>>>24}decrypt(t,e,s){const i=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=this.uint8ArrayToUint32Array_(s);let f=u[0],g=u[1],p=u[2],v=u[3];const E=new Int32Array(t),y=new Int32Array(E.length);let T,S,A,L,I,b,k,D,C,w,N,U,G,M;const F=this.networkToHostOrderSwap;for(;e<E.length;){for(C=F(E[e]),w=F(E[e+1]),N=F(E[e+2]),U=F(E[e+3]),I=C^r[0],b=U^r[1],k=N^r[2],D=w^r[3],G=4,M=1;M<i;M++)T=l[I>>>24]^h[b>>16&255]^d[k>>8&255]^c[D&255]^r[G],S=l[b>>>24]^h[k>>16&255]^d[D>>8&255]^c[I&255]^r[G+1],A=l[k>>>24]^h[D>>16&255]^d[I>>8&255]^c[b&255]^r[G+2],L=l[D>>>24]^h[I>>16&255]^d[b>>8&255]^c[k&255]^r[G+3],I=T,b=S,k=A,D=L,G=G+4;T=a[I>>>24]<<24^a[b>>16&255]<<16^a[k>>8&255]<<8^a[D&255]^r[G],S=a[b>>>24]<<24^a[k>>16&255]<<16^a[D>>8&255]<<8^a[I&255]^r[G+1],A=a[k>>>24]<<24^a[D>>16&255]<<16^a[I>>8&255]<<8^a[b&255]^r[G+2],L=a[D>>>24]<<24^a[I>>16&255]<<16^a[b>>8&255]<<8^a[k&255]^r[G+3],y[e]=F(T^f),y[e+1]=F(L^g),y[e+2]=F(A^p),y[e+3]=F(S^v),f=C,g=w,p=N,v=U,e=e+4}return y.buffer}}class od{constructor(t,e,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=s}expandKey(){const t=ld(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}function ld(n){switch(n){case me.cbc:return"AES-CBC";case me.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${n}`)}}const hd=16;class Ci{constructor(t,e){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,e!==!0)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const s=new Uint8Array(t);this.reset();const i=this.decryptRange;return i?i.start===0&&i.end>=s.length?s:s.slice(i.start,i.end):nd(s)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,s,i,r){return this.decryptRange=r,this.useSoftware||r?new Promise((a,o)=>{const l=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(l,e,s,i);const h=this.flush();h?a(h.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,s,i)}softwareDecrypt(t,e,s,i){const{currentIV:r,currentResult:a,remainderData:o}=this;if(i!==me.cbc||e.byteLength!==16)return at.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=Gt(o,t),this.remainderData=null);const l=this.getValidChunk(t);if(!l.length)return null;r&&(s=r);let h=this.softwareDecrypter;h||(h=this.softwareDecrypter=new ad),h.expandKey(e);const d=a;return this.currentResult=h.decrypt(l.buffer,0,s),this.currentIV=l.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,s,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,s,i));this.key=e,this.fastAesKey=new od(this.subtle,e,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new rd(this.subtle,new Uint8Array(s),i).decrypt(t.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(at.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,s,i)))}onWebCryptoError(t,e,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s,i);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%hd;return s!==t.length&&(e=t.slice(0,s),this.remainderData=t.slice(s)),e}logOnce(t){this.logEnabled&&(at.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Qn=Math.pow(2,17);class Jn{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e,s,i){const r=t.url;if(!r)return Promise.reject(new ie({type:Y.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,o=a.fLoader,l=a.loader;return new Promise((h,d)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(v=>v[0]==="GAP")){d(ta(t));return}else t.gap=!1;const c=this.loader=o?new o(a):new l(a),u=Zn(t,null,e);t.loader=c;const f=Vr(a.fragLoadPolicy.default),g={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:Qn};c.stats.retry=t.stats.retry,t.stats=c.stats;const p={onSuccess:(v,E,y,T)=>{this.resetLoader(t,c);let S=v.data;y.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(S.slice(0,16)),S=S.slice(16)),h({frag:t,part:null,payload:S,networkDetails:T})},onError:(v,E,y,T)=>{this.resetLoader(t,c),d(new ie({type:Y.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:W({url:r,data:void 0},v),error:new Error(`HTTP Error ${v.code} ${v.text}`),networkDetails:y,stats:T}))},onAbort:(v,E,y)=>{this.resetLoader(t,c),d(new ie({type:Y.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:y,stats:v}))},onTimeout:(v,E,y)=>{this.resetLoader(t,c),d(new ie({type:Y.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:y,stats:v}))}};if(s){const v=this.gateProgress(s,i);p.onProgress=(E,y,T,S)=>v({frag:t,part:null,payload:T,networkDetails:S})}c.load(u,g,p)})}gateProgress(t,e){let s=t;if(e){const i=[];let r=!1;e.then(()=>{r=!0,i.forEach(a=>t(a)),i.length=0}).catch(()=>{}),s=a=>{r?t(a):i.push(a)}}return s}loadPart(t,e,s){this.abort();const i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap){l(ta(t,e));return}const h=this.loader=r?new r(i):new a(i),d=Zn(t,e);t.loader=h;const c=Vr(i.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Qn};e.stats=h.stats,h.load(d,u,{onSuccess:(f,g,p,v)=>{this.resetLoader(t,h),this.updateStatsFromPart(t,e);const E={frag:t,part:e,payload:f.data,networkDetails:v};s(E),o(E)},onError:(f,g,p,v)=>{this.resetLoader(t,h),l(new ie({type:Y.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:W({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:v}))},onAbort:(f,g,p)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,h),l(new ie({type:Y.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(t,h),l(new ie({type:Y.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(t,e){const s=t.stats,i=e.stats,r=i.total;if(s.loaded+=i.loaded,r){const l=Math.round(t.duration/e.duration),h=Math.min(Math.round(s.loaded/r),l),d=(l-h)*Math.round(s.loaded/h);s.total=s.loaded+d}else s.total=Math.max(s.loaded,s.total);const a=s.loading,o=i.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(t,e){t.loader=null,t.url=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function Zn(n,t=null,e){const s=t||n,i={type:st.MEDIA_FRAGMENT,frag:n,part:t,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=Ps(n,t,e);return r.resetIV&&(i.resetIV=!0),r.byteRange&&(i.rangeStart=r.byteRange.start,i.rangeEnd=r.byteRange.end),i}function Ps(n,t=null,e){const s={},i=t||n,r=i.byteRangeStartOffset,a=i.byteRangeEndOffset;if($(r)&&$(a)){var o;if((n.sn==="initSegment"||e)&&dd((o=n.decryptdata)==null?void 0:o.method)){let l=Math.floor(r/16)*16;const h=Math.ceil(a/16)*16;s.decryptRange={start:r-l,end:a-l},l>=16&&(s.resetIV=!0,l=l-16),s.byteRange={start:l,end:h}}else s.byteRange={start:r,end:a}}return s}function ta(n,t){const e=new Error(`GAP ${n.gap?"tag":"attribute"} found`),s={type:Y.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:n,error:e,networkDetails:null};return t&&(s.part=t),(t||n).stats.aborted=!0,new ie(s)}function dd(n){return n==="AES-128"||n==="AES-256"}class ie extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class ea extends xt{constructor(t,e){super(t,e),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class _s{constructor(t,e,s,i=0,r=-1,a=!1,o,l,h){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.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=Cs(),this.buffering={audio:Cs(),video:Cs(),audiovideo:Cs()},this.level=t,this.sn=e,this.id=s,this.size=i,this.part=r,this.partial=a,this.duration=o||0,this.decryptRange=h,this.iframe=l||!1}}function Cs(){return{start:0,executeStart:0,executeEnd:0,end:0}}const wi=/\{\$([a-zA-Z0-9-_]+)\}/g;function sa(n){return wi.lastIndex=0,wi.test(n)}function Oi(n,t){if(n.variableList!==null||n.hasVariableRefs){const e=n.variableList;return t.replace(wi,s=>{const i=s.substring(2,s.length-1),r=e?.[i];return r===void 0?(n.playlistParsingError||(n.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return t}function ia(n,t,e){let s=n.variableList;s||(n.variableList=s={});let i,r;if("QUERYPARAM"in t){i=t.QUERYPARAM;try{const a=new self.URL(e).searchParams;if(a.has(i))r=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${e}"`)}catch(a){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=t.NAME,r=t.VALUE;i in s?n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function cd(n,t,e){const s=t.IMPORT;if(e&&s in e){let i=n.variableList;i||(n.variableList=i={}),i[s]=e[s]}else n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const ud=/^(\d+)x(\d+)$/,ra=/(.+?)=(".*?"|.*?)(?:,|$)/g;class vt{constructor(t,e){typeof t=="string"&&(t=vt.parseAttrList(t,e)),ht(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(e.length&1?"0":"")+e;const s=new Uint8Array(e.length/2);for(let i=0;i<e.length/2;i++)s[i]=parseInt(e.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const s=this[t];return s?parseFloat(s):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const s=this[t];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),e)}bool(t){return this[t]==="YES"}decimalResolution(t){const e=ud.exec(this[t]);if(e!==null)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let s;const i={};for(ra.lastIndex=0;(s=ra.exec(t))!==null;){const r=s[1].trim();let a=s[2];const o=a.indexOf('"')===0&&a.lastIndexOf('"')===a.length-1;let l=!1;if(o)a=a.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(e&&(o||l))a=Oi(e,a);else if(!l&&!o)switch(r){case"CLOSED-CAPTIONS":if(a==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":at.warn(`${t}: attribute ${r} is missing quotes`)}i[r]=a}return i}}const fd="com.apple.hls.interstitial";function gd(n){return n!=="ID"&&n!=="CLASS"&&n!=="CUE"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function md(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"||n==="SCTE35-CMD"}class Mi{constructor(t,e,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=e?.tagAnchor||null,this.tagOrder=(i=e?.tagOrder)!=null?i:s,e){const r=e.attr;for(const a in r)if(Object.prototype.hasOwnProperty.call(t,a)&&t[a]!==r[a]){at.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=a;break}t=ht(new vt({}),r,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in t){const r=e?.endDate||new Date(t["END-DATE"]);$(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return t===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return t===null||t.programDateTime===null?(at.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return e!==null?this._dateAtEnd=new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if($(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===fd}get isValid(){return!!this.id&&!this._badValueForSameId&&$(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:$(this.startDate.getTime())?this.isInterstitial&&!("X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)?"Interstitial Date range missing X-ASSET-(LIST|URI)":this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Date range invalid start date":"Missing ID"}}function ws(n,t){return n.length===t.length?!n.some((e,s)=>e!==t[s]):!1}function na(n,t){return!n&&!t?!0:!n||!t?!1:ws(n,t)}function we(n){return n==="AES-128"||n==="AES-256"||n==="AES-256-CTR"}function xi(n){switch(n){case"AES-128":case"AES-256":return me.cbc;case"AES-256-CTR":return me.ctr;default:throw new Error(`invalid full segment method ${n}`)}}function Fi(n){return Uint8Array.from(unescape(encodeURIComponent(n)),t=>t.charCodeAt(0))}function pd(n){const t=Fi(n).subarray(0,16),e=new Uint8Array(16);return e.set(t,16-t.length),e}function aa(n){const t=function(e,s,i){const r=e[s];e[s]=e[i],e[i]=r};t(n,0,3),t(n,1,2),t(n,4,5),t(n,6,7)}function oa(n){const t=n.split(":");let e=null;if(t[0]==="data"&&t.length===2){const s=t[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",a=i[1];r?(s.splice(-1,1),e=pi(a)):e=pd(a)}}return e}const Os=typeof self<"u"?self:void 0;var gt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},kt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ms(n){switch(n){case kt.FAIRPLAY:return gt.FAIRPLAY;case kt.PLAYREADY:return gt.PLAYREADY;case kt.WIDEVINE:return gt.WIDEVINE;case kt.CLEARKEY:return gt.CLEARKEY}}var la={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Ni(n){switch(n){case gt.FAIRPLAY:return kt.FAIRPLAY;case gt.PLAYREADY:return kt.PLAYREADY;case gt.WIDEVINE:return kt.WIDEVINE;case gt.CLEARKEY:return kt.CLEARKEY}}function Je(n){const{drmSystems:t,widevineLicenseUrl:e}=n,s=t?[gt.FAIRPLAY,gt.WIDEVINE,gt.PLAYREADY,gt.CLEARKEY].filter(i=>!!t[i]):[];return!s[gt.WIDEVINE]&&e&&s.push(gt.WIDEVINE),s}const $i=(function(n){return Os!=null&&(n=Os.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function vd(n,t,e,s){let i;switch(n){case gt.FAIRPLAY:i=["cenc","sinf"];break;case gt.WIDEVINE:case gt.PLAYREADY:i=["cenc"];break;case gt.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return yd(i,t,e,s)}function yd(n,t,e,s){return[{initDataTypes:n,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:t.map(i=>({contentType:`audio/mp4; codecs=${i}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:e.map(i=>({contentType:`video/mp4; codecs=${i}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Ed(n){var t;return!!n&&(n.sessionType==="persistent-license"||!!((t=n.sessionTypes)!=null&&t.some(e=>e==="persistent-license")))}function Ui(n){const t=new Uint16Array(n.buffer,n.byteOffset,n.byteLength/2),e=Vt(t),s=e.substring(e.indexOf("<"),e.length),i=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(i){const r=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(r){const a=pi(r).subarray(0,16);return aa(a),a}}return null}let Oe={};class ae{static clearKeyUriToKeyIdMap(){Oe={}}static setKeyIdForUri(t,e){Oe[t]=e}static addKeyIdForUri(t){const e=Object.keys(Oe).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,e),Oe[t]=s,s}constructor(t,e,s,i=[1],r=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=t,this.uri=e,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!we(t),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Zr(a)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&ws(t.keyFormatVersions,this.keyFormatVersions)&&na(t.iv,this.iv)&&na(t.keyId,this.keyId)}isSupported(){if(this.method){if(we(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case kt.FAIRPLAY:case kt.WIDEVINE:case kt.PLAYREADY:case kt.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,e){var s;if(!this.encrypted||!this.uri)return null;if(we(this.method)){let a=this.iv;return a||(typeof t!="number"&&(at.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),a=Sd(t)),new ae(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){const a=Oe[this.uri];if(a&&!ws(this.keyId,a)&&ae.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=oa(this.uri);if(i)switch(this.keyFormat){case kt.WIDEVINE:if(this.pssh=i,!this.keyId){const a=gn(i.buffer).filter(o=>o.systemId===la.WIDEVINE);if(a.length){var r;const o=a[0];this.keyId=(r=o.kids)!=null&&r.length?o.kids[0]:null}}this.keyId||(this.keyId=ha(e));break;case kt.PLAYREADY:{const a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Th(a,null,i),this.keyId=Ui(i);break}default:{let a=i.subarray(0,16);if(a.length!==16){const o=new Uint8Array(16);o.set(a,16-a.length),a=o}this.keyId=a;break}}if(((s=this.keyId)==null?void 0:s.byteLength)!==16){let a;a=Td(e),a||(a=ha(e),a||(a=Oe[this.uri])),a&&(this.keyId=a,ae.setKeyIdForUri(this.uri,a))}return this}}function Td(n){const t=n?.[kt.WIDEVINE];return t?t.keyId:null}function ha(n){const t=n?.[kt.PLAYREADY];if(t){const e=oa(t.uri);if(e)return Ui(e)}return null}function Sd(n){const t=new Uint8Array(16);for(let e=12;e<16;e++)t[e]=n>>8*(15-e)&255;return t}const da=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,ca=/#EXT-X-MEDIA:(.*)/g,Ad=/^#EXT(?:INF|-X-TARGETDURATION):/m,Bi=new RegExp([/#EXTINF:\s*(\d+(?:\.\d*)?|\.\d+)?(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Id=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|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class zt{static findGroup(t,e){for(let s=0;s<t.length;s++){const i=t[s];if(i.id===e)return i}}static resolve(t,e){return ai.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Ad.test(t)}static parseMasterPlaylist(t,e){const s=sa(t),i={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(da.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let a;for(;(a=da.exec(t))!=null;)if(a[1]){const l=new vt(a[1],i),h=ua(l,a[2],e,i,r);h&&i.levels.push(h)}else if(a[3]){const l=a[3],h=a[4];switch(l){case"I-FRAME-STREAM-INF":{const d=new vt(h,i),c=ua(d,d.URI,e,i,r,!0);c&&i.iframeVariants.push(c)}break;case"SESSION-DATA":{const d=new vt(h,i),c=d["DATA-ID"];c&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[c]=d);break}case"SESSION-KEY":{const d=ga(h,e,i);d.encrypted&&d.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(d)):at.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const d=new vt(h,i);ia(i,d,e)}break}case"CONTENT-STEERING":{const d=new vt(h,i);i.contentSteering={uri:zt.resolve(d["SERVER-URI"],e),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=ma(h);break}}}const o=r.length>0&&r.length<i.levels.length;return i.levels=o?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,e,s){let i;const r={},a=s.levels,o={AUDIO:a.map(h=>({id:h.attrs.AUDIO,audioCodec:h.audioCodec})),SUBTITLES:a.map(h=>({id:h.attrs.SUBTITLES,textCodec:h.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(ca.lastIndex=0;(i=ca.exec(t))!==null;){const h=new vt(i[1],s),d=h.TYPE;if(d){const c=o[d],u=r[d]||[];r[d]=u;const f=h.LANGUAGE,g=h["ASSOC-LANGUAGE"],p=h.CHANNELS,v=h.CHARACTERISTICS,E=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?zt.resolve(h.URI,e):""};if(g&&(y.assocLang=g),p&&(y.channels=p),v&&(y.characteristics=v),E&&(y.instreamId=E),c!=null&&c.length){const T=zt.findGroup(c,y.groupId)||c[0];va(y,T,"audioCodec"),va(y,T,"textCodec")}u.push(y)}}return r}static parseLevelPlaylist(t,e,s,i,r,a){var o;const l={url:e},h=new Bn(e),d=h.fragments,c=[];let u=null,f=0,g=0,p=0,v=0,E=0,y=null,T=new Be(i,l),S,A,L,I=-1,b=!1,k=null,D;if(Bi.lastIndex=0,h.m3u8=t,h.hasVariableRefs=sa(t),((o=Bi.exec(t))==null?void 0:o[0])!=="#EXTM3U")return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;(S=Bi.exec(t))!==null;){b&&(b=!1,T=new Be(i,l),T.playlistOffset=p,T.setStart(p),T.sn=f,T.cc=v,E&&(T.bitrate=E),T.level=s,u&&(T.initSegment=u,u.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),k&&(T.setByteRange(k),k=null)));const G=S[1];if(G){T.duration=parseFloat(G);const M=(" "+S[2]).slice(1);T.title=M||null,T.tagList.push(M?["INF",G,M]:["INF",G])}else if(S[3]){if($(T.duration)){var C;T.playlistOffset=p,T.setStart(p),L&&Ea(T,L,h),T.sn=f,T.level=s,T.cc=v;const M=(" "+S[3]).slice(1);T.relurl=Oi(h,M),Gi(T,y,c),y=T,p+=T.duration,f++,g=0;const F=T.byteRange;if(F.length===2&&(T.bitrate=(F[1]-F[0])*8/T.duration|0),h.iframesOnly&&F[0]&&((C=u)==null?void 0:C.cc)!==v){const x=new Be(i,l);x.relurl=T.relurl,x.setByteRange(`${Math.min(F[0],1316)}@0`),x.level=s,x.sn="initSegment",L&&(x.levelkeys=L,L.identity&&(x._decryptdata=L.identity.getDecryptData(0))),u=x,T.initSegment=u}d.push(T),b=!0}}else{if(S=S[0].match(Id),!S){at.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<S.length&&S[A]===void 0;A++);const M=(" "+S[A]).slice(1),F=(" "+S[A+1]).slice(1),x=S[A+2]?(" "+S[A+2]).slice(1):null;switch(M){case"BYTERANGE":y?T.setByteRange(F,y):T.setByteRange(F);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=F,T.tagList.push(["PROGRAM-DATE-TIME",F]),I===-1&&(I=d.length);break;case"PLAYLIST-TYPE":h.type&&he(h,M,S),h.type=F.toUpperCase();break;case"MEDIA-SEQUENCE":h.startSN!==0?he(h,M,S):y!==null&&bd(h,M,S),h.startSN=parseInt(F),f=h.startSN+h.skippedSegments;break;case"SKIP":{h.skippedSegments&&he(h,M,S);const _=new vt(F,h),O=_.decimalInteger("SKIPPED-SEGMENTS");if($(O)){h.skippedSegments+=O;for(let j=O;j--;)d.push(null);f+=O}const H=_.enumeratedString("RECENTLY-REMOVED-DATERANGES");H&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(H.split(" ")));break}case"TARGETDURATION":h.targetduration!==0&&he(h,M,S),h.targetduration=Math.max(parseInt(F),1);break;case"VERSION":h.version!==null&&he(h,M,S),h.version=parseInt(F);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":h.iframesOnly=!0;break;case"ENDLIST":h.live||he(h,M,S),h.live=!1;break;case"#":(F||x)&&T.tagList.push(x?[F,x]:[F]);break;case"DISCONTINUITY":v++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([M]);break;case"BITRATE":T.tagList.push([M,F]),E=parseInt(F)*1e3,$(E)?T.bitrate=E:E=0;break;case"DATERANGE":{const _=new vt(F,h),O=new Mi(_,h.dateRanges[_.ID],h.dateRangeTagCount);h.dateRangeTagCount++,O.isValid||h.skippedSegments?h.dateRanges[O.id]=O:at.log(`Ignoring invalid DATERANGE tag: ${O.invalidReason}: ${F}`),T.tagList.push(["EXT-X-DATERANGE",F]);break}case"DEFINE":{{const _=new vt(F,h);"IMPORT"in _?cd(h,_,a):ia(h,_,e)}break}case"DISCONTINUITY-SEQUENCE":h.startCC!==0&&he(h,M,S),h.startCC=v=parseInt(F),d.forEach(_=>_&&(_.cc=v));break;case"KEY":{const _=ga(F,e,h);if(_.isSupported()){if(_.method==="NONE"){L=void 0;break}L||(L={});const O=L[_.keyFormat];O!=null&&O.matches(_)||(O&&(L=ht({},L)),L[_.keyFormat]=_)}else at.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${F}"`);break}case"START":h.startTimeOffset=ma(F);break;case"MAP":{const _=new vt(F,h);if(T.duration){const O=new Be(i,l);ya(O,_,s,L),u=O,T.initSegment=u,u.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=u.rawProgramDateTime)}else{const O=T.byteRangeEndOffset;if(O){const H=T.byteRangeStartOffset;k=`${O-H}@${H}`}else k=null;ya(T,_,s,L),u=T,b=!0}u.cc=v;break}case"SERVER-CONTROL":{D&&he(h,M,S),D=new vt(F),h.canBlockReload=D.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=D.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&D.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=D.optionalFloat("PART-HOLD-BACK",0),h.holdBack=D.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{h.partTarget&&he(h,M,S);const _=new vt(F);h.partTarget=_.decimalFloatingPoint("PART-TARGET");break}case"PART":{let _=h.partList;_||(_=h.partList=[]);const O=g>0?_[_.length-1]:void 0,H=g++,j=new vt(F,h),tt=new Nr(j,T,l,H,O);_.push(tt),T.duration+=tt.duration;break}case"PRELOAD-HINT":{const _=new vt(F,h);h.preloadHint=_;break}case"RENDITION-REPORT":{const _=new vt(F,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(_);break}default:at.warn(`line parsed but not handled: ${S}`);break}}}y&&!y.relurl?(d.pop(),p-=y.duration,h.partList&&(h.fragmentHint=y)):h.partList&&(Gi(T,y,c),T.cc=v,h.fragmentHint=T,L&&Ea(T,L,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));const w=d.length,N=d[0],U=d[w-1];if(p+=h.skippedSegments*h.targetduration,p>0&&w&&U){h.averagetargetduration=p/w;const G=U.sn;h.endSN=G!=="initSegment"?G:0,h.live||(U.endList=!0),I>0&&(Rd(d,I,I>w-1?T:null),N&&c.unshift(N))}return h.fragmentHint&&(p+=h.fragmentHint.duration),h.totalduration=p,c.length&&h.dateRangeTagCount&&N&&fa(c,h),h.endCC=v,h}}function ua(n,t,e,s,i,r){var a;if(t===void 0)return null;const o=Oi(s,t),l={attrs:n,bitrate:n.decimalInteger("BANDWIDTH")||n.decimalInteger("AVERAGE-BANDWIDTH"),name:n.NAME,url:zt.resolve(o,e)},h=n.decimalResolution("RESOLUTION");h&&(l.width=h.width,l.height=h.height),pa(n.CODECS,l);const d=n["SUPPLEMENTAL-CODECS"];return d&&(l.supplemental={},pa(d,l.supplemental)),(a=l.unknownCodecs)!=null&&a.length||i.push(l),r&&(l.iframes=!0),l}function fa(n,t){let e=n.length;if(!e)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];n.push(o),e++}else return;const s=n[e-1],i=t.live?1/0:t.totalduration,r=Object.keys(t.dateRanges);for(let o=r.length;o--;){const l=t.dateRanges[r[o]],h=l.startDate.getTime();l.tagAnchor=s.ref;for(let d=e;d--;){var a;if(((a=n[d])==null?void 0:a.sn)<t.startSN)break;const c=Ld(t,h,n,d,i);if(c){l.tagAnchor=c.ref;break}}}}function Ld(n,t,e,s,i){const r=e[s];if(r){const o=r.programDateTime;if(t>=o||s===0){var a;const l=(((a=e[s+1])==null?void 0:a.start)||i)-r.start;if(t<=o+l*1e3){const h=r.sn-n.startSN,d=n.fragments;if(h>=0&&h<d.length){if(d.length>e.length){const c=e[s+1]||d[d.length-1],u=Math.min(c.sn-n.startSN,d.length-1);for(let f=u;f>h;f--){const g=d[f].programDateTime;if(t>=g&&t<g+d[f].duration*1e3)return d[f]}}return d[h]}}}}return null}function ga(n,t,e){var s,i;const r=new vt(n,e),a=(s=r.METHOD)!=null?s:"",o=r.URI,l=r.hexadecimalInteger("IV"),h=r.KEYFORMATVERSIONS,d=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!l&&at.error(`Invalid IV: ${r.IV}`);const c=o?zt.resolve(o,t):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new ae(a,c,d,u,l,r.KEYID)}function ma(n){const t=new vt(n).decimalFloatingPoint("TIME-OFFSET");return $(t)?t:null}function pa(n,t){let e=(n||"").split(/[ ,]+/).filter(s=>s);["video","audio","text","image"].forEach(s=>{const i=e.filter(r=>Ii(r,s));i.length&&(t[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),e=e.filter(r=>i.indexOf(r)===-1))}),t.unknownCodecs=e}function va(n,t,e){const s=t[e];s&&(n[e]=s)}function Rd(n,t,e){if(e||(e=n[t]),!!e)for(let s=t;s--;){const i=n[s];if(!i)return;i.programDateTime=e.programDateTime-i.duration*1e3,e=i}}function Gi(n,t,e){n.rawProgramDateTime?e.push(n):t!=null&&t.programDateTime&&(n.programDateTime=t.endProgramDateTime)}function ya(n,t,e,s){n.relurl=t.URI,t.BYTERANGE&&n.setByteRange(t.BYTERANGE),n.level=e,n.sn="initSegment",s&&(n.levelkeys=s),n.initSegment=null}function Ea(n,t,e){n.levelkeys=t;const{encryptedFragments:s}=e;(!s.length||s[s.length-1].levelkeys!==t)&&Object.keys(t).some(i=>t[i].isCommonEncryption)&&s.push(n)}function he(n,t,e){n.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${e[0]})`)}function bd(n,t,e){n.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${e[0]})`)}function Ki(n,t){const e=t.startPTS;if($(e)){let s=0,i;t.sn>n.sn?(s=e-n.start,i=n):(s=n.start-e,i=t),i.duration!==s&&i.setDuration(s)}else t.sn>n.sn?n.cc===t.cc&&n.minEndPTS?t.setStart(n.start+(n.minEndPTS-n.start)):t.setStart(n.start+n.duration):t.setStart(Math.max(n.start-t.duration,0))}function Ta(n,t,e,s,i,r,a,o){s-e<=0&&(o.warn("Fragment should have a positive duration",t),s=e+t.duration,r=i+t.duration);let l=e,h=s;const d=t.startPTS,c=t.endPTS;if($(d)){const f=Math.abs(d-e);n&&f>n.totalduration?o.warn(`media timestamps and playlist times differ by ${f}s for level ${t.level} ${n.url}`):$(t.deltaPTS)?t.deltaPTS=Math.max(f,t.deltaPTS):t.deltaPTS=f,l=Math.max(e,d),e=Math.min(e,d),i=t.startDTS!==void 0?Math.min(i,t.startDTS):i,h=Math.min(s,c),s=Math.max(s,c),r=t.endDTS!==void 0?Math.max(r,t.endDTS):r}const u=e-t.start;return t.start!==0&&t.setStart(e),t.setDuration(s-t.start),t.startPTS=e,t.maxStartPTS=l,t.startDTS=i,t.endPTS=s,t.minEndPTS=h,t.endDTS=r,Sa(n,t,u)}function Sa(n,t,e){var s;const i=t.sn;if(!n||i<n.startSN||i>(((s=n.fragmentHint)==null?void 0:s.sn)||n.endSN))return 0;let r;const a=i-n.startSN,o=n.fragments;for(o[a]=t,r=a;r>0;r--)Ki(o[r],o[r-1]);for(r=a;r<o.length-1;r++)Ki(o[r],o[r+1]);return n.fragmentHint&&Ki(o[o.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,e}function Dd(n,t,e){if(n===t)return;let s=null;const i=n.fragments;for(let d=i.length-1;d>=0;d--){const c=i[d].initSegment;if(c){s=c;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let r;_d(n,t,(d,c,u,f)=>{if(c.cc!==d.cc&&(d.cc>c.cc||t.skippedSegments)){const g=d.cc-c.cc;for(let p=u;p<f.length;p++)f[p].cc+=g;t.endCC=f[f.length-1].cc}$(d.startPTS)&&$(d.endPTS)&&(c.setStart(c.startPTS=d.startPTS),c.startDTS=d.startDTS,c.maxStartPTS=d.maxStartPTS,c.endPTS=d.endPTS,c.endDTS=d.endDTS,c.minEndPTS=d.minEndPTS,c.setDuration(d.endPTS-d.startPTS),c.duration&&(r=c),t.PTSKnown=t.alignedSliding=!0),d.hasStreams&&(c.elementaryStreams=d.elementaryStreams),c.loader=d.loader,c.gap=d.gap||c.gap,d.hasStats&&(c.stats=d.stats),d.initSegment&&(c.initSegment=d.initSegment,s=d.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(s&&o.forEach(d=>{var c;d&&(!d.initSegment||d.initSegment.relurl===((c=s)==null?void 0:c.relurl))&&(d.initSegment=s)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(d=>!d),t.deltaUpdateFailed){e.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let d=t.skippedSegments;d--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=kd(n.dateRanges,t,e));const d=n.fragments.filter(c=>c.rawProgramDateTime);if(n.hasProgramDateTime&&!t.hasProgramDateTime)for(let c=1;c<o.length;c++)o[c].programDateTime===null&&Gi(o[c],o[c-1],d);fa(d,t)}t.endCC=a[a.length-1].cc}else if(t.startSN>n.endSN&&a[0].cc<n.endCC){const d=n.endCC-a[0].cc;o.forEach(c=>{c.cc+=d}),t.endCC+=d}if(!t.startCC){var l;const d=xs(n,t.startSN-1);t.startCC=(l=d?.cc)!=null?l:a[0].cc}if(Pd(n.partList,t.partList,(d,c)=>{c.elementaryStreams=d.elementaryStreams,c.stats=d.stats,c.gap=d.gap||c.gap}),r){const d=t.iframesOnly&&r.type===K.MAIN;Ta(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,d,e)}else Ia(n,t);a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=n.driftStartTime,t.driftStart=n.driftStart;const h=t.advancedDateTime;if(t.advanced&&h){const d=t.edge;t.driftStart||(t.driftStartTime=h,t.driftStart=d),t.driftEndTime=h,t.driftEnd=d}else t.driftEndTime=n.driftEndTime,t.driftEnd=n.driftEnd,t.advancedDateTime=n.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=n.requestScheduled)}function kd(n,t,e){const{dateRanges:s,recentlyRemovedDateranges:i}=t,r=ht({},n);i&&i.forEach(o=>{delete r[o]});const a=Object.keys(r).length;return a?(Object.keys(s).forEach(o=>{const l=r[o],h=new Mi(s[o].attr,l);h.isValid?(r[o]=h,l||(h.tagOrder+=a)):e.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ft(s[o].attr)}"`)}),r):s}function Pd(n,t,e){if(n&&t){let s=0;for(let i=0,r=n.length;i<r;i++){const a=n[i],o=t[i+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?e(a,o):s--}}}function _d(n,t,e){var s;const i=t.skippedSegments,r=Math.max(n.startSN,t.startSN)-t.startSN,a=(n.fragmentHint?1:0)+(i?t.endSN:Math.min(n.endSN,t.endSN))-t.startSN,o=t.startSN-n.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,h=(s=n.fragmentHint)!=null&&s.duration?n.fragments.concat(n.fragmentHint):n.fragments;for(let d=r;d<=a;d++){const c=h[o+d];let u=l[d];if(i&&!u&&c&&(u=t.fragments[d]=c),c&&u){e(c,u,d,l);const f=c.relurl,g=u.relurl;if(f&&wd(f,g)){t.playlistParsingError=Aa(`media sequence mismatch ${u.sn}:`,n,t,c,u);return}else if(c.cc!==u.cc){t.playlistParsingError=Aa(`discontinuity sequence mismatch (${c.cc}!=${u.cc})`,n,t,c,u);return}}}}function Aa(n,t,e,s,i){return new Error(`${n} ${i.url}
17
+ Playlist starting @${t.startSN}
18
+ ${t.m3u8}
19
+
20
+ Playlist starting @${e.startSN}
21
+ ${e.m3u8}`)}function Ia(n,t,e=!0,s){const i=t.startSN+t.skippedSegments-n.startSN,r=n.fragments,a=i>=0;let o=0;if(a&&i<r.length)o=r[i].start,s?.log(`Aligning playlists based on SN ${t.startSN} (diff: ${o})`);else if(a&&t.startSN===n.endSN+1)o=n.fragmentEnd,s?.log(`Aligning playlists based on first/last SN ${t.startSN} (diff: ${o})`);else if(a&&e)o=n.fragmentStart+i*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)o=n.fragmentStart,s?.log(`Aligning playlists based on first SN ${t.startSN} (diff: ${o})`);else return o;return Cd(t,o),o}function Cd(n,t){if(t){const e=n.fragments;for(let s=n.skippedSegments;s<e.length;s++)e[s].addStart(t);n.fragmentHint&&n.fragmentHint.addStart(t)}}function La(n,t=1/0){let e=1e3*n.targetduration;if(n.updated){const s=n.fragments;if(s.length&&e*4>t){const i=s[s.length-1].duration*1e3;i>0&&i<e&&(e=i)}}else e/=2;return Math.round(e)}function xs(n,t,e){var s;if(!n)return null;let i=n.fragments[t-n.startSN];return i||(i=n.fragmentHint,((s=i)==null?void 0:s.sn)===t)?i:e&&t<n.startSN&&e.sn===t?e:null}function Ra(n,t,e){return n?ba(n.partList,t,e):null}function ba(n,t,e){if(n)for(let s=n.length;s--;){const i=n[s];if(i.index===e&&i.fragment.sn===t)return i}return null}function Da(n){n.forEach((t,e)=>{var s;(s=t.details)==null||s.fragments.forEach(i=>{i.level=e,i.initSegment&&(i.initSegment.level=e)})})}function wd(n,t){return n!==t&&t?ka(n)!==ka(t):!1}function ka(n){return n.replace(/\?[^?]*$/,"")}function Ze(n,t){for(let s=0,i=n.length;s<i;s++){var e;if(((e=n[s])==null?void 0:e.cc)===t)return n[s]}return null}function Od(n,t){return!!(n&&t.startCC<n.endCC&&t.endCC>n.startCC)}function Pa(n,t){const e=n.start+t;n.setStart(e)}function _a(n,t){const e=t.fragments;for(let s=0,i=e.length;s<i;s++)Pa(e[s],n);t.fragmentHint&&Pa(t.fragmentHint,n),t.alignedSliding=!0}function Fs(n,t,e){n&&(Md(t,n,e),t.alignedSliding||xd(t,n,e),!t.alignedSliding&&!t.skippedSegments&&Ia(n,t,!1,e))}function Md(n,t,e){if(!Od(t,n))return;const s=Math.min(t.endCC,n.endCC),i=Ze(t.fragments,s),r=Ze(n.fragments,s);if(!i||!r)return;const a=i.start-r.start;e.log(`Aligning playlists using dicontinuity sequence ${s} (diff: ${a})`),_a(a,n)}function xd(n,t,e){if(!n.hasProgramDateTime||!t.hasProgramDateTime)return;const s=n.fragments,i=t.fragments;if(!s.length||!i.length)return;let r,a;const o=Math.min(t.endCC,n.endCC);t.startCC<o&&n.startCC<o&&(r=Ze(i,o),a=Ze(s,o)),(!r||!a)&&(r=i[Math.floor(i.length/2)]||i.filter(u=>!!u)[0],a=Ze(s,r.cc)||s[Math.floor(s.length/2)]);const l=r.programDateTime,h=a.programDateTime;if(!l||!h)return;const d=(h-l)/1e3;if(Math.abs(d)>Math.max(60,n.totalduration)){e.log(`Cannot align playlists using PDT without overlap (${Math.abs(d)} > ${n.totalduration})`);return}const c=d-(a.start-r.start);e.log(`Aligning playlists using PDT (diff: ${c})`),_a(c,n)}const P={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 Ns extends ea{constructor(t,e,s,i,r){super(i,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=P.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=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:o,media:l,mediaBuffer:h,state:d}=this,c=l?l.currentTime:0,u=q.bufferInfo(h||l,c,a.maxBufferHole),f=u.len;if(this.log(`Media seeking to ${c}, state: ${d}, ${f?"in":"out of"} buffer`),this.state===P.ENDED)this.resetLoadingState();else if(o){const v=a.maxFragLookUpTolerance,E=o.start-v,y=o.start+o.duration+v;if(!f||y<u.start||E>u.end){const T=c<E,S=c>y;(T||S)&&(o.loader&&(S||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${T?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(l){var g;(g=this.hls)!=null&&g.hasEnoughToStart&&!f&&c!==this.startPosition&&this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0);const v=this.lastCurrentTime;if(c>v&&(this.lastCurrentTime=c),!this.loadingParts){const E=Math.max(u.end,c),y=this.shouldLoadParts(this.getLevelDetails(),E);y&&(this.log(`LL-Part loading ON after seeking to ${c} with buffer @${E}`),this.loadingParts=y)}}const p=!q.isBuffered(l,c);(!this.hls.hasEnoughToStart||p)&&(this.log(`Setting ${p?"startPosition":"nextLoadPosition"} to ${c} for seek without enough to start`),this.nextLoadPosition=c,p?this.startPosition=c:this.lastCurrentTime=c),f<1&&this.state===P.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.nextLoadPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new Jn(t.config),this.initFragmentLoader=new Jn(t.config),this.keyLoader=s,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Ci(t.config)}registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(m.ERROR,this.onError,this)}doTick(){}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&t.seeking===!1&&(this.lastCurrentTime=t.currentTime)}startLoad(t){}stopLoad(){if(this.state===P.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;t!=null&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=P.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;if(e===-1&&t){const s=this.getLevelDetails();return s!=null&&s.live?(this.hls.liveSyncPosition||s.fragmentStart)+this.timelineOffset:t}return e}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(t){}get couldBacktrack(){return!1}set couldBacktrack(t){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const s=t.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=q.bufferedInfo(r,t.start,0));const a=t.nextStart;if(a&&a>i&&a<e.edge||this.media.currentTime<t.start)return!1;const o=e.partList;if(o!=null&&o.length){const h=o[o.length-1];return q.isBuffered(this.media,h.start+h.duration/2)}const l=e.fragments[e.fragments.length-1];return this.fragmentTracker.isEndListAppended(l.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;if(t){var e;return((e=this.getLevelDetails())==null?void 0:e.appliedTimelineOffset)||t}return 0}onMediaAttached(t,e){const s=this.media=this.mediaBuffer=e.media;lt(s,"seeking",this.onMediaSeeking),lt(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===P.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(t,e){this.fragPlaying=null;const s=!!e.transferMedia,i=this.media;if(i===null)return;if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ot(i,"seeking",this.onMediaSeeking),ot(i,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1;const{fragmentTracker:r}=this,a=r.gapFragments();r.removeAllFragments(),a.forEach(o=>r.addAsGap(o)),this.stopLoad()}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.nextLoadPosition=0,this.startPosition=-1,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=P.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,s){this.startFragRequested=!0,this._loadFragForPlayback(t,e,s)}_loadFragForPlayback(t,e,s){const i=r=>{const a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)} was dropped during download.`),this.fragmentTracker.removeFragment(a);return}const o=++a.stats.chunkCount;this.log(`load progress ${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)} chunk: ${o}`),this._handleFragmentLoadProgress(r)};this._doFragLoad(t,e,s,i).then(r=>{if(!r)return;const a=this.state,o=r.frag;if(this.fragContextChanged(o)){(a===P.FRAG_LOADING||!this.fragCurrent&&a===P.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=P.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level} (bytes ${o.stats.loaded})`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===P.STOPPED||this.state===P.ERROR||(this.log(`Frag error ${t.type} sn:${t.sn} cc:${t.cc}: ${r?.message||r}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===mt.APPENDING){const i=t.type,r=this.getFwdBufferInfo(this.mediaBuffer,i),a=Math.max(t.duration,r?r.len:this.config.maxBufferLength),o=this.backtrackFragment;((o?t.sn-o.sn:0)===1||this.reduceMaxBufferLength(a,t.duration))&&s.removeFragment(t)}else((e=this.mediaBuffer)==null?void 0:e.buffered.length)===0?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===mt.PARTIAL&&s.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=this.fragmentTracker,s=t.fragments[t.fragments.length-1];if(s.endList&&!e.isEndListAppended(this.playlistType)){const i=e.getPartialFragment(s.end);i&&(e.removeFragment(i),e.fragBuffered(s,!0))}e.detectPartialFragments({frag:s,part:null,stats:s.stats,id:s.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return e?.live&&e.type!=="EVENT"&&e.advancedDateTime!==void 0&&(e.expired||this.loadingParts&&e.partsExpired||e.misses<3&&e.partEnd<=this.getLoadPosition())}flushMainBuffer(t,e,s=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(t){const{hls:e}=this;return this.initFragmentLoader.abort(),e.trigger(m.FRAG_LOADING,{frag:t,targetBufferTime:0}),this.initFragmentLoader.load(t).then(s=>{var i;const r=s.frag;if(!this.levels||!li(r,(i=this.fragCurrent)==null?void 0:i.initSegment))throw new ie({type:Y.NETWORK_ERROR,details:R.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:r,networkDetails:null});return s}).then(s=>{const{frag:i,payload:r}=s,a=i.decryptdata;if(r&&r.byteLength>0&&a!=null&&a.key&&a.iv&&we(a.method)){const o=self.performance.now(),{decryptRange:l}=Ps(i,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,xi(a.method),l).catch(h=>{throw e.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:h,reason:h.message,frag:i}),this.fragmentLoader.abort(),h}).then(h=>{const d=self.performance.now();return e.trigger(m.FRAG_DECRYPTED,{frag:i,part:null,payload:h,stats:{tstart:o,tdecrypt:d}}),s.payload=h,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)})}completeInitSegmentLoad(t){const e=t.frag.stats;t.frag.data=new Uint8Array(t.payload),e.parsing.start=e.buffering.start=self.performance.now(),e.parsing.end=e.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(t){const{initSegment:e}=t;if(!this.bitrateTest&&Et(t)&&e&&!e.data){var s;return(e.encrypted&&!((s=e.decryptdata)!=null&&s.key)?this.keyLoader.load(e).then(()=>this._loadInitSegment(e)):this._loadInitSegment(e)).catch(i=>{throw this.state===P.STOPPED||this.state===P.ERROR||("data"in i&&(this.fragmentLoader.abort(),this.handleFragLoadError(i,t)),this.resetFragmentLoading(t)),i})}}unhandledEncryptionError(t,e){var s,i;const r=t.tracks;if(r&&!e.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(m.ERROR,{type:Y.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!li(t,e)}fragBufferedComplete(t,e){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${s?Ds(q.getBuffered(s)):"(detached)"})`),Et(t)){var i;if(t.type!==K.SUBTITLE){const a=t.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=P.IDLE;return}}const r=(i=this.levels)==null?void 0:i[t.level];r!=null&&r.fragmentError&&(e||this.fragmentTracker.getState(t)!==mt.PARTIAL)&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0,t.stats.retry=0)}this.state=P.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const s=t.frag,{part:i,partsLoaded:r}=t,a=!r||r.length===0||r.some(h=>!h),{decryptRange:o}=Ps(s,i),l=new _s(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!a,s.duration,this.iframesOnly,o);this.log(`load complete ${s.type} sn: ${s.sn}${i?" part: "+i.index:""} of ${this.fragInfo(s,!1,i)}`),e.flush(l)}_handleFragmentLoadProgress(t){}loadKeyFor(t,e,s){var i;let r=null;return t.encrypted&&!((i=t.decryptdata)!=null&&i.key)?(this.log(`Loading key for ${t.sn} of [${e.startSN}-${e.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=P.KEY_LOADING,r=this.keyLoader.load(t,s).then(a=>{if(!this.fragContextChanged(a.frag))return this.hls.trigger(m.KEY_LOADED,a),this.state===P.KEY_LOADING&&(this.state=P.IDLE),a}),this.hls.trigger(m.KEY_LOADING,{frag:t})):t.encrypted||(r=this.keyLoader.loadClear(t,e.encryptedFragments,this.startFragRequested),r&&this.log(`[eme] blocking frag sn: ${t.sn} load until media-keys acquired`)),r}_doFragLoad(t,e,s=null,i){this.fragCurrent=t;const r=e.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);const a=this.fragPrevious;if(!Ue(t,a)){const f=this.shouldLoadParts(e.details,t.end);f!==this.loadingParts&&(this.log(`LL-Part loading ${f?"ON":"OFF"} loading sn ${a?.sn}->${t.sn}`),this.loadingParts=f)}if(s=Math.max(t.start,s||0),this.loadingParts){const f=r.partList;if(f&&i){s>r.fragmentEnd&&r.fragmentHint&&(t=r.fragmentHint);const g=this.getNextPart(f,t,s);if(g>-1){const p=f[g];if(t=this.fragCurrent=p.fragment,!Ue(t,a)&&!this.shouldLoadParts(e.details,t.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(t,!1,p)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(p,e.details))return Promise.resolve(null);const v=this.loadKeyFor(t,r);if(this.fragContextChanged(t))return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} part: ${p.index} (${g}/${f.length-1}) of ${this.fragInfo(t,!1,p)} cc: ${t.cc} [${r.startSN}-${r.endSN}], target: ${s}${p.byteRange.length?` range:${p.byteRange.join("-")}`:""}`),this.nextLoadPosition=p.start+p.duration,this.state=P.FRAG_LOADING;let E;const y=this.loadInitSegmentIfNeeded(t);if(v||y){const T=!!v;E=Promise.all([v,y]).then(([S])=>T&&(!S||this.fragContextChanged(S.frag))?null:this.doFragPartsLoad(t,p,e,i)).catch(S=>this.handleFragLoadError(S,t))}else E=this.doFragPartsLoad(t,p,e,i).catch(T=>this.handleFragLoadError(T,t));return this.hls.trigger(m.FRAG_LOADING,{frag:t,part:p,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):E}else if(!t.url||this.loadedEndOfParts(f,s))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${s} Check buffer at sn: ${t.sn} loaded parts: ${(o=r.partList)==null?void 0:o.filter(f=>f.loaded).map(f=>`[${f.start}-${f.end}]`)}`),this.loadingParts=!1}else if(!t.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(t,e.details))return Promise.resolve(null);const l=this.loadInitSegmentIfNeeded(t),h=this.loadKeyFor(t,r,l);if(this.fragContextChanged(t)){var d;return this.log(`Context changed in KEY_LOADING sn: ${t.sn} ${t.relurl} > ${(d=this.fragCurrent)==null?void 0:d.relurl}`),l?.catch(()=>null),h?.catch(()=>null),Promise.resolve(null)}this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)} cc: ${t.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${s}${t.byteRange.length?` range:${t.byteRange.join("-")}`:""}`),$(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=P.FRAG_LOADING;const c=this.config.progressive&&t.type!==K.SUBTITLE;let u;return c&&h?u=h.then(f=>!f||this.fragContextChanged(f.frag)?null:this.fragmentLoader.load(t,this.iframesOnly,i,l)).catch(f=>this.handleFragLoadError(f,t)):u=Promise.all([this.fragmentLoader.load(t,this.iframesOnly,c?i:void 0,c?l:void 0),h,l]).then(([f])=>(!c&&i&&i(f),f)).catch(f=>this.handleFragLoadError(f,t)),this.hls.trigger(m.FRAG_LOADING,{frag:t,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([u,l]).then(([f])=>f)}doFragPartsLoad(t,e,s,i){return new Promise((r,a)=>{var o;const l=[],h=(o=s.details)==null?void 0:o.partList,d=c=>{this.fragmentLoader.loadPart(t,c,i).then(u=>{l[c.index]=u;const f=u.part;this.hls.trigger(m.FRAG_LOADED,u);const g=Ra(s.details,t.sn,c.index+1)||ba(h,t.sn,c.index+1);if(g)d(g);else return r({frag:t,part:f,partsLoaded:l})}).catch(a)};d(e)})}handleFragLoadError(t,e){if("data"in t){const s=t.data;s.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(e,s.part):s.type===Y.KEY_SYSTEM_ERROR&&!s.fatal&&(e.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e)),s.frag!==e?(s.frag&&this.warn(`${s.details} error cascading from ${this.fragInfo(s.frag,!1,s.part)} to ${this.fragInfo(e,!1)}`),this.hls.trigger(m.ERROR,W(W({},s),{},{frag:e}))):this.hls.trigger(m.ERROR,s)}else this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==P.PARSING){!this.fragCurrent&&this.state!==P.STOPPED&&this.state!==P.ERROR&&(this.state=P.IDLE);return}const{frag:s,part:i,level:r}=e,a=self.performance.now();s.stats.parsing.end=a,i&&(i.stats.parsing.end=a);const o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end}`),this.loadingParts=l),this.updateLevelTiming(s,i,r,t)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList&&!this.iframesOnly){var s;const i=t.partList[0],r=i.end+(((s=t.fragmentHint)==null?void 0:s.duration)||0);if(e>=r&&this.playhead>i.start-i.fragment.duration)return!0}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:i,sn:r,part:a}=t;if(!(e!=null&&e[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=e[i],l=o.details,h=a>-1?Ra(l,r,a):null,d=h?h.fragment:xs(l,r,s);return d?(s&&s!==d&&(d.stats=s.stats),{frag:d,part:h,level:o}):null}bufferFragmentData(t,e,s,i,r){if(this.state!==P.PARSING)return;Et(e)&&!this.fragContextChanged(e)&&(this.fragPrevious=e);const{data1:a,data2:o}=t;let l=a;if(o&&(l=Gt(a,o)),!l.length)return;const h=this.initPTS[e.cc],d=h?-h.baseTime/h.timescale:void 0,c={type:t.type,frag:e,part:s,chunkMeta:i,offset:d,parent:e.type,data:l};if(this.hls.trigger(m.BUFFER_APPENDING,c),t.dropped&&t.independent&&!s){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!q.isBuffered(e,e.currentTime)){this.flushMainBuffer(0,t.start);return}const s=e.currentTime,i=q.bufferInfo(e,s,0),r=t.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(t.start-a,i.end-a),s+a);t.start-o>a&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,e){var s;const i=this.playhead,r=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,i,e,r)}getFwdBufferInfoAtPos(t,e,s,i){const r=q.bufferInfo(t,e,i);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(e,s);if(a&&(r.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(r.nextStart,a.end)-e,i);return q.bufferInfo(t,e,o)}}return r}getMaxBufferLength(t){const{config:e}=this;let s;return t?s=Math.max(8*e.maxBufferSize/t,e.maxBufferLength):s=e.maxBufferLength,Math.min(s,e.maxMaxBufferLength)}exceedsMaxBuffer(t,e,s){const i=t.nextStart;if(i&&s.start>i){const r=t.buffered;if(r){let a=t.len;const o=t.bufferedIndex;for(let l=r.length-1;l>o;l--)r[l].start<s.start&&(a+=r[l].end-r[l].start);return a>=e}}return!1}reduceMaxBufferLength(t,e){const s=this.config,i=Math.max(Math.min(t-e,s.maxBufferLength),e/2),r=Math.max(t-e*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(t){const e=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,this.playlistType):null;return e&&"fragment"in e?e.fragment:e}getNextFragment(t,e){const s=e.fragments,i=s.length;if(!i)return null;const{config:r}=this,a=e.fragmentStart,o=r.lowLatencyMode&&!!e.partList;let l=null;if(e.live){const c=r.initialLiveManifestSize;if(i<c)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${c})`),null;if(!this.startFragRequested&&o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!e.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||t<a){var h;l=this.getInitialLiveFragment(e);const u=this.config.startPosition,f=this.hls.startPosition,g=this.hls.liveSyncPosition,p=((h=l)==null?void 0:h.start)||0;let v,E;if(f!==-1&&f>=a?(v=f,E=f===u?"config":"next load start"):g?(v=g,E="live edge"):(v=t,E="buffer pos"),v<p&&(v=p,E="live frag start"),v<a&&(v=a,E="playlist start"),this.startPosition!=v||this.nextLoadPosition!=v){const y=e.live&&!this.filterReplacedPrimary(l,e)?-1:v;this.log(`Setting startPosition to ${y} next load ${v} ${f===-1?"":`(from ${u}) `}based on ${E}. live edge: ${g} live frag start: ${p} playlist start: ${a} buffer pos: ${t}`),this.startPosition=y,this.nextLoadPosition=v}}}else t<=a&&(l=s[0]);if(!l){const c=this.loadingParts?e.partEnd:e.fragmentEnd;l=this.getFragmentAtPosition(t,c,e)}let d=this.filterReplacedPrimary(l,e);return!d&&l&&(d=xn(e,l.sn),d&&(this.nextLoadPosition=d.start)),d}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;const s=this.fragmentTracker.getState(t);return!!(s===mt.OK||s===mt.PARTIAL&&(t.gap||t.stats.retry>1))}getNextFragmentLoopLoading(t,e,s,i,r){let a=null;if(t.gap&&(a=this.getNextFragment(this.nextLoadPosition,e),a&&!a.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if($s(this.config)){var t;if(!((t=this.hls.interstitialsManager)==null||(t=t.playingItem)==null)&&t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if($s(this.config)&&("type"in t?t:t.fragment).type!==K.SUBTITLE){const s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){const r=i.event;if(r){if(!r.appendInPlace&&(Math.abs(t.start-i.start)>1||i.start===0))return null}else if(t.end<=i.start&&e?.live===!1||t.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||t.start-i.end>1))return null}if(Ca(t,s?.playerQueue,this.playhead))return null}return t}getNextPart(t,e,s){let i=-1,r=!1,a=!0;for(let l=0,h=t.length;l<h;l++){const d=t[l];if(a=a&&!d.independent,i>-1&&s<d.start)break;const c=d.loaded||d.gap;c?i=-1:(r||(d.independent||a)&&d.fragment===e)&&(i=l),r=c&&!d.gap}const o=t[i];return o&&o.fragment!==e&&this.log(`Need buffer at ${s} but next unloaded part starts at ${o.start} (sn: ${e.sn} -> ${o.fragment.sn})`),i}loadedEndOfParts(t,e){let s;for(let i=t.length;i--;){if(s=t[i],!s.loaded)return!1;if(e>s.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,s=this.fragPrevious;let i=null;if(s){if(t.hasProgramDateTime&&(i=zh(e,s.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!i){const r=s.sn+1;if(r>=t.startSN&&r<=t.endSN){const a=e[r-t.startSN];s.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Mn(t,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i}getFragmentAtPosition(t,e,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=s;const{fragmentHint:l}=s,{maxFragLookUpTolerance:h}=i,d=s.partList,c=!!(this.loadingParts&&d!=null&&d.length&&l);c&&!this.bitrateTest&&d[d.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn),r&&this.fragmentTracker.getState(r)===mt.NOT_LOADED&&(r=null);let u;if(t<e){var f;const g=t<this.lastCurrentTime||t>e-h||(f=this.media)!=null&&f.paused||this.loadingParts||!this.startFragRequested?0:h;u=_e(r,a,t,g)}else u=a[a.length-1];if(u){const g=u.sn,p=g-s.startSN,v=this.fragmentTracker.getState(u);if((v===mt.OK||v===mt.PARTIAL&&u.gap)&&(r=u),Ue(u,r)&&(!c||d[0].fragment.sn>g||!s.live||!d.some(E=>E.fragment.sn===g&&!E.loaded&&!E.gap))){const E=a[p+1];u.sn<o&&this.fragmentTracker.getState(E)!==mt.OK?u=E:u=null}}return u}alignPlaylists(t,e,s){const i=t.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=t.fragmentStart,a=!e,o=t.alignedSliding&&$(r);if(a||!o&&!r){Fs(s,t,this);const l=t.fragmentStart;return this.log(`Live playlist sliding: ${l} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${i}`),l}return r}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,e){let s=this.startPosition;s<e&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,a=r?this.startTimeOffset:t.startTimeOffset;if(a!==null&&$(a))s=e+a,a<0&&(s+=t.edge),s=Math.min(Math.max(e,s),e+t.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s;else if(t.live){const o=this.hls.liveSyncPosition;s=o||e,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${s}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=s=0;this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var t;const{media:e}=this;let s=0;return(t=this.hls)!=null&&t.hasEnoughToStart&&e&&!this.iframesOnly?s=e.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}get playhead(){var t;if((t=this.hls)!=null&&t.hasEnoughToStart){var e;const s=(e=this.media)==null?void 0:e.currentTime;return $(s)?s:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var t;if(this.playlistType!==K.MAIN)return!1;const e=this.getLevelDetails();return e?e.iframesOnly:(t=this.levelLastLoaded)==null?void 0:t.iframes}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&Et(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.state!==P.STOPPED&&(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==P.FRAG_LOADING_WAITING_RETRY)&&(this.state=P.IDLE)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const y=this.getCurrentContext(e.chunkMeta);y&&(e.frag=y.frag)}const{frag:s,part:i}=e;if(!s||!this.levels||s.type!==t)return;if(this.fragContextChanged(s)){var r;this.warn(`Frag load error must match current frag to retry ${s.relurl} > ${(r=this.fragCurrent)==null?void 0:r.relurl}`);return}const a=e.details===R.FRAG_GAP;a&&this.fragmentTracker.addAsGap(s);const o=e.errorAction;if(!o){this.state=P.ERROR;return}const{action:l,flags:h,retryCount:d=0,retryConfig:c}=o,u=!!c,f=u&&l===Dt.RetryRequest,g=u&&!o.resolved&&h&bt.MoveAllAlternatesMatchingHost,p=this.hls.latestLevelDetails,v=p?.live;if(!f&&g&&Et(s)&&v&&s.sn<p.endSN&&!Gr(e))this.resetFragmentErrors(t),i?i.gap=!0:this.treatAsGap(s),o.resolved=!0;else if((f||g)&&d<c.maxNumRetry){var E;const y=Ke((E=e.response)==null?void 0:E.code),T=hi(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=P.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,y){this.log("Waiting for connection (offline)"),this.retryDate=1/0,e.reason="offline";return}this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${d+1}/${c.maxNumRetry} in ${T}ms`)}else if(c)if(this.resetFragmentErrors(t),d<c.maxNumRetry)!a&&l!==Dt.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${e.details} reached or exceeded max retry (${d})`);return}else l===Dt.SendAlternateToPenaltyBox?this.state=P.WAITING_LEVEL:this.state=P.ERROR;this.tickImmediate()}onSourceBufferError(t,e){var s,i;const{frag:r,part:a,sourceBufferName:o}=e,l=r&&((s=this.levels)==null||(s=s[r.level])==null?void 0:s.details);if(e.error.name!==Hn||r?.type!==t||!Et(r)||!(l!=null&&l.live))return;const h=a?a.index===0?a:null:r,d=h&&o?(i=h.elementaryStreams[o])==null?void 0:i.startPTS:void 0;if(this.markSourceBufferErrorGap(xs(l,r.sn)||r),d===void 0)return;const c=xs(l,r.sn-1);c&&this.fragmentTracker.getState(c)!==mt.NOT_LOADED&&!q.isBuffered(this.mediaBuffer||this.media,d-this.config.maxBufferHole)&&this.markSourceBufferErrorGap(c)}markSourceBufferErrorGap(t){this.warn(`Marking fragment ${t.sn} of ${this.playlistLabel()} ${t.level} as a gap after a SourceBuffer error`),this.fragmentTracker.addAsGap(t)}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,s=e===1/0;(!e||t>=e||s&&!Ke(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=P.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===P.PARSING||this.state===P.PARSED){const e=t.frag,s=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,e?.duration||10);const a=!r;return a?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${s} buffer`):i.nextStart&&e&&i.nextStart>e.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,s===K.AUDIO?s:void 0),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(t){t===K.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==P.STOPPED&&(this.state=P.IDLE)}afterBufferFlushed(t,e){if(!t)return;const s=q.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,this.playlistType),this.state===P.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==P.STOPPED&&(this.state=P.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.getLevelDetails();t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${t.level===-1?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(this.log(`update level timing ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`),!Object.keys(t.elementaryStreams).reduce((d,c)=>{const u=t.elementaryStreams[c];if(u){const f=u.endPTS-u.startPTS;if(f<=0)return this.warn(`Could not parse fragment ${t.sn} ${c} duration reliably (${f})`),d||!1;let g=0;return i.partial?e&&i.part===0&&(g=e.start-u.startPTS,t.startPTS=t.maxStartPTS=u.startPTS,t.startDTS=u.startDTS,t.start!==0&&t.setStart(u.startPTS),Sa(r,t,g)):g=Ta(r,t,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this.iframesOnly,this),this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:g,type:c,frag:t,part:e,start:u.startPTS,end:u.endPTS}),!0}return d},!1)){var a,o,l,h;const d=((a=this.transmuxer)==null?void 0:a.error)===null,c=((o=this.transmuxer)==null?void 0:o.error)!=null,u=((l=(h=this.levels)==null?void 0:h.length)!=null?l:0)>1;if((s.fragmentError===0||d&&(s.fragmentError<2||t.endList)||c&&u)&&this.treatAsGap(t,s),d){const f=new Error(`Found no media in ${this.playlistLabel()} ${t.level} ${e?`part: ${e.index} of `:""}sn: ${t.sn} at playlist time: ${t.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(f.message),this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:f,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=P.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`),this.hls.trigger(m.FRAG_PARSED,{frag:t,part:e,chunkMeta:i})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(t,e=!0,s){var i,r;return`${t.type} playlist ${t.level} (${s?"part":"frag"}:[${(i=e&&!s?t.startPTS:(s||t).start)!=null?i:NaN}-${(r=e&&!s?t.endPTS:(s||t).end)!=null?r:NaN}]${s&&t.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""})`}treatAsGap(t,e){e&&e.fragmentError++,this.fragmentTracker.addAsGap(t)}resetTransmuxer(){var t;(t=this.transmuxer)==null||t.reset()}isFragmentNearlyDownloaded(t){var e;const s=(e=t.loader)==null?void 0:e.stats;if(!s||s.total<=0)return!1;const i=s.loading.first>0,r=(s.total-s.loaded)*8/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&r<=.15}recoverWorkerError(t){t.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}calculateOptimalSwitchPoint(t,e){let s=0;const{hls:i,media:r,config:a,levels:o,playlistType:l}=this,h=this.getLevelDetails();if(r&&!r.paused&&o){var d;const f=l===K.AUDIO?In(t.audioCodec,128e3):t.maxBitrate,g=1+i.ttfbEstimate/1e3,p=i.bandwidthEstimate*a.abrBandWidthUpFactor,v=h&&(this.loadingParts?h.partTarget:h.averagetargetduration)||((d=this.fragCurrent)==null?void 0:d.duration)||6;s=g+f*v/p,t.details||(s+=g)}const c=this.playhead,u=!(h!=null&&h.live)||e.end-c>s*1.5;return{fetchdelay:s,okToFlushForwardBuffer:u}}scheduleTrackSwitch(t,e,s){const{media:i,playlistType:r}=this;if(!i||!t)return;const a=s?this.getBufferedFrag(this.playhead+e):null;if(a){const l=this.followingBufferedFrag(a);if(l){var o;this.abortCurrentFrag();const h=l.maxStartPTS?l.maxStartPTS:l.start,d=l.duration,c=Math.max(a.end,h+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>c)return;const u=r===K.MAIN?null:"audio";this.flushMainBuffer(c,Number.POSITIVE_INFINITY,u),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:t,playlistType:e}=this;if(!t)return;const s=this.getAppendedFrag(this.playhead);if(s&&s.start>1){const i=e===K.AUDIO;this.flushMainBuffer(0,s.start-(i?0:1),i?"audio":null)}}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,this.playlistType)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}abortCurrentFrag(){var t;const e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case P.KEY_LOADING:case P.FRAG_LOADING:case P.FRAG_LOADING_WAITING_RETRY:case P.PARSING:case P.PARSED:this.state=P.IDLE;break}this.nextLoadPosition=(t=this.hls)!=null&&t.hasEnoughToStart?this.playhead:this.lastCurrentTime}checkFragPlaying(){const t=this.media;let e=null;if(t&&t.readyState>1&&t.seeking===!1){const s=t.currentTime;if(q.isBuffered(t,s)?e=this.getAppendedFrag(s):q.isBuffered(t,s+.1)&&(e=this.getAppendedFrag(s+.1)),e&&(this.backtrackFragment=void 0,!Ue(e,this.fragPlaying)))return this.fragPlaying=e,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:t,media:e,hls:s,config:i,playlistType:r}=this;if(e!=null&&e.readyState&&t&&s&&i){const a=this.getBufferOutput(),o=this.getFwdBufferInfo(a,r);if(!o)return;const l=r===K.AUDIO?s.nextAudioTrack:s.nextLoadLevel,h=t[l],{fetchdelay:d,okToFlushForwardBuffer:c}=this.calculateOptimalSwitchPoint(h,o);this.scheduleTrackSwitch(o,d,c)}this.tickImmediate()}}function Ca(n,t,e){if(t)for(let s=t.length;s--;){const i=t[s].interstitial,r=i.startTime,a=Math.min(r+i.duration,i.resumeTime);if(i.appendInPlace&&(n.start>=r&&n.end<=a||e>n.start&&n.end>r&&n.start<a))return!0}return!1}function $s(n){return!!n.interstitialsController&&n.enableInterstitialPlayback!==!1}class wa{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let s;if(t.length)t.length===1?s=t[0]:s=Fd(t,e);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Fd(n,t){const e=new Uint8Array(t);let s=0;for(let i=0;i<n.length;i++){const r=n[i];e.set(r,s),s+=r.length}return e}var Oa={exports:{}},Ma;function Nd(){return Ma||(Ma=1,(function(n){var t=Object.prototype.hasOwnProperty,e="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(e=!1));function i(l,h,d){this.fn=l,this.context=h,this.once=d||!1}function r(l,h,d,c,u){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new i(d,c||l,u),g=e?e+h:h;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function a(l,h){--l._eventsCount===0?l._events=new s:delete l._events[h]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,d;if(this._eventsCount===0)return l;for(d in h=this._events)t.call(h,d)&&l.push(e?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=e?e+l:l,d=this._events[h];if(!d)return[];if(d.fn)return[d.fn];for(var c=0,u=d.length,f=new Array(u);c<u;c++)f[c]=d[c].fn;return f},o.prototype.listenerCount=function(l){var h=e?e+l:l,d=this._events[h];return d?d.fn?1:d.length:0},o.prototype.emit=function(l,h,d,c,u,f){var g=e?e+l:l;if(!this._events[g])return!1;var p=this._events[g],v=arguments.length,E,y;if(p.fn){switch(p.once&&this.removeListener(l,p.fn,void 0,!0),v){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,h),!0;case 3:return p.fn.call(p.context,h,d),!0;case 4:return p.fn.call(p.context,h,d,c),!0;case 5:return p.fn.call(p.context,h,d,c,u),!0;case 6:return p.fn.call(p.context,h,d,c,u,f),!0}for(y=1,E=new Array(v-1);y<v;y++)E[y-1]=arguments[y];p.fn.apply(p.context,E)}else{var T=p.length,S;for(y=0;y<T;y++)switch(p[y].once&&this.removeListener(l,p[y].fn,void 0,!0),v){case 1:p[y].fn.call(p[y].context);break;case 2:p[y].fn.call(p[y].context,h);break;case 3:p[y].fn.call(p[y].context,h,d);break;case 4:p[y].fn.call(p[y].context,h,d,c);break;default:if(!E)for(S=1,E=new Array(v-1);S<v;S++)E[S-1]=arguments[S];p[y].fn.apply(p[y].context,E)}}return!0},o.prototype.on=function(l,h,d){return r(this,l,h,d,!1)},o.prototype.once=function(l,h,d){return r(this,l,h,d,!0)},o.prototype.removeListener=function(l,h,d,c){var u=e?e+l:l;if(!this._events[u])return this;if(!h)return a(this,u),this;var f=this._events[u];if(f.fn)f.fn===h&&(!c||f.once)&&(!d||f.context===d)&&a(this,u);else{for(var g=0,p=[],v=f.length;g<v;g++)(f[g].fn!==h||c&&!f[g].once||d&&f[g].context!==d)&&p.push(f[g]);p.length?this._events[u]=p.length===1?p[0]:p:a(this,u)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=e?e+l:l,this._events[h]&&a(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=e,o.EventEmitter=o,n.exports=o})(Oa)),Oa.exports}var $d=Nd(),Vi=Dl($d);const ts="1.7.4",Me={};function Ud(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Bd(){const n=Me[ts];if(n)return n.clientCount++,n;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(t),s={worker:new self.Worker(e),objectURL:e,clientCount:1};return Me[ts]=s,s}function Gd(n){const t=Me[n];if(t)return t.clientCount++,t;const e=new self.URL(n,self.location.href).href,s={worker:new self.Worker(e),scriptURL:e,clientCount:1};return Me[n]=s,s}function Kd(n){const t=Me[n||ts];if(t&&t.clientCount--===1){const{worker:e,objectURL:s}=t;delete Me[n||ts],s&&self.URL.revokeObjectURL(s),e.terminate()}}function Vd(n,t,e,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=t[e+2],a=r>>2&15;if(a>12){const v=new Error(`invalid ADTS sampling index:${a}`);n.emit(m.ERROR,m.ERROR,{type:Y.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:v,reason:v.message});return}const o=(r>>6&3)+1,l=t[e+3]>>6&3|(r&1)<<2,h=i[a];let d=a;(o===5||o===29)&&(d-=3);let c;const u=(d&14)>>1,f=(d&1)<<7|l<<3;let g=0;if(o===1&&a>=6){g=5;const v=a-3;c=[g<<3|u,f|(v&14)>>1,(v&1)<<7|8,0]}else c=[o<<3|u,f];const p="mp4a.40."+(g||o);return at.log(`manifest codec:${s}, parsed codec:${p}, channels:${l}, rate:${h} (ADTS object type:${o} sampling index:${a} esds config:[${c.join(",")}])`),{config:c,samplerate:h,channelCount:l,codec:p,parsedCodec:p,manifestCodec:s}}function xa(n,t){return n[t]===255&&(n[t+1]&246)===240}function Fa(n,t){return n[t+1]&1?7:9}function Hi(n,t){return(n[t+3]&3)<<11|n[t+4]<<3|(n[t+5]&224)>>>5}function Hd(n,t){return t+5<n.length}function Us(n,t){return t+1<n.length&&xa(n,t)}function Yd(n,t){return Hd(n,t)&&xa(n,t)&&Hi(n,t)<=n.length-t}function Wd(n,t){if(Us(n,t)){const e=Fa(n,t);if(t+e>=n.length)return!1;const s=Hi(n,t);if(s<=e)return!1;const i=t+s;return i===n.length||Us(n,i)}return!1}function Na(n,t,e,s,i){if(!n.samplerate){const r=Vd(t,e,s,i);if(!r)return;ht(n,r)}}function $a(n){return 1024*9e4/n}function jd(n,t){const e=Fa(n,t);if(t+e<=n.length){const s=Hi(n,t)-e;if(s>0)return{headerLength:e,frameLength:s}}}function Ua(n,t,e,s,i){const r=$a(n.samplerate),a=s+i*r,o=jd(t,e);let l;if(o){const{frameLength:d,headerLength:c}=o,u=c+d,f=Math.max(0,e+u-t.length);f?(l=new Uint8Array(u-c),l.set(t.subarray(e+c,t.length),0)):l=t.subarray(e+c,e+u);const g={unit:l,pts:a};return f||n.samples.push(g),{sample:g,length:u,missing:f}}const h=t.length-e;return l=new Uint8Array(h),l.set(t.subarray(e,t.length),0),{sample:{unit:l,pts:a},length:h,missing:-1}}let _t=(function(n){return n.audioId3="org.id3",n.dateRange="com.apple.quicktime.HLS",n.emsg="https://aomedia.org/emsg/ID3",n.misbklv="urn:misb:KLV:bin:1910.1",n})({});function re(n="",t=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class Yi{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,s){}demux(t,e){this.cachedData&&(t=Gt(this.cachedData,t),this.cachedData=null);let s=Ve(t,0),i=s?s.length:0,r;const a=this._audioTrack,o=this._id3Track,l=s?mi(s):void 0,h=t.length;for((this.basePTS===null||this.frameIndex===0&&$(l))&&(this.basePTS=qd(l,e,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:_t.audioId3,duration:Number.POSITIVE_INFINITY});i<h;){if(this.canParse(t,i)){const d=this.appendFrame(a,t,i);d?(this.frameIndex++,this.lastPTS=d.sample.pts,i+=d.length,r=i):i=h}else Yl(t,i)?(s=Ve(t,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:_t.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===h&&r!==h){const d=t.slice(r);this.cachedData?this.cachedData=Gt(this.cachedData,d):this.cachedData=d}}return{audioTrack:a,videoTrack:re(),id3Track:o,textTrack:re()}}demuxSampleAes(t,e,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:re(),id3Track:this._id3Track,textTrack:re()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const qd=(n,t,e)=>{if($(n))return n*90;const s=e?e.baseTime*9e4/e.timescale:0;return t*9e4+s},Xd=[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],zd=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Qd=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Jd=[0,1,1,4];function Ba(n,t,e,s,i){if(e+24>t.length)return;const r=Ga(t,e);if(r&&e+r.frameLength<=t.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*a,l={unit:t.subarray(e,e+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function Ga(n,t){const e=n[t+1]>>3&3,s=n[t+1]>>1&3,i=n[t+2]>>4&15,r=n[t+2]>>2&3;if(e!==1&&i!==0&&i!==15&&r!==3){const a=n[t+2]>>1&1,o=n[t+3]>>6,l=e===3?3-s:s===3?3:4,h=Xd[l*14+i-1]*1e3,d=zd[(e===3?0:e===2?1:2)*3+r],c=o===3?1:2,u=Qd[e][s],f=Jd[s],g=u*8*f,p=Math.floor(u*h/d+a)*f,v=We();return v&&v<=87&&s===2&&h>=224e3&&o===0&&(n[t+3]=n[t+3]|128),{sampleRate:d,channelCount:c,frameLength:p,samplesPerFrame:g}}}function Wi(n,t){return n[t]===255&&(n[t+1]&224)===224&&(n[t+1]&6)!==0}function Ka(n,t){return t+1<n.length&&Wi(n,t)}function Zd(n,t){return Wi(n,t)&&4<=n.length-t}function Va(n,t){if(t+1<n.length&&Wi(n,t)){const e=Ga(n,t);let s=4;e!=null&&e.frameLength&&(s=e.frameLength);const i=t+s;return i===n.length||Ka(n,i)}return!1}class Ha{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Ci(e,!0)}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,me.cbc,{start:0,end:t.byteLength})}decryptAacSample(t,e,s){const i=t[e].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)}).catch(s)}decryptAacSamples(t,e,s){for(;;e++){if(e>=t.length){s();return}if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=Math.floor((t.length-48)/160)*16+16,s=new Int8Array(e);let i=0;for(let r=32;r<t.length-16;r+=160,i+=16)s.set(t.subarray(r,r+16),i);return s}getAvcDecryptedUnit(t,e){const s=new Uint8Array(e);let i=0;for(let r=32;r<t.length-16;r+=160,i+=16)t.set(s.subarray(i,i+16),r);return t}decryptAvcSample(t,e,s,i,r){const a=fn(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(t,e,s+1,i)}).catch(i)}decryptAvcSamples(t,e,s,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length){i();return}const r=t[e].units;for(;!(s>=r.length);s++){const a=r[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(t,e,s,i,a),!this.decrypter.isSync()))return}}}}class tc extends Yi{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=t,this.config=e}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const s=Ve(t,0);let i=s?.length||0;if(Va(t,i))return!1;for(let r=t.length;i<r;i++)if(Wd(t,i))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return Yd(t,e)}appendFrame(t,e,s){Na(t,this.observer,e,s,t.manifestCodec);const i=Ua(t,e,s,this.basePTS,this.frameIndex);if(i?.missing===0)return i}demuxSampleAes(t,e,s){const i=this.demux(t,s),r=this.sampleAes=new Ha(this.observer,this.config,e);return new Promise(a=>{r.decryptAacSamples(i.audioTrack.samples,0,()=>{a(i)})})}}const Ya=(n,t)=>{let e=0,s=5;t+=s;const i=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=n[t];const o=Math.min(s,8),l=8-o;r[0]=4278190080>>>24+l<<l,i[0]=(a[0]&r[0])>>l,e=e?e<<o|i[0]:i[0],t+=1,s-=o}return e};class ec extends Yi{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,s){const i=Wa(t,e,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:t.samples[t.samples.length-1],length:i,missing:0}}static probe(t){if(!t)return!1;const e=Ve(t,0);if(!e)return!1;const s=e.length;if(t[s]===11&&t[s+1]===119&&mi(e)!==void 0){if(Ya(t,s)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}function Wa(n,t,e,s,i){if(e+8>t.length||t[e]!==11||t[e+1]!==119)return-1;const r=t[e+4]>>6;if(r>=3)return-1;const a=[48e3,44100,32e3][r],o=t[e+4]&63,l=[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][o*3+r]*2;if(e+l>t.length)return-1;const h=t[e+6]>>5;let d=0;h===2?d+=2:(h&1&&h!==1&&(d+=2),h&4&&(d+=2));const c=(t[e+6]<<8|t[e+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=t[e+5]>>3,g=t[e+5]&7,p=new Uint8Array([r<<6|f<<1|g>>2,(g&3)<<6|h<<3|c<<2|o>>4,o<<4&224]),v=1536/a*9e4,E=s+i*v,y=t.subarray(e,e+l);return n.config=p,n.channelCount=u,n.samplerate=a,n.samples.push({unit:y,pts:E}),l}class sc extends Yi{resetInitSegment(t,e,s,i){super.resetInitSegment(t,e,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=Ve(t,0);let s=e?.length||0;if(e&&t[s]===11&&t[s+1]===119&&mi(e)!==void 0&&Ya(t,s)<=16)return!1;for(let i=t.length;s<i;s++)if(Va(t,s))return at.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return Zd(t,e)}appendFrame(t,e,s){if(this.basePTS!==null)return Ba(t,e,s,this.basePTS,this.frameIndex)}}const ic=/\/emsg[-/]ID3/i;class rc{constructor(t,e,s,i=at){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.initData=void 0,this.logger=void 0,this.config=e,this.logger=i}resetTimeStamp(){}resetInitSegment(t,e,s,i){const r=this.videoTrack=re("video",1),a=this.audioTrack=re("audio",1),o=this.txtTrack=re("text",1);if(this.id3Track=re("id3",1),this.initData=void 0,this.timeOffset=0,!(t!=null&&t.byteLength))return;const l=this.initData=on(t);if(l.video){const{id:h,timescale:d,codec:c,supplemental:u}=l.video;r.id=h,r.timescale=o.timescale=d,r.codec=c,r.supplemental=u}if(l.audio){const{id:h,timescale:d,codec:c}=l.audio;a.id=h,a.timescale=d,a.codec=c}o.id=tn.text,r.sampleDuration=0,r.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return ah(t,"moof")}demux(t,e,s){this.timeOffset=e;let i=t;const r=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=Gt(this.remainderData,t));const h=ph(i);this.remainderData=h.remainder,r.samples=h.valid||new Uint8Array}else r.samples=i;const o=this.extractID3Track(r,e),l=this.parseFragment(r,a,e,s);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(t,e){const s=this.timeOffset,i=this.videoTrack,r=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;const a=this.extractID3Track(i,this.timeOffset),o=this.parseFragment(i,r,s,e);return{videoTrack:i,audioTrack:re(),id3Track:a,textTrack:re(),initData:this.initData,sampleData:o}}parseFragment(t,e,s,i){const r=this.initData;if(r&&i){const{samples:a,sampleData:o}=mh(s,t,r,this.logger,i.iframe);return e.samples=a,o}e.samples=vh(s,t)}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const i=J(t.samples,["emsg"]);i&&i.forEach(r=>{const a=yh(r);if(ic.test(a.schemeIdUri)){const o=ja(a,e);let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const h=a.payload;s.samples.push({data:h,len:h.byteLength,dts:o,pts:o,type:_t.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){const o=this.config.emsgKLVSchemaUri||_t.misbklv;if(a.schemeIdUri.startsWith(o)){const l=ja(a,e);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:l,pts:l,type:_t.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return s}demuxSampleAes(t,e,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}}function ja(n,t){return $(n.presentationTime)?n.presentationTime/n.timeScale:t+n.presentationTimeDelta/n.timeScale}const nc=1,ac=2,oc=3,es=-1;class qa{constructor(){this.VideoSample=null}createVideoSample(t,e,s){return{key:t,frame:!1,pts:e,dts:s,units:[],length:0}}getLastNalUnit(t){var e;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=t[t.length-1]),(e=s)!=null&&e.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(t.pts===void 0){const s=e.samples,i=s.length;if(i){const r=s[i-1];t.pts=r.pts,t.dts=r.dts}else{e.dropped++;return}}e.samples.push(t)}}parseNALu(t,e,s){const i=e.byteLength;if(i===0)return[];const r=t.naluState||0,a=r===es?0:r,o=[];let l=0,h=0,d=-1,c=0;for(r===es&&(d=0,c=this.getNALuType(e,0),h=1);h<i;){const u=e.indexOf(nc,h);if(u===-1)break;h=u+1;let f=u;for(;f>0&&e[f-1]===0;)f--;const g=u-f+(f===0?a:0);if(g<ac)continue;const p=Math.min(g,oc),v=Math.min(u-f,p),E=p-v;if(f=u-v,d>=0)o.push({data:e.subarray(d,f),type:c});else{const y=this.getLastNalUnit(t.samples);y&&(f>0?y.data=Gt(y.data,e.subarray(0,f)):E>0&&(y.data=y.data.subarray(0,y.data.byteLength-E)),y.state=0)}if(h<i)d=h,c=this.getNALuType(e,h);else{l=es,d=-1;break}}if(l!==es){let u=i;for(;u>0&&e[u-1]===0;)u--;l=i-u+(u===0?a:0)}if(d>=0)o.push({data:e.subarray(d),type:c,state:l});else if(o.length===0&&l!==es){const u=this.getLastNalUnit(t.samples);u&&(u.data=Gt(u.data,e),u.state=l)}return t.naluState=l,o}}class ss{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,s=t.byteLength-e,i=new Uint8Array(4),r=Math.min(4,e);if(r===0)throw new Error("no bytes available");i.set(t.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,e=t>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const s=this.word>>>32-e;if(t>32&&at.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return e=t-e,e>0&&this.bitsAvailable?s<<e|this.readBits(e):s}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if((this.word&2147483648>>>t)!==0)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}}class lc extends qa{parsePES(t,e,s,i,r){const a=r.iframe,o=this.parseNALu(t,s.data,i);let l=this.VideoSample,h,d=!1;s.data=null,l&&o.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),o.forEach(c=>{var u,f;switch(c.type){case 1:{if(a)break;let E=!1;h=!0;const y=c.data;if(d&&y.length>4){const T=this.readSliceType(y);(T===2||T===4||T===7||T===9)&&(E=!0)}if(E){var g;(g=l)!=null&&g.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.frame=!0,l.key=E;break}case 5:h=!0,(u=l)!=null&&u.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.key=!0,l.frame=!0;break;case 6:{if(a)break;h=!0,Ye(c.data,1,s.pts,e.samples);break}case 7:{var p,v;h=!0,d=!0;const E=c.data,y=this.readSPS(E);if(!t.sps||t.width!==y.width||t.height!==y.height||((p=t.pixelRatio)==null?void 0:p[0])!==y.pixelRatio[0]||((v=t.pixelRatio)==null?void 0:v[1])!==y.pixelRatio[1]){t.width=y.width,t.height=y.height,t.pixelRatio=y.pixelRatio,t.sps=[E];const T=E.subarray(1,4);let S="avc1.";for(let A=0;A<3;A++){let L=T[A].toString(16);L.length<2&&(L="0"+L),S+=L}t.codec=S}break}case 8:h=!0,t.pps=[c.data];break;case 9:h=!0,t.audFound=!0,(f=l)!=null&&f.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:h=!0;break;default:h=!1;break}l&&h&&l.units.push(c)}),i&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,e){return t[e]&31}readSliceType(t){const e=new ss(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let s=8,i=8,r;for(let a=0;a<t;a++)i!==0&&(r=e.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(t){const e=new ss(t);let s=0,i=0,r=0,a=0,o,l,h;const d=e.readUByte.bind(e),c=e.readBits.bind(e),u=e.readUEG.bind(e),f=e.readBoolean.bind(e),g=e.skipBits.bind(e),p=e.skipEG.bind(e),v=e.skipUEG.bind(e),E=this.skipScalingList.bind(this);d();const y=d();if(c(5),g(3),d(),v(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){const b=u();if(b===3&&g(1),v(),v(),g(1),f())for(l=b!==3?8:12,h=0;h<l;h++)f()&&(h<6?E(16,e):E(64,e))}v();const T=u();if(T===0)u();else if(T===1)for(g(1),p(),p(),o=u(),h=0;h<o;h++)p();v(),g(1);const S=u(),A=u(),L=c(1);L===0&&g(1),g(1),f()&&(s=u(),i=u(),r=u(),a=u());let I=[1,1];if(f()&&f())switch(d()){case 1:I=[1,1];break;case 2:I=[12,11];break;case 3:I=[10,11];break;case 4:I=[16,11];break;case 5:I=[40,33];break;case 6:I=[24,11];break;case 7:I=[20,11];break;case 8:I=[32,11];break;case 9:I=[80,33];break;case 10:I=[18,11];break;case 11:I=[15,11];break;case 12:I=[64,33];break;case 13:I=[160,99];break;case 14:I=[4,3];break;case 15:I=[3,2];break;case 16:I=[2,1];break;case 255:{I=[d()<<8|d(),d()<<8|d()];break}}return{width:Math.ceil((S+1)*16-s*2-i*2),height:(2-L)*(A+1)*16-(L?2:4)*(r+a),pixelRatio:I}}}class hc extends qa{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,s,i){const r=this.parseNALu(t,s.data,i);let a=this.VideoSample,o,l=!1;s.data=null;const h=d=>(a=this.VideoSample=this.createVideoSample(d,s.pts,s.dts),a);r.forEach((d,c)=>{var u,f;if(this.startsNewAccessUnit(a,t,d,c)){this.pushAccessUnit(a,t);const p=d.type>=16&&d.type<=23;a=h(p),l=!1}switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=h(!1)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,l){var g;(g=a)!=null&&g.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null)}a||(a=h(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(u=a)!=null&&u.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=h(!0)),a.key=!0,a.frame=!0;break;case 39:o=!0,Ye(d.data,2,s.pts,e.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=ht(t.params,this.readVPS(d.data)),this.initVPS=d.data),t.vps=[d.data];break;case 33:if(o=!0,l=!0,t.vps!==void 0&&t.vps[0]!==this.initVPS&&t.sps!==void 0&&!this.matchSPS(t.sps[0],d.data)&&(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const p=this.readSPS(d.data);t.width=p.width,t.height=p.height,t.pixelRatio=p.pixelRatio,t.codec=p.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const v in p.params)t.params[v]=p.params[v]}this.pushParameterSet(t.sps,d.data,t.vps),a||(a=h(!1));break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const p=this.readPPS(d.data);for(const v in p)t.params[v]=p[v]}this.pushParameterSet(t.pps,d.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(f=a)!=null&&f.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=h(!1));break;default:o=!1;break}a&&o&&a.units.push(d)}),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,s){(s&&s[0]===this.initVPS||!s&&!t.length)&&t.push(e)}startsNewAccessUnit(t,e,s,i){if(!t)return!1;if(!e.audFound&&i===0)return!0;if(!t.frame)return!1;const{type:r,data:a}=s;return r>=32&&r<=35||r===39||r>=41&&r<=44||r>=48&&r<=55?!0:r<=31&&a.length>2&&(a[2]&128)!==0}getNALuType(t,e){return(t[e]&126)>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let s=0;for(let i=0;i<t.byteLength;i++)i>=2&&t[i]===3&&t[i-1]===0&&t[i-2]===0||(e[s]=t[i],s++);return new Uint8Array(e.buffer,0,s)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new ss(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);const s=e.readBits(3),i=e.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(t){const e=new ss(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const s=e.readBits(3);e.readBoolean();const i=e.readBits(2),r=e.readBoolean(),a=e.readBits(5),o=e.readUByte(),l=e.readUByte(),h=e.readUByte(),d=e.readUByte(),c=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),p=e.readUByte(),v=e.readUByte(),E=e.readUByte(),y=[],T=[];for(let z=0;z<s;z++)y.push(e.readBoolean()),T.push(e.readBoolean());if(s>0)for(let z=s;z<8;z++)e.readBits(2);for(let z=0;z<s;z++)y[z]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),T[z]&&e.readUByte();e.readUEG();const S=e.readUEG();S==3&&e.skipBits(1);const A=e.readUEG(),L=e.readUEG(),I=e.readBoolean();let b=0,k=0,D=0,C=0;I&&(b+=e.readUEG(),k+=e.readUEG(),D+=e.readUEG(),C+=e.readUEG());const w=e.readUEG(),N=e.readUEG(),U=e.readUEG(),G=e.readBoolean();for(let z=G?0:s;z<=s;z++)e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.readBoolean()&&e.readBoolean())for(let z=0;z<4;z++)for(let pt=0;pt<(z===3?2:6);pt++)if(!e.readBoolean())e.readUEG();else{const it=Math.min(64,1<<4+(z<<1));z>1&&e.readEG();for(let St=0;St<it;St++)e.readEG()}e.readBoolean(),e.readBoolean(),e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const M=e.readUEG();let F=0;for(let z=0;z<M;z++){let pt=!1;if(z!==0&&(pt=e.readBoolean()),pt){z===M&&e.readUEG(),e.readBoolean(),e.readUEG();let it=0;for(let St=0;St<=F;St++){const At=e.readBoolean();let nt=!1;At||(nt=e.readBoolean()),(At||nt)&&it++}F=it}else{const it=e.readUEG(),St=e.readUEG();F=it+St;for(let At=0;At<it;At++)e.readUEG(),e.readBoolean();for(let At=0;At<St;At++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const z=e.readUEG();for(let pt=0;pt<z;pt++){for(let it=0;it<U+4;it++)e.readBits(1);e.readBits(1)}}let x=0,_=1,O=1,H=!0,j=1,tt=0;e.readBoolean(),e.readBoolean();let X=!1;if(e.readBoolean()){if(e.readBoolean()){const z=e.readUByte(),pt=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],it=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];z>0&&z<16?(_=pt[z-1],O=it[z-1]):z===255&&(_=e.readBits(16),O=e.readBits(16))}if(e.readBoolean()&&e.readBoolean(),e.readBoolean()&&(e.readBits(3),e.readBoolean(),e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())),e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),X=e.readBoolean(),X&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG()),e.readBoolean()&&(j=e.readBits(32),tt=e.readBits(32),e.readBoolean()&&e.readUEG(),e.readBoolean())){const z=e.readBoolean(),pt=e.readBoolean();let it=!1;(z||pt)&&(it=e.readBoolean(),it&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),it&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let St=0;St<=s;St++){H=e.readBoolean();const At=H||e.readBoolean();let nt=!1;At?e.readEG():nt=e.readBoolean();const yt=nt?1:e.readUEG()+1;if(z)for(let ct=0;ct<yt;ct++)e.readUEG(),e.readUEG(),it&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(pt)for(let ct=0;ct<yt;ct++)e.readUEG(),e.readUEG(),it&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),x=e.readUEG())}let Z=A,rt=L;if(I){let z=1,pt=1;S===1?z=pt=2:S==2&&(z=2),Z=A-z*k-z*b,rt=L-pt*C-pt*D}const Rt=i?["A","B","C"][i]:"",et=o<<24|l<<16|h<<8|d;let dt=0;for(let z=0;z<32;z++)dt=(dt|(et>>z&1)<<31-z)>>>0;let Qt=dt.toString(16);return a===1&&Qt==="2"&&(Qt="6"),{codecString:`hvc1.${Rt}${a}.${Qt}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[o,l,h,d],general_constraint_indicator_flags:[c,u,f,g,p,v],general_level_idc:E,bit_depth:w+8,bit_depth_luma_minus8:w,bit_depth_chroma_minus8:N,min_spatial_segmentation_idc:x,chroma_format_idc:S,frame_rate:{fixed:H,fps:tt/j}},width:Z,height:rt,pixelRatio:[_,O]}}readPPS(t){const e=new ss(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2),e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const s=e.readBoolean(),i=e.readBoolean();let r=1;return i&&s?r=0:i?r=3:s&&(r=2),{parallelismType:r}}matchSPS(t,e){return Vt(t).substring(3)===Vt(e).substring(3)}}const Lt=188;class ce{constructor(t,e,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=e,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(t,e){const s=ce.syncOffset(t);return s>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(t){const e=t.length;let s=Math.min(Lt*5,e-Lt)+1,i=0;for(;i<s;){let r=!1,a=-1,o=0;for(let l=i;l<e;l+=Lt)if(t[l]===71&&(e-l===Lt||t[l+Lt]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+Lt*99,t.length-Lt)+1)),r||(r=Bs(t,l)===0),r&&o>1&&(a===0&&o>2||l+Lt>s))return a}else{if(o)return-1;break}i++}return-1}static createTrack(t,e){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:tn[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?e:void 0}}resetInitSegment(t,e,s,i,r,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ce.createTrack("video"),this._videoTrack.duration=i,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new uc(this.logger):null,this._audioTrack=ce.createTrack("audio",i),this._id3Track=ce.createTrack("id3"),this._txtTrack=ce.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s,t&&this.demux(t,0,a,r?.method==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.videoParser=null,this.aacOverFlow=null,this.remainderData=null}demux(t,e,s,i=!1,r=!1){i||(this.sampleAes=null);let a;const o=this._videoTrack,l=this.videoIntegrityChecker,h=this._audioTrack,d=this._id3Track,c=this._txtTrack,u=s.iframe;let f=o.pid,g=o.pesData,p=h.pid,v=d.pid,E=this._klvPid,y=h.pesData,T=d.pesData,S=null,A=null,L=this.pmtParsed,I=this._pmtId,b=t.length;if(this.remainderData&&(t=Gt(this.remainderData,t),b=t.length,this.remainderData=null),b<Lt&&!r)return this.remainderData=t,{audioTrack:h,videoTrack:o,id3Track:d,textTrack:c};const k=Math.max(0,ce.syncOffset(t));b-=(b-k)%Lt,b<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,b,t.buffer.byteLength-b));let D=0;for(let w=k;w<b;w+=Lt)if(t[w]===71){const N=!!(t[w+1]&64),U=Bs(t,w),G=(t[w+3]&48)>>4;let M;if(G>1){if(M=w+5+t[w+4],M===w+Lt)continue}else M=w+4;switch(U){case f:N&&(g&&!(l!=null&&l.isCorrupted)&&(a=Ae(g,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,c,a,!1,s)),g={data:[],size:0},l?.reset(f)),l?.handlePacket(t.subarray(w)),g&&(g.data.push(t.subarray(M,w+Lt)),g.size+=w+Lt-M);break;case p:if(u)break;if(N){if(y&&(a=Ae(y,this.logger)))switch(h.segmentCodec){case"aac":this.parseAACPES(h,a,s);break;case"mp3":this.parseMPEGPES(h,a);break;case"ac3":this.parseAC3PES(h,a);break}y={data:[],size:0}}y&&(y.data.push(t.subarray(M,w+Lt)),y.size+=w+Lt-M);break;case v:if(u)break;N&&(T&&(a=Ae(T,this.logger))&&this.parseID3PES(d,a),T={data:[],size:0}),T&&(T.data.push(t.subarray(M,w+Lt)),T.size+=w+Lt-M);break;case E:if(u)break;N&&(S&&(a=Ae(S,this.logger))&&this.parseKlvPES(d,a),S={data:[],size:0}),S&&(S.data.push(t.subarray(M,w+Lt)),S.size+=w+Lt-M);break;case 0:N&&(M+=t[M]+1),I=this._pmtId=dc(t,M);break;case I:{N&&(M+=t[M]+1);const F=cc(t,M,this.typeSupported,i,this.observer,this.logger,this.config,s);f=F.videoPid,f>0&&(o.pid=f,o.segmentCodec=F.segmentVideoCodec),p=F.audioPid,p>0&&(h.pid=p,h.segmentCodec=F.segmentAudioCodec),v=F.id3Pid,v>0&&(d.pid=v),E=F.klvPid,E>0&&(this._klvPid=E),A!==null&&!L&&(this.logger.warn(`MPEG-TS PMT found at ${w} after unknown PID '${A}'. Backtracking to sync byte @${k} to parse all TS packets.`),A=null,w=k-188),L=this.pmtParsed=!0;break}case 17:case 8191:break;default:A=U;break}}else D++;D>0&&ji(this.observer,new Error(`Found ${D} TS packet/s that do not start with 0x47`),s,void 0,this.logger),o.pesData=g,h.pesData=y,d.pesData=T;const C={audioTrack:h,videoTrack:o,id3Track:d,textTrack:c};return r&&this.extractRemainingSamples(C,s),C}flush(t,e){const{remainderData:s}=this;this.remainderData=null;let i;return s?i=this.demux(s,0,e,!1,!0):i={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i,e),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(t,e){const{audioTrack:s,videoTrack:i,id3Track:r,textTrack:a}=t,o=i.pesData,l=s.pesData,h=r.pesData,d=this.videoIntegrityChecker;let c;if(o&&!(d!=null&&d.isCorrupted)&&(c=Ae(o,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,a,c,!0,e),i.pesData=null)):i.pesData=o,l&&(c=Ae(l,this.logger))){switch(s.segmentCodec){case"aac":this.parseAACPES(s,c,e);break;case"mp3":this.parseMPEGPES(s,c);break;case"ac3":this.parseAC3PES(s,c);break}s.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),s.pesData=l;h&&(c=Ae(h,this.logger))?(this.parseID3PES(r,c),r.pesData=null):r.pesData=h}demuxSampleAes(t,e,s,i){const r=this.demux(t,s,i,!0,!this.config.progressive),a=this.sampleAes=new Ha(this.observer,this.config,e);return this.decrypt(r,a)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new lc:t==="hevc"&&(this.videoParser=new hc))}decrypt(t,e){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=t;i.samples&&i.segmentCodec==="aac"?e.decryptAacSamples(i.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{s(t)}):s(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{s(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(t,e,s){let i=0;const r=this.aacOverFlow;let a=e.data;if(r){this.aacOverFlow=null;const u=r.missing,f=r.sample.unit.byteLength;if(u===-1)a=Gt(r.sample.unit,a);else{const g=f-u;r.sample.unit.set(a.subarray(0,u),g),t.samples.push(r.sample),i=r.missing}}let o,l;for(o=i,l=a.length;o<l-1&&!Us(a,o);o++);if(o!==i){let u;const f=o<l-1;if(f?u=`AAC PES did not start with ADTS header,offset:${o}`:u="No ADTS header found in AAC PES",ji(this.observer,new Error(u),s,f,this.logger),!f)return}Na(t,this.observer,a,o,this.audioCodec);let h;if(e.pts!==void 0)h=e.pts;else if(r){const u=$a(t.samplerate);h=r.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,c;for(;o<l;)if(c=Ua(t,a,o,h,d),o+=c.length,c.missing){this.aacOverFlow=c;break}else for(d++;o<l-1&&!Us(a,o);o++);}parseMPEGPES(t,e){const s=e.data,i=s.length;let r=0,a=0;const o=e.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<i;)if(Ka(s,a)){const l=Ba(t,s,a,o,r);if(l)a+=l.length,r++;else break}else a++}parseAC3PES(t,e){{const s=e.data,i=e.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let a=0,o=0,l;for(;o<r&&(l=Wa(t,s,o,i,a++))>0;)o+=l}}parseID3PES(t,e){if(e.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=ht({},e,{type:this._videoTrack?_t.emsg:_t.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}parseKlvPES(t,e){var s;const i=(s=e.pts)!=null?s:e.dts;if(i===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}const r=e.data;if(r.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let a=0;for(;a<r.length;){var o;if(a+16>r.length)break;const l=a;if(a+=16,a>=r.length)break;const h=r[a];a+=1;let d=0;if(h&128){const g=h&127;if(g===0||g>4||a+g>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let p=0;p<g;p++)d=d<<8|r[a+p];a+=g}else d=h;if(a+d>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const c=a+d,u=r.subarray(l,c),f={data:u,len:u.byteLength,pts:i,dts:(o=e.dts)!=null?o:i,type:_t.misbklv,duration:Number.POSITIVE_INFINITY};t.samples.push(f),a=c}}}function Bs(n,t){return((n[t+1]&31)<<8)+n[t+2]}function dc(n,t){return(n[t+10]&31)<<8|n[t+11]}function cc(n,t,e,s,i,r,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},h=(n[t+1]&15)<<8|n[t+2],d=t+3+h-4,c=(n[t+10]&15)<<8|n[t+11];for(t+=12+c;t<d;){const u=Bs(n,t),f=(n[t+3]&15)<<8|n[t+4];switch(n[t]){case 207:if(!s){qi("ADTS AAC",r);break}case 15:l.audioPid===-1&&(l.audioPid=u);break;case 21:l.id3Pid===-1&&(l.id3Pid=u);break;case 219:if(!s){qi("H.264",r);break}case 27:l.videoPid===-1&&(l.videoPid=u);break;case 3:case 4:!e.mpeg&&!e.mp3?r.log("MPEG audio found, not supported in this browser"):l.audioPid===-1&&(l.audioPid=u,l.segmentAudioCodec="mp3");break;case 193:if(!s){qi("AC-3",r);break}case 129:e.ac3?l.audioPid===-1&&(l.audioPid=u,l.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(f>0){let g=t+5,p=f;for(;p>2;){switch(n[g]){case 106:l.audioPid===-1&&(e.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=u,l.segmentAudioCodec="ac3"));break;case 5:l.klvPid===-1&&a.enableEmsgKLVMetadata&&(l.klvPid=u,r.log(`KLV metadata PID found: ${u}`));break}const v=n[g+1]+2;g+=v,p-=v}}break;case 194:case 135:return ji(i,new Error("Unsupported EC-3 in M2TS found"),o,void 0,r),l;case 36:l.videoPid===-1&&(l.videoPid=u,l.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}t+=f+5}return l}function ji(n,t,e,s,i){i.warn(`parsing error: ${t.message}`),n.emit(m.ERROR,m.ERROR,{type:Y.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:e,error:t,reason:t.message})}function qi(n,t){t.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function Ae(n,t){let e=0,s,i,r,a,o;const l=n.data;if(!n||n.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=Gt(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>n.size-6)return null;const h=s[7];h&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(t.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),r=s[8];let d=r+9;if(n.size<=d)return null;n.size-=d;const c=new Uint8Array(n.size);for(let u=0,f=l.length;u<f;u++){s=l[u];let g=s.byteLength;if(d)if(d>g){d-=g;continue}else s=s.subarray(d),g-=d,d=0;c.set(s,e),e+=g}return i&&(i-=r+3),{data:c,pts:a,dts:o,len:i}}return null}class uc{constructor(t){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t}get isCorrupted(){return this.integrityState!=="ok"}reset(t){this.pid=t,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(t){if(t.byteLength<4)return;const e=Bs(t,0);if(e!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${e}`);return}const s=(t[3]&48)>>4;if(s===0)return;const i=t[3]&15,r=this.lastContinuityCounter;this.lastContinuityCounter=i;const a=(s&1)!=0;if((s&2)!=0&&t[4]!=0&&(t[5]&128)!=0||r<0)return;const o=a?r+1&15:r;if(i!==o){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${e}', CC=${i}, Expected-CC=${o} Last-CC=${r}`),this.integrityState="cc-failed";return}if((t[1]&128)!==0){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${e}'`),this.integrityState="tei-bit";return}}}class fc{static getSilentFrame(t,e){switch(t){case"mp4a.40.2":if(e===1)return new Uint8Array([0,200,0,128,35,128]);if(e===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(e===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(e===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(e===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(e===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(e===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(e===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(e===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}var Gs;const gc={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},Xi=new Uint8Array([0,0,0,0,0,0,0,0]),mc=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),pc=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),vc=new Uint8Array([0,0,0,0,0,0,0,0]),is=new Uint8Array([0,0,0,0,0,0,0,1]),Xa=new Uint8Array([105,115,111,109]),yc=new Uint8Array([97,118,99,49]),Ec=new Uint8Array([0,0,0,1]);class B{static box(t,...e){let s=8,i=e.length;const r=i;for(;i--;)s+=e[i].byteLength;const a=new Uint8Array(s);for(Tt(a,0,s),Tt(a,4,t),i=0,s=8;i<r;i++)a.set(e[i],s),s+=e[i].byteLength;return a}static hdlr(t){return B.box(Q.hdlr,gc[t])}static mdat(t){return B.box(Q.mdat,t)}static mdhd(t,e){e*=t;const s=Math.floor(e/(Zt+1)),i=Math.floor(e%(Zt+1));return B.box(Q.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(t){return B.box(Q.mdia,B.mdhd(t.timescale||0,t.duration||0),B.hdlr(t.type),B.minf(t))}static mfhd(t){return B.box(Q.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?B.box(Q.minf,B.box(Q.smhd,vc),B.DINF,B.stbl(t)):B.box(Q.minf,B.box(Q.vmhd,pc),B.DINF,B.stbl(t))}static moof(t,e,s){return B.box(Q.moof,B.mfhd(t),B.traf(s,e))}static moov(t){let e=t.length;const s=[];for(;e--;)s[e]=B.trak(t[e]);return B.box.apply(null,[Q.moov,B.mvhd(t[0].timescale||0,t[0].duration||0)].concat(s).concat(B.mvex(t)))}static mvex(t){let e=t.length;const s=[];for(;e--;)s[e]=B.trex(t[e]);return B.box.apply(null,[Q.mvex,...s])}static mvhd(t,e){e*=t;const s=Math.floor(e/(Zt+1)),i=Math.floor(e%(Zt+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return B.box(Q.mvhd,r)}static sdtp(t){const e=t.samples||[],s=new Uint8Array(4+e.length);let i,r;for(i=0;i<e.length;i++)r=e[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return B.box(Q.sdtp,s)}static stbl(t){return B.box(Q.stbl,B.stsd(t),B.box(Q.stts,Xi),B.box(Q.stsc,Xi),B.box(Q.stsz,mc),B.box(Q.stco,Xi))}static avc1(t){let e=[],s=[],i,r,a;for(i=0;i<t.sps.length;i++)r=t.sps[i],a=r.byteLength,e.push(a>>>8&255),e.push(a&255),e=e.concat(Array.prototype.slice.call(r));for(i=0;i<t.pps.length;i++)r=t.pps[i],a=r.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(r));const o=B.box(Q.avcC,new Uint8Array([1,e[3],e[4],e[5],255,224|t.sps.length].concat(e).concat([t.pps.length]).concat(s))),l=t.width,h=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return B.box(Q.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,l&255,h>>8&255,h&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,B.box(Q.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),B.box(Q.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(t){const e=t.config,s=e.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5,s,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,e&255,0,0])}static mp4a(t){return B.box(Q.mp4a,B.audioStsd(t),B.box(Q.esds,B.esds(t)))}static mp3(t){return B.box(Q[".mp3"],B.audioStsd(t))}static ac3(t){return B.box(Q["ac-3"],B.audioStsd(t),B.box(Q.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if(t.type==="audio"){if(e==="aac")return B.box(Q.stsd,is,B.mp4a(t));if(e==="ac3"&&t.config)return B.box(Q.stsd,is,B.ac3(t));if(e==="mp3"&&t.codec==="mp3")return B.box(Q.stsd,is,B.mp3(t))}else if(t.pps&&t.sps){if(e==="avc")return B.box(Q.stsd,is,B.avc1(t));if(e==="hevc"&&t.vps)return B.box(Q.stsd,is,B.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,s=(t.duration||0)*(t.timescale||0),i=t.width||0,r=t.height||0,a=Math.floor(s/(Zt+1)),o=Math.floor(s%(Zt+1));return B.box(Q.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(t,e){const s=B.sdtp(t),i=t.id,r=Math.floor(e/(Zt+1)),a=Math.floor(e%(Zt+1));return B.box(Q.traf,B.box(Q.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),B.box(Q.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),B.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,B.box(Q.trak,B.tkhd(t),B.mdia(t))}static trex(t){const e=t.id;return B.box(Q.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const s=t.samples||[],i=s.length,r=12+16*i,a=new Uint8Array(r);let o,l,h,d,c,u;for(e+=8+r,a.set([t.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255],0),o=0;o<i;o++)l=s[o],h=l.duration,d=l.size,c=l.flags,u=l.cts,a.set([h>>>24&255,h>>>16&255,h>>>8&255,h&255,d>>>24&255,d>>>16&255,d>>>8&255,d&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return B.box(Q.trun,a)}static initSegment(t){const e=B.moov(t);return Gt(B.FTYP,e)}static hvc1(t){const e=t.params,s=[t.vps,t.sps,t.pps],i=4,r=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),i-1|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),s.length]);let a=r.length;for(let g=0;g<s.length;g+=1){a+=3;for(let p=0;p<s[g].length;p+=1)a+=2+s[g][p].length}const o=new Uint8Array(a);o.set(r,0),a=r.length;const l=s.length-1;for(let g=0;g<s.length;g+=1){o.set(new Uint8Array([32+g|(g===l?128:0),0,s[g].length]),a),a+=3;for(let p=0;p<s[g].length;p+=1)o.set(new Uint8Array([s[g][p].length>>8,s[g][p].length&255]),a),a+=2,o.set(s[g][p],a),a+=s[g][p].length}const h=B.box(Q.hvcC,o),d=t.width,c=t.height,u=t.pixelRatio[0],f=t.pixelRatio[1];return B.box(Q.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,d>>8&255,d&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),h,B.box(Q.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),B.box(Q.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,f>>24,f>>16&255,f>>8&255,f&255])))}}Gs=B,B.FTYP=Gs.box(Q.ftyp,Xa,Ec,Xa,yc),B.DINF=Gs.box(Q.dinf,Gs.box(Q.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));const za=9e4;function zi(n,t,e=1,s=!1){const i=n*t*e;return s?Math.round(i):i}function Tc(n,t,e=1,s=!1){return zi(n,t,1/e,s)}function rs(n,t=!1){return zi(n,1e3,1/za,t)}function Sc(n,t=1){return zi(n,za,1/t)}function Qa(n){const{baseTime:t,timescale:e,trackId:s}=n;return`${t/e} (${t}/${e}) trackId: ${s}`}const Ac=10*1e3,Ic=1024,Lc=1152,Rc=1536,Qi=8589934592;function Ja(n,t,e,s){return{duration:t,size:e,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:n?2:1,isNonSync:n?0:1,paddingValue:0}}}class Ks extends xt{constructor(t,e,s,i){super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=s,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;(!e||!t||t.trackId!==e.trackId||t.baseTime!==e.baseTime||t.timescale!==e.timescale)&&this.log(`Reset initPTS: ${e&&Qa(e)} > ${t&&Qa(t)}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const s=t[0].pts,i=t.reduce((r,a)=>{let o=a.pts,l=o-r;return l<-4294967296&&(e=!0,o=Nt(o,s),l=o-r),l>0?r:o},s);return e&&this.debug("PTS rollover detected"),i}remux(t,e,s,i,r,a,o,l,h){let d,c,u,f,g,p,v=r,E=r;const y=!h.iframe&&t.pid>-1,T=e.pid>-1,S=e.samples.length,A=t.samples.length>0,L=o&&S>0||S>1;if((!y||A)&&(!T||L)||this.ISGenerated||o){if(this.ISGenerated){var I,b,k,D;const U=this.videoTrackConfig;(U&&(e.width!==U.width||e.height!==U.height||((I=e.pixelRatio)==null?void 0:I[0])!==((b=U.pixelRatio)==null?void 0:b[0])||((k=e.pixelRatio)==null?void 0:k[1])!==((D=U.pixelRatio)==null?void 0:D[1]))||!U&&L||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(t,e,r,a));const C=this.isVideoContiguous;let w=-1,N;if(L&&(w=bc(e.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,w>0){this.warn(`Dropped ${w} out of ${S} video samples due to a missing keyframe`);const U=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(w),e.dropped+=w,E+=(e.samples[0].pts-U)/e.inputTimeScale,N=E}else w===-1&&(this.warn(`No keyframe found out of ${S} video samples`),p=!1);if(this.ISGenerated){if(A&&L&&r){const U=this.getVideoStartPts(e.samples),G=(Nt(t.samples[0].pts,U)-U)/e.inputTimeScale;v+=Math.max(0,G),E+=Math.max(0,-G)}if(A){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(t,e,r,a)),c=this.remuxAudio(t,v,this.isAudioContiguous,a,T||L||l===K.AUDIO?E:void 0,h),L){const U=c?c.endPTS-c.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(t,e,r,a)),d=this.remuxVideo(e,E,C,U,h)}}else L&&(d=this.remuxVideo(e,E,C,0,h));d&&(d.firstKeyFrame=w,d.independent=w!==-1,d.firstKeyFramePTS=N)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=Za(s,r,this._initPTS,this._initDTS)),i.samples.length&&(f=to(i,r,this._initPTS))),{audio:c,video:d,initSegment:u,independent:p,text:f,id3:g}}computeInitPts(t,e,s,i){const r=Math.round(s*e);let a=Nt(t,r);if(a<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-a)/e} ${i}`);a<r;)a+=Qi;return a-r}generateIS(t,e,s,i){const r=t.samples,a=e.samples,o=this.typeSupported,l={},h=this._initPTS,d=!h||i;let c="audio/mp4",u,f,g,p=-1;if(d&&(u=f=1/0),t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":o.mpeg?(c="audio/mpeg",t.codec=""):o.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3";break}if(l.audio={id:"audio",container:c,codec:t.codec,initSegment:t.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):B.initSegment([t]),metadata:{channelCount:t.channelCount}},d){p=t.id,g=t.inputTimeScale;const v=this.computeInitPts(r[0].pts,g,s,"audio");(!h||g!==h.timescale||s===0&&v<h.baseTime)&&(u=f=v)}}if(e.sps&&e.pps&&a.length){if(e.timescale=e.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:B.initSegment([e]),metadata:{width:e.width,height:e.height}},d){p=e.id,g=e.inputTimeScale;const v=this.getVideoStartPts(a),E=Nt(a[0].dts,v),y=this.computeInitPts(E,g,s,"video"),T=this.computeInitPts(v,g,s,"video");if(!h||g!==h.timescale||$(u)||s===0&&T<h.baseTime){f=Math.min(f,y);const S=!h&&this.isVideoContiguous?T:y;u=Math.min(u,S)}}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,d&&$(u)?(h&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${u/g} != initPTS: ${h.baseTime/h.timescale} (${h.baseTime}/${h.timescale}) trackId: ${h.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${u/g} (${u}/${g}) trackId: ${p}`),this._initPTS={baseTime:u,timescale:g,trackId:p},this._initDTS={baseTime:f,timescale:g,trackId:p}):u=g=void 0,{tracks:l,initPTS:u,timescale:g,trackId:p}}remuxVideo(t,e,s,i,r){const a=t.inputTimeScale,o=t.samples,l=[],h=o.length,d=this._initPTS,c=d.baseTime*a/d.timescale;let u=this.nextVideoTs,f=8,g=this.videoSampleDuration,p,v,E=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,T=!1;if(!s||u===null){const _=c+e*a,O=o[0].pts-Nt(o[0].dts,o[0].pts);We()&&u!==null&&Math.abs(_-O-(u+c))<15e3?s=!0:u=_-O-c}const S=u+c;for(let _=0;_<h;_++){const O=o[_];O.pts=Nt(O.pts,S),O.dts=Nt(O.dts,S),O.dts<o[_>0?_-1:_].dts&&(T=!0)}T&&o.sort(function(_,O){const H=_.dts-O.dts,j=_.pts-O.pts;return H||j}),p=o[0].dts,v=o[o.length-1].dts;const A=v-p,L=A?Math.round(A/(h-1)):g||t.inputTimeScale/30;if(s){const _=p-S,O=_>L,H=_<-1;if((O||H)&&(O?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${rs(_,!0)} ms (${_}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${rs(-_,!0)} ms (${_}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!H||S>=o[0].pts||We())){p=S;const j=o[0].pts-_;if(O)o[0].dts=p,o[0].pts=j;else{let tt=!0;for(let X=0;X<o.length&&!(o[X].dts>j&&tt);X++){const Z=o[X].pts;if(o[X].dts-=_,o[X].pts-=_,X<o.length-1){const rt=o[X+1].pts,Rt=o[X].pts,et=rt<=Rt,dt=rt<=Z;tt=et==dt}}}this.log(`Video: Initial PTS/DTS adjusted: ${rs(j,!0)}/${rs(p,!0)}, delta: ${rs(_,!0)} ms`)}}p=Math.max(0,p);let I=0,b=0,k=p;for(let _=0;_<h;_++){const O=o[_],H=O.units,j=H.length;let tt=0;for(let X=0;X<j;X++)tt+=H[X].data.length;b+=tt,I+=j,O.length=tt,O.dts<k?(O.dts=k,k+=L/4|0||1):k=O.dts,E=Math.min(O.pts,E),y=Math.max(O.pts,y)}v=o[h-1].dts;const D=b+4*I+8;let C;try{C=new Uint8Array(D)}catch(_){this.observer.emit(m.ERROR,m.ERROR,{type:Y.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:r,error:_,bytes:D,reason:`fail allocating video mdat ${D}`});return}Tt(C,0,D),Tt(C,4,Q.mdat);let w=!1,N=Number.POSITIVE_INFINITY,U=Number.POSITIVE_INFINITY,G=Number.NEGATIVE_INFINITY,M=Number.NEGATIVE_INFINITY;for(let _=0;_<h;_++){const O=o[_],H=O.units;let j=0;for(let Z=0,rt=H.length;Z<rt;Z++){const Rt=H[Z],et=Rt.data,dt=Rt.data.byteLength;Tt(C,f,dt),f+=4,C.set(et,f),f+=dt,j+=4+dt}let tt;if(_<h-1)g=o[_+1].dts-O.dts,tt=o[_+1].pts-O.pts;else{const Z=this.config,rt=_>0?O.dts-o[_-1].dts:L;if(tt=_>0?O.pts-o[_-1].pts:L,Z.stretchShortVideoTrack&&this.nextAudioTs!==null){const Rt=Math.floor(Z.maxBufferHole*a),et=(i?E+i*a:this.nextAudioTs+c)-O.pts;et>Rt?(g=et-rt,g<0?g=rt:w=!0,this.log(`It is approximately ${et/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=rt}else g=rt}let X=Math.round(O.pts-O.dts);if(N=Math.min(N,g),G=Math.max(G,g),U=Math.min(U,tt),M=Math.max(M,tt),!s&&_===0&&X>g){const Z=Math.round(X/L)*L;Z-X===1&&(this.log(`pad first CTS ${X} -> ${Z} of sn: ${r.sn}`),X=Z)}l.push(Ja(O.key,g,j,X))}if(l.length){const _=We();if(_){if(_<70){const O=l[0].flags;O.dependsOn=2,O.isNonSync=0}}else if(Lh()&&M-U<G-N&&L/G<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let O=p;for(let H=0,j=l.length;H<j;H++){const tt=O+l[H].duration,X=O+l[H].cts;if(H<j-1){const Z=tt+l[H+1].cts;l[H].duration=Z-X}else l[H].duration=H?l[H-1].duration:L;l[H].cts=0,O=tt}}}g=w||!g?L:g;const F=v+g;this.nextVideoTs=u=F-c,this.videoSampleDuration=g,this.isVideoContiguous=!0,r.iframe&&(l.length===1?(l[0].duration=g=r.duration*a,this.nextVideoTs=u=p+g-c):this.warn(`Not adjusting IFrame duration (sample count ${l.length})`));const x={data1:B.moof(r.sn,p,ht(t,{samples:l})),data2:C,startPTS:(E-c)/a,endPTS:(y+g-c)/a,startDTS:(p-c)/a,endDTS:u/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:t.dropped};return t.samples=[],t.dropped=0,x}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return Lc;case"ac3":return Rc;default:return Ic}}remuxAudio(t,e,s,i,r,a){const o=t.inputTimeScale,l=t.samplerate?t.samplerate:o,h=o/l,d=this.getSamplesPerFrame(t),c=d*h,u=this._initPTS,f=t.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],p=r!==void 0;let v=t.samples,E=f?0:8,y=this.nextAudioTs||-1;const T=u.baseTime*o/u.timescale,S=T+e*o;if(this.isAudioContiguous=s=s||v.length&&y>0&&(i&&Math.abs(S-(y+T))<9e3||Math.abs(Nt(v[0].pts,S)-(y+T))<20*c),v.forEach(function(M){M.pts=Nt(M.pts,S)}),!s||y<0){const M=v.length;if(v=v.filter(F=>F.pts>=0),M!==v.length&&this.warn(`Removed ${v.length-M} of ${M} samples (initPTS ${T} / ${o})`),!v.length)return;r===0?y=0:i&&!p?y=Math.max(0,S-T):y=v[0].pts-T}if(t.segmentCodec==="aac"){const M=this.config.maxAudioFramesDrift;for(let F=0,x=y+T;F<v.length;F++){const _=v[F],O=_.pts,H=O-x,j=Math.abs(1e3*H/o);if(H<=-M*c&&p)F===0&&(this.warn(`Audio frame @ ${(O/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*H/o)} ms.`),this.nextAudioTs=y=O-T,x=O);else if(H>=M*c&&j<Ac&&p){let tt=Math.round(H/c);for(x=O-tt*c;x<T&&tt&&c;)tt--,x+=c;F===0&&(this.nextAudioTs=y=x-T),this.warn(`Injecting ${tt} audio frames @ ${((x-T)/o).toFixed(3)}s due to ${Math.round(1e3*H/o)} ms gap.`);for(let X=0;X<tt;X++){let Z=fc.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);Z||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),Z=_.unit.subarray()),v.splice(F,0,{unit:Z,pts:x}),x+=c,F++}}_.pts=x,x+=c}}let A=null,L=null,I,b=0,k=v.length;for(;k--;)b+=v[k].unit.byteLength;for(let M=0,F=v.length;M<F;M++){const x=v[M],_=x.unit;let O=x.pts;if(L!==null){const j=g[M-1];j.duration=Math.round((O-L)/h)}else if(s&&t.segmentCodec==="aac"&&(O=y+T),A=O,b>0){b+=E;try{I=new Uint8Array(b)}catch(j){this.observer.emit(m.ERROR,m.ERROR,{type:Y.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:j,bytes:b,reason:`fail allocating audio mdat ${b}`});return}f||(Tt(I,0,b),Tt(I,4,Q.mdat))}else return;I&&I.set(_,E);const H=_.byteLength;E+=H,g.push(Ja(!0,d,H,0)),L=O}const D=g.length;if(!D)return;const C=g[g.length-1];y=L-T,this.nextAudioTs=y+h*C.duration;const w=f?new Uint8Array(0):B.moof(t.sequenceNumber++,A/h,ht({},t,{samples:g}));t.samples=[];const N=(A-T)/o,U=this.nextAudioTs/o,G={data1:w,data2:I,startPTS:N,endPTS:U,startDTS:N,endDTS:U,type:"audio",hasAudio:!0,hasVideo:!1,nb:D};return this.isAudioContiguous=!0,G}}function Nt(n,t){let e;if(t===null)return n;for(t<n?e=-Qi:e=Qi;Math.abs(n-t)>4294967296;)n+=e;return n}function bc(n){for(let t=0;t<n.length;t++)if(n[t].key)return t;return-1}function Za(n,t,e,s){const i=n.samples.length;if(!i)return;const r=n.inputTimeScale;for(let o=0;o<i;o++){const l=n.samples[o];l.pts=Nt(l.pts-e.baseTime*r/e.timescale,t*r)/r,l.dts=Nt(l.dts-s.baseTime*r/s.timescale,t*r)/r}const a=n.samples;return n.samples=[],{samples:a}}function to(n,t,e){const s=n.samples.length;if(!s)return;const i=n.inputTimeScale;for(let a=0;a<s;a++){const o=n.samples[a];o.pts=Nt(o.pts-e.baseTime*i/e.timescale,t*i)/i}n.samples.sort((a,o)=>a.pts-o.pts);const r=n.samples;return n.samples=[],{samples:r}}class Dc extends xt{constructor(t,e,s,i){super("passthrough-remuxer",i),this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=t}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,s,i){this.audioCodec=e,this.videoCodec=s,this.decryptdata=i,this.pendingInitSegment=t,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(t,e,s){this.videoOnlyRemux=!1;let{audioCodec:i,videoCodec:r}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:a,video:o}=this.initData=s||on(t);if(e)dh(t,e);else{const h=a||o;h!=null&&h.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${h.codec}")!`)}a&&(i=eo(a,ut.AUDIO,this)),o&&(r=eo(o,ut.VIDEO,this));const l={};a&&o?l.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:t,id:"main"}:a?l.audio={container:"audio/mp4",codec:i,encrypted:a.encrypted,initSegment:t,id:"audio"}:o?l.video={container:"video/mp4",codec:r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(t,e,s,i,r,a,o,l,h,d,c){var u,f;let{initPTS:g,lastEndTime:p}=this;const v={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};$(p)||(p=this.lastEndTime=r||0);const E=e.samples;if(!E.length)return v;const y=this.pendingInitSegment;y&&(this.pendingInitSegment=void 0,this.generateInitSegment(y,this.decryptdata,d));const T={initPTS:void 0,timescale:void 0,trackId:void 0};let S=this.initData;if((u=S)!=null&&u.length||(this.generateInitSegment(E),S=this.initData),!((f=S)!=null&&f.length))return this.warn("Failed to generate initSegment."),v;if(h.iframe&&S.audio&&S.video){var A;const nt=(A=this.initTracks)==null||(A=A.audiovideo)==null?void 0:A.initSegment,yt=nt?rh(nt):null;if(yt){var L;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(yt,this.decryptdata),(L=this.initData)!=null&&L.length&&(S=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(T.tracks=this.initTracks,v.initSegment=T,this.emitInitSegment=!1);const I=h.iframe,b=c&&(!I||c.includeSampleDetails)?c.tracks:gh(E,S,h,this,I),k=S.audio?b[S.audio.id]:null,D=S.video?b[S.video.id]:null,C=!!S.audio,w=!!S.video;let N="";C&&(N+="audio"),w&&(N+="video");const U=Vs(D,1/0),G=Vs(k,1/0),M=Vs(D,0,!0),F=Vs(k,0,!0);let x=r,_=0;D&&k&&S.audio&&(G>M||U>F)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${U}-${M} a: ${G}-${F}}`,D,k);const O=!!k&&(!D||!g&&G<U||!!g&&g.trackId===S.audio.id),H=O?k:D;if(!H)return this.log(`No media samples found in ${l} ${h.level} ${h.part===-1?"":`part: ${h.part} of`} sn: ${h.sn} at playlist time: ${r}`),v;let j=E,tt,X;if(D&&D.sampleCount>=1&&S.video&&h.iframe){const{trun:nt,start:yt}=D,ct=nt.length===1,$t=nt.length?ct?nt[0].samples:nt[0].samples.concat(...nt.slice(1).map(Jt=>Jt.samples)):[];if($t.length){const Jt=nt[0];let ue=Jt;for(let Kt=nt.length;Kt--;)if(nt[Kt].samples.length){ue=nt[Kt];break}const ni=ue.lastSampleDurationOffset,{defaultSampleDurationOffset:ds}=Jt,Ut=Math.abs(h.duration-(M-U))>.05,Bt=$t.length<D.sampleCount;if(!(Ut||Bt||this.videoOnlyRemux||!ct))_=M-U;else{const Kt=Bt?ue.sampleOffset+ue.samples.reduce((cs,$e)=>cs+$e.size,0):void 0,Ee=Ut?h.duration:M-U,Ct=Pc($t,Ee*S.video.timescale,ni,ds),Re=nh(E,S.video.id,$t.length,Kt,Ct);Re?(j=Re,X=kc(yt,$t)):this.warn(`IFrame remux skipped (sn ${h.sn}); using native sample duration`),_=Re&&Ct?Ee:M-U}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${nt.length})`),_=M-U}else _=O?F-G:M-U;if(this.videoOnlyRemux&&j===E)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${h.sn})`),v;const Z=H.timescale,rt=H.start-r*Z,Rt=O?S.audio.id:S.video.id;if(x=H.start/Z,!(g&&h.id>1)&&(a||!g)&&(_c(g,x,r,_)||Z!==g.timescale)){let nt=!1;const yt=O?"audio":"video";if(g){const ct=r!==0?x/r:1+x/1;nt=x>=0&&Math.abs(1-ct)<.001,this.log(`${yt} timestamps in track ${Rt} at playlist time: ${a?"":"~"}${r} maps to ${x} with initPTS: ${g.baseTime/g.timescale} (${rt/Z-g.baseTime/g.timescale}s diff) (${N}) drift estimate: ${ct} ${nt?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}nt||(this.log(`Found initPTS in ${yt} track ${Rt} at playlist time: ${r} offset: ${x-r} (${rt}/${Z})`),g=null,T.initPTS=rt,T.timescale=Z,T.trackId=Rt)}g?(T.initPTS=g.baseTime,T.timescale=g.timescale,T.trackId=g.trackId):((!T.timescale||T.trackId===void 0||T.initPTS===void 0)&&(this.warn("Could not set initPTS"),T.initPTS=x,T.timescale=1,T.trackId=-1),this.initPTS=g={baseTime:T.initPTS,timescale:T.timescale,trackId:T.trackId});const et=x-g.baseTime/g.timescale,dt=et+_,Qt=w&&H?.ptsMin!==void 0?H.ptsMin/H.timescale-g.baseTime/g.timescale:et,z=X!==void 0&&D?X/D.timescale-g.baseTime/g.timescale:w&&H!=null&&H.ptsMax?H.ptsMax/H.timescale-g.baseTime/g.timescale:dt;_>0?this.lastEndTime=dt:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const pt=(S.audio?S.audio.encrypted:!1)||(S.video?S.video.encrypted:!1),it={data1:j,data2:tt,startPTS:Qt,startDTS:et,endPTS:z,endDTS:dt,type:N,hasAudio:C,hasVideo:w,nb:1,dropped:0,encrypted:pt};v.audio=C&&!w?it:void 0,v.video=w?it:void 0;const St=this.isVideoContiguous,At=D?.sampleCount;if(At){const nt=D.keyFrameIndex,yt=nt!==-1;it.nb=At,it.dropped=nt===0||St?0:yt?nt:At,it.independent=yt,it.firstKeyFrame=nt,yt&&D.keyFrameStart&&(it.firstKeyFramePTS=(D.keyFrameStart-g.baseTime)/g.timescale),St||(v.independent=yt),this.isVideoContiguous||(this.isVideoContiguous=yt),it.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${nt}/${At} dropped: ${it.dropped} start: ${it.firstKeyFramePTS||"NA"}`)}return v.initSegment=T,v.id3=Za(s,r,g,g),i.samples.length&&(v.text=to(i,r,g)),v}}function Vs(n,t,e=!1){return n?.start!==void 0?(n.start+(e?n.duration:0))/n.timescale:t}function kc(n,t){let e=n,s=n;for(let i=0;i<t.length;i++){const{cts:r,duration:a}=t[i];s=Math.max(s,e+(r||0)+a),e+=a}return s}function Pc(n,t,e,s){if(e!==void 0){const r=n[n.length-1];let a=t;for(let o=0;o<n.length-1;o++)a-=n[o].duration;return a<=0&&(a=r.duration),r.duration=a,{durationOffset:e,value:a}}if(s===void 0)return;const i=Math.round(t/n.length);for(let r=0;r<n.length;r++)n[r].duration=i;return{durationOffset:s,value:i}}function _c(n,t,e,s){if(n===null)return!0;const i=Math.max(s,1),r=t-n.baseTime/n.timescale;return Math.abs(r-e)>=i}function eo(n,t,e){const s=n.codec;return s&&s.length>4?s:t===ut.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Is(s,!1):(e.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):s==="mjpg"?s:(e.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let pe;try{pe=self.performance.now.bind(self.performance)}catch{pe=Date.now}const Hs=[{demux:rc,remux:Dc},{demux:ce,remux:Ks},{demux:tc,remux:Ks},{demux:sc,remux:Ks}];Hs.splice(2,0,{demux:ec,remux:Ks});class so{constructor(t,e,s,i,r,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=s,this.id=r,this.logger=a}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,s,i){if(!this.observer)return Ys(s);const r=s.transmuxing;r.executeStart=pe();const a=new Uint8Array(t),{currentTransmuxState:o,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);const{contiguous:h,discontinuity:d,trackSwitch:c,accurateTimeOffset:u,timeOffset:f,initSegmentChange:g}=i||o,{audioCodec:p,videoCodec:v,defaultInitPts:E,duration:y,initSegmentData:T}=l,S=Cc(a,e);if(S&&we(S.method)){const b=this.getDecrypter(),k=xi(S.method);return this.asyncResult=!0,this.decryptionPromise=b.decrypt(a,S.key.buffer,S.iv.buffer,k,s.decryptRange).then(D=>{const C=this.push(D,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}const A=this.needsProbing(d,c);if(A){const b=s.iframe&&T&&ce.probe(T,this.logger)?T:a,k=this.configureTransmuxer(b);if(k)return this.logger.warn(`[transmuxer] ${k.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:Y.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:k,reason:k.message}),r.executeEnd=pe(),Ys(s)}(d||c||g||A)&&this.resetInitSegment(T,p,v,y,e,s),(d||g||A)&&this.resetInitialTimestamp(E),h||this.resetContiguity();const L=this.transmux(a,S,f,u,s);this.asyncResult=ns(L);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,r.executeEnd=pe(),L}flush(t){const e=t.transmuxing;e.executeStart=pe();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const a=[],{timeOffset:o}=i;if(s){const c=s.flush();c&&a.push(this.push(c.buffer,null,t))}const{demuxer:l,remuxer:h}=this;if(!l||!h){e.executeEnd=pe();const c=[Ys(t)];return this.asyncResult?Promise.resolve(c):c}const d=l.flush(o,t);return ns(d)?(this.asyncResult=!0,d.then(c=>(this.flushRemux(a,c,t),a))):(this.flushRemux(a,d,t),this.asyncResult?Promise.resolve(a):a)}flushRemux(t,e,s){if(!this.remuxer)return;const{audioTrack:i,videoTrack:r,id3Track:a,textTrack:o}=e,{accurateTimeOffset:l,timeOffset:h}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id} playlist ${s.level}`);const d=this.remuxer.remux(i,r,a,o,h,l,!0,this.id,s,e.initData,e.sampleData);t.push({remuxResult:d,chunkMeta:s}),s.transmuxing.executeEnd=pe()}resetInitialTimestamp(t){const{demuxer:e,remuxer:s}=this;!e||!s||(e.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;!t||!e||(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,s,i,r,a){const{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(t,e,s,i,r,a),l.resetInitSegment(t,e,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(t,e,s,i,r){let a;return e?.method==="SAMPLE-AES"?a=this.transmuxSampleAes(t,e,s,i,r):a=this.transmuxUnencrypted(t,s,i,r),a}transmuxUnencrypted(t,e,s,i){const{demuxer:r,remuxer:a}=this;if(!r||!a)return Ys(i);const o=r.demux(t,e,i,!1,!this.config.progressive),{audioTrack:l,videoTrack:h,id3Track:d,textTrack:c}=o;return{remuxResult:a.remux(l,h,d,c,e,s,!1,this.id,i,o.initData,o.sampleData),chunkMeta:i}}transmuxSampleAes(t,e,s,i,r){return this.demuxer?this.demuxer.demuxSampleAes(t,e,s,r).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,i,!1,this.id,r,a.initData,a.sampleData),chunkMeta:r})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:i}=this;if(!s)return;let r;try{for(let c=0,u=Hs.length;c<u;c++){var a;if((a=Hs[c].demux)!=null&&a.probe(t,this.logger)){r=Hs[c];break}}}catch(c){return c}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,h=r.demux,d=r.remux;(!o||!(o instanceof h))&&(this.logger.log(`Using ${h.name}`),this.demuxer=new h(s,e,i,this.logger),this.probe=h.probe),(!l||!(l instanceof d))&&(this.logger.log(`Using ${d.name}`),this.remuxer=new d(s,e,i,this.logger))}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Ci(this.config)),t}}function Cc(n,t){let e=null;return n.byteLength>0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(e=t),e}const Ys=n=>({remuxResult:{},chunkMeta:n});function ns(n){return"then"in n&&n.then instanceof Function}class wc{constructor(t,e,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class Oc{constructor(t,e,s,i,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=a}}let io=0;class ro{constructor(t,e,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=io++,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=l=>{const h=l.data,d=this.hls;if(!(!d||!(h!=null&&h.event)||h.instanceNo!==this.instanceNo))switch(h.event){case"init":{var c;const u=(c=this.workerContext)==null?void 0:c.objectURL;u&&self.URL.revokeObjectURL(u);break}case"transmuxComplete":{this.handleTransmuxComplete(h.data);break}case"flush":{this.onFlush(h.data);break}case"workerLog":{d.logger[h.data.logType]&&d.logger[h.data.logType](h.data.message);break}default:{h.data=h.data||{},h.data.frag=this.frag,h.data.part=this.part,h.data.id=this.id,d.trigger(h.event,h.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;const h=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:h})};const r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const a=(l,h)=>{h=h||{},h.frag=this.frag||void 0,l===m.ERROR&&(h=h,h.parent=this.id,h.part=this.part,this.error=h.error),this.hls.trigger(l,h)};this.observer=new Vi,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);const o=En(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const l=this.hls.logger;if(r.workerPath||Ud()){try{r.workerPath?(l.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=Gd(r.workerPath)):(l.log(`injecting Web Worker for "${e}"`),this.workerContext=Bd());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:e,config:ft(r)})}catch(h){l.warn(`Error setting up "${e}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new so(this.observer,o,r,"",e,t.logger)}return}}this.transmuxer=new so(this.observer,o,r,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=io++;const e=this.hls.config,s=En(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:s,id:this.id,config:ft(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),Kd(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,s,i,r,a,o,l,h,d){var c,u;h.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,p=a?a.start:r.start,v=r.decryptdata,E=this.frag,y=E?r.cc!==E.cc:!0,T=E?h.level!==E.level:!0,S=E?h.sn-E.sn:-1,A=this.part?h.part-this.part.index:-1,L=S===0&&h.id>1&&h.id===E?.stats.chunkCount,I=!T&&(S===1||S===0&&(A===1||L&&A<=0)),b=self.performance.now();(T||S||r.stats.parsing.start===0)&&(r.stats.parsing.start=b),a&&(A||!I)&&(a.stats.parsing.start=b);const k=!(E&&((c=r.initSegment)==null?void 0:c.url)===((u=E.initSegment)==null?void 0:u.url)),D=new Oc(y,I,l,T,p,k);if(!I||y||k){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${h.sn}${h.part>-1?" part: "+h.part:""} ${this.id} playlist: ${h.level} id: ${h.id}
22
+ discontinuity: ${y}
23
+ trackSwitch: ${T}
24
+ contiguous: ${I}
25
+ accurateTimeOffset: ${l}
26
+ timeOffset: ${p}
27
+ initSegmentChange: ${k}`);const C=new wc(s,i,e,o,d);this.configureTransmuxer(C)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:t,decryptdata:v,chunkMeta:h,state:D},t instanceof ArrayBuffer?[t]:[]);else if(g){const C=g.push(t,v,h,D);ns(C)?C.then(w=>{this.handleTransmuxComplete(w)}).catch(w=>{this.transmuxerError(w,h,"transmuxer-interface push error")}):this.handleTransmuxComplete(C)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(s){const i=s.flush(t);ns(i)?i.then(r=>{this.handleFlushResult(r,t)}).catch(r=>{this.transmuxerError(r,t,"transmuxer-interface flush error")}):this.handleFlushResult(i,t)}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):s&&s.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}const no=100;class ao extends Ns{constructor(t,e,s){super(t,e,s,"audio-stream-controller",K.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(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)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),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))}onInitPtsFound(t,e){const{frag:s,id:i,initPTS:r,timescale:a,trackId:o,timestampOffsets:l}=e;if(i===K.MAIN){const h=s.cc,d=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${h} found from main: ${r/a} (${r}/${a}) trackId: ${o}`),this.mainAnchor=s,this.state===P.WAITING_INIT_PTS){const c=this.waitingData;(!c&&!this.loadingParts||c&&c.frag.cc!==h)&&this.syncWithAnchor(s,c?.frag)}else!this.hls.hasEnoughToStart&&d&&d.cc!==h?(d.abortRequests(),this.syncWithAnchor(s,d)):this.state===P.IDLE&&this.tick()}}getLoadPosition(){var t;return!this.startFragRequested&&this.nextLoadPosition>=0&&((t=this.switchingTrack)==null?void 0:t.flushImmediate)!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(e&&i?.cc===e.cc)return;const r=(i||t).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=Mn(a,r,o);l&&this.fragmentTracker.getState(l)!==mt.OK&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===P.IDLE&&this.doTickIdle())}startLoad(t,e){if(!this.levels){this.startPosition=t,this.state=P.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(no),s>0&&t===-1&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),t=s),this.state=P.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,!e&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case P.IDLE:this.doTickIdle();break;case P.WAITING_TRACK:{const{levels:t,trackId:e}=this,s=t?.[e],i=s?.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=P.WAITING_INIT_PTS}break}case P.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case P.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:i,complete:r}=t,a=this.mainAnchor;if(this.initPTS[e.cc]!==void 0){this.waitingData=null,this.state=P.FRAG_LOADING;const o=i.flush().buffer,l={frag:e,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),r&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==t.frag.cc&&this.syncWithAnchor(a,t.frag)}else this.state=P.IDLE}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){var t;const{hls:e,levels:s,media:i,trackId:r}=this,a=e.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[r]))return;const o=s[r],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=P.WAITING_TRACK,this.startFragRequested=!1;return}const h=this.getBufferOutput();this.bufferFlushed&&h&&(this.bufferFlushed=!1,this.afterBufferFlushed(h,ut.AUDIO));const d=this.getFwdBufferInfo();if(d===null)return;if(!this.switchingTrack&&this._streamEnded(d,l)){e.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=P.ENDED;return}const c=d.len,u=e.maxBufferLength,f=l.fragments,g=f[0].start,p=this.getLoadPosition(),v=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?p:d.end;if(this.switchingTrack&&i){const T=p;l.PTSKnown&&T<g&&T>=this.timelineOffset&&(d.end>g||d.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${T} -> ${g} + 0.05`),i.currentTime=g+.05)}if(c>=u&&!this.switchingTrack&&v<f[f.length-1].start)return;let E=this.getNextFragment(v,l);if(E&&this.isLoopLoading(E,v)&&(E=this.getNextFragmentLoopLoading(E,l,d,K.MAIN,u)),!E){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(d,u,E))return;let y=((t=this.mainFragLoading)==null?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&Et(E)&&!E.endList&&(!l.live||!this.loadingParts&&v<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===mt.OK&&(this.mainFragLoading=y=null),y&&Et(y))){if(E.start>y.end){const T=this.fragmentTracker.getFragAtPos(v,K.MAIN);T&&T.end>y.end&&(y=T,this.mainFragLoading={frag:T,targetBufferTime:null})}if(E.start>y.end)return}this.loadFragment(E,o,v)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(s=>new Pe(s))}onAudioTrackSwitching(t,e){const s=!!e.url;this.trackId=e.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=e,e.flushImmediate||(this.nextTrackId=e.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(e),this.state!==P.STOPPED&&(this.setInterval(no),this.state=P.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(t,e){var s;const{levels:i}=this,{details:r,id:a,groupId:o,track:l}=e;if(!i){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}const h=this.mainDetails;if(!h||r.endCC>h.endCC||h.expired){this.cachedTrackLoadedData=e,this.state!==P.STOPPED&&(this.state=P.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=i[a];let c=0;if(r.live||(s=d.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(d.details){var u;c=this.alignPlaylists(r,d.details,(u=this.levelLastLoaded)==null?void 0:u.details)}r.alignedSliding||(Fs(h,r,this),c=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(h,c),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:e.groupId}),this.state===P.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=P.IDLE),this.tick()}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,payload:r}=t,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const h=l[o];if(!h){this.warn("Audio track is undefined on fragment load progress");return}const d=h.details;if(!d){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const c=a.defaultAudioCodec||h.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new ro(this.hls,K.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[s.cc],g=(e=s.initSegment)==null?void 0:e.data;if(f!==void 0){const p=i?i.index:-1,v=p!==-1,E=new _s(s.level,s.sn,s.stats.chunkCount,r.byteLength,p,v,s.duration);u.push(r,g,c,"",s,i,d.totalduration,!1,E,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${d.startSN} ,${d.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new wa,complete:!1};p.push(new Uint8Array(r)),this.state!==P.STOPPED&&(this.state=P.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===K.MAIN&&Et(e.frag)&&(this.mainFragLoading=e,this.state===P.IDLE&&this.tick())}onFragBuffered(t,e){const{frag:s,part:i}=e;if(s.type!==K.AUDIO){!this.audioOnly&&s.type===K.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Et(s)){const r=this.switchingTrack;r&&(this.bufferedTrack=r)}this.fragBufferedComplete(s,i),this.media&&this.tick()}getFwdBufferInfo(){const t=this.getBufferOutput();return super.getFwdBufferInfo(t,K.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const{fragPlaying:e,switchingTrack:s}=this,i=!e||e.level!==t?.level;return i&&t&&this.cleanupBackBuffer(),s&&(i||e?.level===s.id)&&this.completeAudioSwitch(s),!0}onError(t,e){var s;if(e.fatal){this.state=P.ERROR;return}switch(e.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(K.AUDIO,e);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===P.WAITING_TRACK&&((s=e.context)==null?void 0:s.type)===st.AUDIO_TRACK&&(this.state=P.IDLE);break;case R.BUFFER_APPEND_NO_PROGRESS:if(e.parent!=="audio")return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of track ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case R.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(K.AUDIO,e);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(e.parent!=="audio")return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(e.parent!=="audio")return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onBufferFlushing(t,{type:e}){e!==ut.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==ut.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===P.ENDED&&(this.state=P.IDLE);const s=this.getBufferOutput();s&&(this.afterBufferFlushed(s,e),this.tick())}}_handleTransmuxComplete(t){var e;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:a}=t,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:h,level:d}=o,{details:c}=d,{audio:u,text:f,id3:g,initSegment:p}=r;if(this.fragContextChanged(l)||!c){this.fragmentTracker.removeFragment(l),p!=null&&p.tracks&&this.resetTransmuxer();return}if(this.state=P.PARSING,u&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:v}=this,E=v.nextAudioTrackBufferFlushForwardOffset,y=Math.max(this.getLoadPosition()+E,(h||l).start);super.flushMainBuffer(y,Number.POSITIVE_INFINITY,K.AUDIO)}if(p!=null&&p.tracks){const v=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(d,p.tracks,v,a),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:s,tracks:p.tracks})}if(u){const{startPTS:v,endPTS:E,startDTS:y,endDTS:T}=u;h&&(h.elementaryStreams[ut.AUDIO]={startPTS:v,endPTS:E,startDTS:y,endDTS:T}),l.setElementaryStreamInfo(ut.AUDIO,v,E,y,T),this.bufferFragmentData(u,l,h,a)}if(g!=null&&(e=g.samples)!=null&&e.length){const v=ht({id:s,frag:l,details:c},g);i.trigger(m.FRAG_PARSING_METADATA,v)}if(f){const v=ht({id:s,frag:l,details:c},f);i.trigger(m.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(t,e,s,i){if(this.state!==P.PARSING||(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio))return;const r=e.audio;r.id=K.AUDIO;const a=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a?.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(m.BUFFER_CODECS,e);const o=r.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);if(this.switchingTrack||i===mt.NOT_LOADED||i===mt.PARTIAL){var r;if((r=e.details)!=null&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=P.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==e.details.fragmentStart&&Fs(a,e.details,this)}else super.loadFragment(t,e,s)}else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack&&t.flushImmediate){const{name:e,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o}=this.bufferedTrack;Te({name:e,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o},t,Se)||(bs(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.bufferedTrack=t,this.switchingTrack=null,e.trigger(m.AUDIO_TRACK_SWITCHED,W({},t))}get nextAudioTrack(){return this.nextTrackId}}class Ws extends xt{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.loadingSync=!1,this.hls=t}destroy(){this.clearTimer(),this.hls=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,s){const i=e?.renditionReports;if(i){let r=-1;for(let a=0;a<i.length;a++){const o=i[a];let l;try{l=new self.URL(o.URI,e.url).href}catch(h){this.warn(`Could not construct new URL for Rendition Report: ${h}`),l=o.URI||""}if(l===t){r=a;break}else l===t.substring(0,l.length)&&(r=a)}if(r!==-1){const a=i[r],o=parseInt(a["LAST-MSN"])||e.lastPartSn;let l=parseInt(a["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const d=Math.min(e.age-e.partTarget,e.targetduration);l>=0&&d>e.partTarget&&(l+=1)}const h=s&&Rn(s);return new ki(o,l>=0?l:void 0,h)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return t}playlistLoaded(t,e,s){const{details:i,stats:r}=e,a=i.fragments,o=self.performance.now(),l=r.loading.first?Math.max(0,Math.floor(o-r.loading.first)):0;i.advancedDateTime=Date.now()-l;const h=this.hls.config.timelineOffset;if(h!==i.appliedTimelineOffset){const c=Math.max(h||0,0);i.appliedTimelineOffset=c,a.forEach(u=>{u?.setStart(u.playlistOffset+c)})}if(i.live||s!=null&&s.live){var d;const c="levelInfo"in e?e.levelInfo:e.track;i.reloaded(s);const u=(d=a[a.length-1])==null?void 0:d.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const A=new Error(`${u} playlist ${c.id} hit max allowed unchanged reloads.`);this.warn(A);const{networkDetails:L,context:I}=e;this.hls.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:R.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:A,reason:A.message,level:e.level,parent:u,context:I,networkDetails:L,stats:r});return}if(s){Dd(s,i,this);const A=i.playlistParsingError;if(A){this.warn(A);const L=this.hls;if(!L.config.ignorePlaylistParsingErrors){const{networkDetails:I}=e;L.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:A,reason:A.message,level:e.level,parent:u,networkDetails:I,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const f=this.hls.mainForwardBufferInfo,g=f?f.end-f.len:0,p=(i.edge-g)*1e3,v=La(i,p);i.requestScheduled+v<o?i.requestScheduled=o:i.requestScheduled<=o&&(i.requestScheduled+=v);const E=e.deliveryDirectives;if(this.log(`live playlist ${t} ${i.advanced?`REFRESHED ${i.lastPartSn} - ${i.lastPartIndex}`:i.updated?"UPDATED":`MISSED (received ${i.lastPartSn} - ${i.lastPartIndex}${E?` | requested ${E.msn} - ${E.part}`:""})`}`),!this.canLoad||!i.live)return;let y,T,S;if(i.canBlockReload&&i.advanced){const A=this.hls.config.lowLatencyMode,L=i.lastPartSn,I=i.endSN,b=i.lastPartIndex,k=b!==-1,D=L===I;k?D?(T=I+1,S=A?0:b):(T=L,S=A?b+1:i.maxPartIndex):T=I+1;const C=i.age,w=C+i.ageHeader;let N=Math.min(w-i.partTarget,i.targetduration*1.5);if(N>0){if(w>i.targetduration*3)this.log(`Playlist last advanced ${C.toFixed(2)}s ago. Omitting segment and part directives.`),T=void 0,S=void 0;else if(s!=null&&s.tuneInGoal&&w-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${N} with playlist age: ${i.age}`),N=0;else{const U=Math.floor(N/i.targetduration);if(T+=U,S!==void 0){const G=Math.round(N%i.targetduration/i.partTarget);S+=G}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${C.toFixed(2)}s goal: ${N} skip sn ${U} to part ${S}`)}i.tuneInGoal=N}if(y=this.getDeliveryDirectives(i,e.deliveryDirectives,T,S),A||!D){i.requestScheduled=o,this.loadingPlaylist(c,y);return}}else(i.canBlockReload||i.canSkipUntil)&&(y=this.getDeliveryDirectives(i,e.deliveryDirectives,T,S));y&&T!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(v-l*2,v/2)),this.scheduleLoading(c,y,i)}else this.clearTimer()}scheduleLoading(t,e,s){const i=s||t.details;if(!i){this.loadingPlaylist(t,e);return}const r=self.performance.now(),a=i.requestScheduled;if(r>=a&&!this.loadingSync){this.loadingSync=!0,this.loadingPlaylist(t,e),this.loadingSync=!1;return}const o=Math.max(a-r,0);this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),o)}getDeliveryDirectives(t,e,s,i){let r=Rn(t);return e!=null&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,i=e.part,r=Xe.No),new ki(s,i,r)}checkRetry(t){const e=t.details,s=gs(t),i=t.errorAction,{action:r,retryCount:a=0,retryConfig:o}=i||{},l=!!i&&!!o&&(r===Dt.RetryRequest||!i.resolved&&r===Dt.SendAlternateToPenaltyBox);if(l){var h;if(a>=o.maxNumRetry)return!1;if(s&&(h=t.context)!=null&&h.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{var d;const c=Ke((d=t.response)==null?void 0:d.code);if(this.clearTimer(),c)this.log("Waiting for connection (offline)"),t.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const u=hi(o,a);this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${e}" in ${u}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),u)}}t.levelRetry=!0,i.resolved=!0}return l}checkOfflineStatus(){this.clearTimer(),Ke(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function oo(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(!as(n[e].attrs,t[e].attrs))return!1;return!0}function as(n,t,e){const s=n["STABLE-RENDITION-ID"];return s&&!e?s===t["STABLE-RENDITION-ID"]:!(e||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>n[i]!==t[i])}class lo extends Ws{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.LEVEL_LOADING,this.onLevelLoading,this),t.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.LEVEL_LOADING,this.onLevelLoading,this),t.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(m.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=e.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,o)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>i?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(u=>ze(u.groupId,s));if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,f)=>{u.id=f});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!r&&l){const u=se(l,o,Se);if(u>-1)r=o[u];else{const f=se(l,this.tracks);r=this.tracks[f]}}let h=this.findTrackId(r);h===-1&&r&&(h=this.findTrackId(null));const d={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,d);const c=this.trackId;if(h!==-1&&c===-1)this.setAudioTrack(h);else if(o.length&&c===-1){var a;const u=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(u.message),this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:u})}}}onError(t,e){e.fatal||!e.context||e.context.type===st.AUDIO_TRACK&&e.context.id===this.trackId&&ze(e.context.groupId,this.groupIds)&&this.checkRetry(e)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t,!1)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Te(t,i,Se))return i;const r=se(t,this.tracksInGroup,Se);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r,"flushImmediate"in t&&t.flushImmediate),a}else if(i){let a=e.loadLevel;a===-1&&(a=e.firstAutoLevel);const o=qh(t,e.levels,s,a,Se);if(o===-1)return null;e.nextLoadLevel=o}if(t.channels||t.audioCodec){const a=se(t,s);if(a>-1)return s[a]}}}return null}setAudioTrack(t,e=!0){const s=this.tracksInGroup;if(t<0||t>=s.length){this.warn(`Invalid audio track id: ${t}`);return}this.selectDefaultTrack=!1;const i=this.currentTrack,r=s[t],a=r.details&&!r.details.live;if(t===this.trackId&&r===i&&a||(this.log(`Switching to audio-track ${t} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=t,this.currentTrack=r,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,W(W({},r),{},{flushImmediate:e})),a))return;const o=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(o)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const i=e[s];if(!(this.selectDefaultTrack&&!i.default)&&(!t||Te(t,i,Se)))return s}if(t){const{name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:l}=t;for(let h=0;h<e.length;h++){const d=e[h];if(Te({name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:l},d,Se))return h}for(let h=0;h<e.length;h++){const d=e[h];if(as(t.attrs,d.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return h}for(let h=0;h<e.length;h++){const d=e[h];if(as(t.attrs,d.attrs,["LANGUAGE"]))return h}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&bs(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),a=t.details,o=a?.age;this.log(`Loading audio-track ${s} "${t.name}" lang:${t.lang} group:${i}${e?.msn!==void 0?" at sn "+e.msn+" part "+e.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}}class ri{constructor(t){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:t}=this;t&&(t.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(m.BUFFER_CODECS,this.onBufferCodecs,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:t}=this;t&&(t.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(m.BUFFER_CODECS,this.onBufferCodecs,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(t,e){if(!this.hls)return;const s=this.hls.levels[e.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(t,e){const s=e.media;this.clientRect=null,this.hls&&(s instanceof HTMLVideoElement?(this.media=s,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(t,e){this.restrictedLevels=[],e.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls){if((this.timer||this.observer)&&($(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(this.observer===void 0&&this.timer===void 0){const t=this.hls.levels;t.length>1&&t.some(e=>!!e.videoCodec)&&this.startCapping()}}}onBufferCodecs(t,e){e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}const t=this.hls.levels;if(t.length>1){const e=this.hls,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}else t.length===1&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;const e=this.hls.levels;if(!e.length)return-1;const s=e.filter((i,r)=>this.isLevelAllowed(i)&&r<=t);return this.observer||(this.clientRect=null),ri.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}observe(){const t=self.ResizeObserver;t&&(this.observer=new t(e=>{var s;const i=(s=e[0])==null?void 0:s.contentRect;i&&(this.clientRect=i,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var t;this.timer||this.observer||!((t=this.hls)!=null&&t.config.capLevelToPlayerSize)||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const s=t.getBoundingClientRect();e.width=s.width,e.height=s.height,!e.width&&!e.height&&(e.width=s.right-s.left||t.width||0,e.height=s.bottom-s.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls)return t;const{ignoreDevicePixelRatio:e,maxDevicePixelRatio:s}=this.hls.config;if(!e)try{t=self.devicePixelRatio}catch{}return Math.min(t,s)}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,s){if(!(t!=null&&t.length))return-1;const i=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let r=t.length-1;const a=Math.max(e,s);for(let o=0;o<t.length;o+=1){const l=t[o];if((l.width>=a||l.height>=a)&&i(l,t[o+1])){r=o;break}}return r}}var wt=class Mr{constructor(t,e){Array.isArray(t)&&(t=t.map(s=>s instanceof Mr?s:new Mr(s))),this.value=t,this.params=e}};const Mc="Dict";function xc(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":typeof n=="object"?JSON.stringify(n):String(n)}function Fc(n,t,e,s){return new Error(`failed to ${n} "${xc(t)}" as ${e}`,{cause:s})}const ho="Bare Item",Nc="Boolean",$c="Byte Sequence",Uc="Decimal",Bc="Integer";function Gc(n){return n<-999999999999999||999999999999999<n}const Kc="String",Vc=/[\x00-\x1f\x7f]+/;var co=class{constructor(n){this.description=n}};const Hc="Token",Yc="Key";function ne(n,t,e){return Fc("serialize",n,t,e)}function Wc(n){if(typeof n!="boolean")throw ne(n,Nc);return n?"?1":"?0"}function jc(n){if(ArrayBuffer.isView(n)===!1)throw ne(n,$c);return`:${Bl(n)}:`}function uo(n){if(Gc(n))throw ne(n,Bc);return n.toString()}function qc(n){return`@${uo(n.getTime()/1e3)}`}function Xc(n){const t=qr(n,3);if(Math.floor(Math.abs(t)).toString().length>12)throw ne(n,Uc);const e=t.toString();return e.includes(".")?e:`${e}.0`}function zc(n){if(Vc.test(n))throw ne(n,Kc);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Qc(n){return n.description||n.toString().slice(7,-1)}function fo(n){const t=Qc(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw ne(t,Hc);return t}function Ji(n){switch(typeof n){case"number":if(!$(n))throw ne(n,ho);return Number.isInteger(n)?uo(n):Xc(n);case"string":return zc(n);case"symbol":return fo(n);case"boolean":return Wc(n);case"object":if(n instanceof Date)return qc(n);if(n instanceof Uint8Array)return jc(n);if(n instanceof co)return fo(n);default:throw ne(n,ho)}}function Zi(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw ne(n,Yc);return n}function tr(n){return n==null?"":Object.entries(n).map(([t,e])=>e===!0?`;${Zi(t)}`:`;${Zi(t)}=${Ji(e)}`).join("")}function go(n){return n instanceof wt?`${Ji(n.value)}${tr(n.params)}`:Ji(n)}function Jc(n){return`(${n.value.map(go).join(" ")})${tr(n.params)}`}function Zc(n,t={whitespace:!0}){if(typeof n!="object"||n==null)throw ne(n,Mc);const e=n instanceof Map?n.entries():Object.entries(n),s=t!=null&&t.whitespace?" ":"";return Array.from(e).map(([i,r])=>{r instanceof wt||(r=new wt(r));let a=Zi(i);return r.value===!0?a+=tr(r.params):(a+="=",Array.isArray(r.value)?a+=Jc(r):a+=go(r)),a}).join(`,${s}`)}function mo(n,t){return Zc(n,t)}const tu=["url"],eu=["version","eventTargets","sid","transmissionMode"],su=["customData","headers"],po=n=>n instanceof wt?new wt(Math.round(n.value),n.params):Math.round(n),er=n=>Array.isArray(n)?n.map(po):po(n),sr=(n,t)=>Array.isArray(n)?n.map(e=>sr(e,t)):n instanceof wt&&typeof n.value=="string"?new wt(sr(n.value,t),n.params):(t.baseUrl&&(n=Hl(n,Vl(t.baseUrl))),t.version===1?encodeURIComponent(n):n),vo=n=>n instanceof wt?new wt(Math.round(n.value/100)*100,n.params):Math.round(n/100)*100,js=n=>Array.isArray(n)?n.map(vo):vo(n),iu=(n,t)=>{let e=n;return t.version>=2&&(n instanceof wt&&typeof n.value=="string"?e=new wt([n]):typeof n=="string"&&(e=[n])),sr(e,t)},ru={br:er,d:er,bl:js,dl:js,mtp:js,nor:iu,rtp:js,tb:er},os=2,yo="bc",nu="ps",Eo="pr",au="e",To="t",ou="c",So="b",ir="rr",Ao="ce",qs={BITRATE_CHANGE:yo,ERROR:au,RESPONSE_RECEIVED:ir,CUSTOM_EVENT:Ao},Io=new Map([[nu,"sta"],[Eo,"pr"],[ou,"cid"],[So,"bg"],[yo,"br"]]),rr="event",nr="request",Lo=["cen","e","h","ts"],Ro=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],lu=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function ar(n){return lu.test(n)}const hu=new Set(Ro);function bo(n){return hu.has(n)||ar(n)}const Do=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],du=new Set(Do);function ko(n){return du.has(n)}const cu=new Set(Lo);function uu(n){return bo(n)||ko(n)||cu.has(n)}const fu=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),Xs=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],gu=new Set(Xs);function mu(n){return gu.has(n)||ar(n)}const pu=new Set(["ot","sf","st","e","sta"]);function vu(n){return pu.has(n)}function yu(n){return typeof n=="number"?$(n):n!=null&&n!==""&&n!==!1}const Eu={[rr]:uu,[nr]:bo};function Po(n,t){if(Array.isArray(n)){let e;return t&&(e=n.find(s=>{var i;return((i=s.params)==null?void 0:i.ot)===t})),e||(e=n[0]),Po(e)}return n instanceof wt?n.value:n}function Tu(n){const t={};for(const[s,i]of Object.entries(n)){if(i==null){t[s]=i;continue}if(s==="nor"){const r=(Array.isArray(i)?i:[i])[0];if(r instanceof wt){var e;t.nor=r.value,(e=r.params)!=null&&e.r&&(t.nrr=r.params.r)}else t.nor=r}else fu.has(s)?t[s]=Po(i,n.ot):t[s]=i}return t}function _o(n,t={}){const e={};if(n==null||typeof n!="object")return e;const s=t.version||n.v||os,i=t.reportingMode||nr,r=s===1?Tu(n):n,a=s===1?mu:Eu[i];let o=Object.keys(r).filter(a);r.e&&r.e!==ir&&(o=o.filter(f=>!ko(f)));const l=t.filter;typeof l=="function"&&(o=o.filter(l));const h=i===rr;if(h){const f=r.e;!o.includes("e")&&f!=null&&o.push("e"),o.includes("ts")||o.push("ts"),!o.includes("cen")&&r.cen!=null&&f===Ao&&o.push("cen");const g=f?Io.get(f):void 0;g&&r[g]!=null&&!o.includes(g)&&o.push(g)}if(o.length===0)return e;s>1&&!o.includes("v")&&o.push("v");const d={version:s,reportingMode:i,baseUrl:t.baseUrl};o.sort();for(const f of o){var c,u;let g=r[f];const p=(c=(u=t.formatters)==null?void 0:u[f])!=null?c:ru[f];if(typeof p=="function"&&(g=p(g,d)),f==="v"){if(s===1)continue;g=s}if(f==="pr"&&g===1&&!(h&&r.e===Eo))continue;h&&f==="ts"&&!$(g)&&(g=Date.now());const v=h&&g===!1&&f==="bg"&&r.e===So;!yu(g)&&!v||(vu(f)&&typeof g=="string"&&(g=new co(g)),e[f]=g)}return e}const de="CMCD-Object",Ot="CMCD-Request",xe="CMCD-Session",Ht="CMCD-Status",Su={REQUEST:Ot},Au={ab:de,br:de,d:de,lab:de,lb:de,ot:de,tab:de,tb:de,tpb:de,bl:Ot,cs:Ot,dfa:Ot,dl:Ot,ltc:Ot,mtp:Ot,nor:Ot,nrr:Ot,pb:Ot,sn:Ot,sta:Ot,su:Ot,tbl:Ot,cid:xe,msd:xe,sf:xe,sid:xe,st:xe,v:xe,bg:Ht,bs:Ht,bsa:Ht,bsd:Ht,bsda:Ht,cdn:Ht,ec:Ht,nr:Ht,pr:Ht,pt:Ht,rtp:Ht};function Iu(n){return Object.keys(n).reduce((t,e)=>{var s;return(s=n[e])==null||s.forEach(i=>t[i]=e),t},{})}function Lu(n,t){const e={};if(!n)return e;const s=Object.keys(n),i=t?Iu(t):{};for(const a of s){var r;const o=Au[a]||i[a]||Su.REQUEST,l=(r=e[o])!=null?r:e[o]={};l[a]=n[a]}return e}function Ru(n,t){const e={},s=Lu(n,t);for(const[i,r]of Object.entries(s)){const a=mo(r,{whitespace:!1});a&&(e[i]=a)}return e}const Co="CMCD";function wo(n){return mo(n,{whitespace:!1})}function bu(n,t={}){return n?wo(_o(n,t)):""}const Du=30,or=[...Xs,...Ro,...Do,...Lo].filter((n,t,e)=>e.indexOf(n)===t),ku="application/cmcd",Pu=1,Pt={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Yt={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},lr="query",Oo="headers";function Mo(n,t,e){var s;const i=new Set((s=t.enabledKeys)!=null?s:[]);return{version:t.version||os,reportingMode:n,filter:r=>i.has(r),baseUrl:e}}function _u(n,t){if(n===t)return!0;if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++){const s=n[e],i=t[e];if(s===i)continue;if(typeof s=="number"||typeof i=="number"||s.value!==i.value)return!1;const r=s.params,a=i.params,o=r&&Object.keys(r)[0],l=a&&Object.keys(a)[0];if(o!==l||o!==void 0&&l!==void 0&&r&&a&&r[o]!==a[l])return!1}return!0}const Cu=Object.is,wu=n=>n,xo=Array.from(Io,([n,t])=>t==="br"?{event:n,field:t,equal:(e,s)=>e===void 0||s===void 0?e===s:_u(e,s),snapshot:e=>e.slice()}:{event:n,field:t,equal:Cu,snapshot:wu}),Ou=new Map(xo.map(n=>[n.event,n]));function Mu(n){const{url:t}=n,e=fs(n,tu);return fetch(t,e)}function xu(n){const{version:t=os,eventTargets:e=[],sid:s=Xr(),transmissionMode:i=lr}=n,r=fs(n,eu);return W(W({},r),{},{version:t,transmissionMode:i,sid:s,eventTargets:e.reduce((a,o)=>{var l,h,d;return o!=null&&o.url&&(l=o.events)!=null&&l.length&&a.push({version:o.version||os,enabledKeys:((h=o.enabledKeys)==null?void 0:h.slice())||[],url:o.url,events:o.events.slice(),interval:(d=o.interval)!=null?d:Du,batchSize:o.batchSize||1}),a},[])})}var Fu=class{constructor(n,t=Mu){var e;this.timeOrigin=performance.timeOrigin||((e=performance.timing)==null?void 0:e.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=xu(n),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=t;for(const s of this.config.eventTargets)this.eventTargets.set(s,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((n,t)=>{if(this.disarmInterval(n),t.interval===0||!t.events.includes(To))return;const e=()=>{this.recordTargetEvent(n,t,To),this.processEventTargets()};n.intervalId=setInterval(e,t.interval*1e3),e()})}stop(n=!1){n&&this.flush(),this.eventTargets.forEach(t=>{this.disarmInterval(t)})}flush(){this.processEventTargets(!0)}update(n){n.sid&&n.sid!==this.data.sid&&this.resetSession(),n.msd&&!isNaN(n.msd)&&(this.msd=n.msd),this.data=W(W(W({},this.data),n),{},{msd:void 0});for(const t of xo)t.field in n&&!t.equal(this.data[t.field],this.lastEmitted[t.field])&&this.recordEvent(t.event)}recordEvent(n,t={}){const e=Ou.get(n);if(e){const s=e.field,i=t[s];i!==void 0&&ht(this.data,{[s]:i});const r=this.data[s];if(r===void 0||e.equal(r,this.lastEmitted[s]))return;ht(this.lastEmitted,{[s]:e.snapshot(r)})}this.eventTargets.forEach((s,i)=>{this.recordTargetEvent(s,i,n,t)}),this.processEventTargets()}recordTargetEvent(n,t,e,s={}){var i;if(!t.events.includes(e))return;const r=W(W(W({},this.data),s),{},{e,ts:(i=s.ts)!=null?i:Date.now(),sn:n.sn++});!isNaN(this.msd)&&!n.msdSent&&(r.msd=this.msd,n.msdSent=!0),n.queue.push(r)}recordResponseReceived(n,t={}){var e,s,i;const{request:r}=n,a=(e=t.url)!=null?e:r?.url;if(!a)return;const o=new URL(a);o.searchParams.delete(Co);const l={url:o.toString(),rc:n.status},h=n.resourceTiming;h&&(h.startTime!=null&&(l.ts=Math.round(this.timeOrigin+h.startTime),h.responseStart!=null&&(l.ttfb=Math.round(h.responseStart-h.startTime))),h.duration!=null&&(l.ttlb=Math.round(h.duration)));const d=(s=(i=r.customData)==null?void 0:i.cmcd)!=null?s:{};this.recordEvent(ir,W(W(W({},d),l),t))}applyRequestReport(n){var t;return(t=this.createRequestReport(n))!=null?t:n}isRequestReportingEnabled(){var n;return!!((n=this.config.enabledKeys)!=null&&n.length)}createRequestReport(n,t){var e;const{customData:s={},headers:i={}}=n,r=fs(n,su),a=W(W({},r),{},{headers:W({},i),customData:W(W({},s),{},{cmcd:{}})});if(!((e=this.config.enabledKeys)!=null&&e.length)||!a.url)return a;const o=new URL(a.url),l=W(W(W({},this.data),t),{},{sn:this.requestTarget.sn++}),h=Mo(nr,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(l.msd=this.msd,this.requestTarget.msdSent=!0);const d=a.customData.cmcd=_o(l,h);switch(this.config.transmissionMode){case lr:const c=wo(d);c&&(o.searchParams.set(Co,c),a.url=o.toString());break;case Oo:ht(a.headers,Ru(d,h.customHeaderMap));break}return a}processEventTargets(n=!1){let t=!1;this.eventTargets.forEach((e,s)=>{const{queue:i}=e;if(!i.length||i.length<s.batchSize&&!n)return;const r=n?i.length:s.batchSize,a=i.splice(0,r);this.sendEventReport(s,a).catch(()=>{e.queue.unshift(...a)}),t||(t=i.length>0)}),t&&this.processEventTargets()}async sendEventReport(n,t){const e=Mo(rr,n),{status:s}=await this.requester({url:n.url,method:"POST",headers:{"Content-Type":ku},body:t.map(i=>bu(i,e)).join(`
28
+ `)+`
29
+ `});if(s===410)this.disposeEventTarget(n);else if(s===429||s>499&&s<600)throw new Error(`Event report failed with status ${s}`)}disarmInterval(n){clearInterval(n.intervalId),n.intervalId=void 0}disposeEventTarget(n){const t=this.eventTargets.get(n);t&&(this.disarmInterval(t),this.eventTargets.delete(n))}resetSession(){this.eventTargets.forEach(n=>n.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};const Nu={HLS:"h"},hr={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function $u(n,t){return new wt(n,t)}new Set(Xs),new Set(or);const Uu=["includeKeys"];function Fo(n){return Object.keys(n).every(ar)}class No{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(Yt.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(Yt.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Yt.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Yt.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Yt.SEEKING)},this.onSeeked=()=>{var i;this.initialized&&(i=this.media)!=null&&i.paused&&this.setPlayerState(Yt.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=i=>{try{this.apply(i,{ot:Pt.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:o,part:l}=i,h=this.hls.levels[o.level],d=this.getObjectType(o,h),c={d:(l||o).duration*1e3,ot:d};if(d===Pt.VIDEO||d===Pt.AUDIO||d===Pt.MUXED||d==null&&(o.type==="main"||o.type==="audio")){var r;const f=h.bitrate/1e3;c.br=[f];const{cmcd:g}=this.config,p=(r=g?.rtpSafetyFactor)!=null?r:5;if(c.rtp=Math.round(f*p/100)*100,d===Pt.MUXED||d==null&&o.type==="main"){const y=this.getTopBandwidth()/1e3;$(y)&&(c.tb=[y]);const T=this.getLowestBandwidth()/1e3;$(T)&&(c.lb=[T])}const v=this.getBufferLength(o);if($(v)){var a;c.bl=[v];const y=((a=this.media)==null?void 0:a.playbackRate)||1;c.dl=Math.round(v/y/100)*100}this.playheadLevel&&(c.pb=[this.playheadLevel.bitrate/1e3]);const E=this.hls.maxAutoLevel;if(E>=0){const y=this.hls.levels[E];y&&(c.tpb=[y.bitrate/1e3])}}const u=l?this.getNextPart(l):this.getNextFrag(o);u!=null&&u.url&&u.url!==o.url&&(u.byteRange.length>0?c.nor=[$u(u.url,{r:`${u.byteRange[0]}-${u.byteRange[1]}`})]:c.nor=[u.url]),this.apply(i,c)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},this.recordFragmentResponse=(i,r,a)=>{var o;const{cmcd:l}=this.config,h=l==null||(o=l.eventTargets)==null?void 0:o.some(d=>{var c;return(c=d.events)==null?void 0:c.includes(qs.RESPONSE_RECEIVED)});if(!(!this.reporter||!(a.loading.first>0)||!h))try{this.reporter.recordResponseReceived({request:{url:i},status:r.code,resourceTiming:{startTime:a.loading.start,responseStart:a.loading.first,duration:a.loading.end-a.loading.start,encodedBodySize:a.total}})}catch(d){this.hls.logger.warn("Could not record fragment response CMCD data.",d)}},this.hls=t;const e=this.config=t.config,{cmcd:s}=e;s!=null&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var t,e;const{cmcd:s}=this.config;if(s==null)return;const i=s.version||Pu;if(this.reporter=new Fu({sid:s.sessionId||this.hls.sessionId,cid:s.contentId,version:i,transmissionMode:s.useHeaders===!0?Oo:lr,enabledKeys:(t=s.includeKeys)!=null?t:[...i>=os?or:Xs],eventTargets:((e=s.eventTargets)!=null?e:[]).map(r=>{let{includeKeys:a}=r,o=fs(r,Uu);return W(W({},o),{},{enabledKeys:a??or})})},s.loader),this.reporter.update({sf:Nu.HLS,sta:this.playerState}),s.reporterCallback){const r=this.reporter,a={updateCustomData:o=>{Fo(o)&&r.update(o)},recordCustomEvent:(o,l={})=>{Fo(l)&&r.recordEvent(qs.CUSTOM_EVENT,W({cen:o},l))}};s.reporterCallback(a)}this.reporter.start()}registerListeners(){const t=this.hls;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(m.MEDIA_DETACHED,this.onMediaDetached,this),t.on(m.MEDIA_ENDED,this.onMediaEnded,this),t.on(m.ERROR,this.onError,this),t.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(m.LEVEL_SWITCHED,this.onLevelSwitched,this),t.on(m.BUFFER_APPENDED,this.onBufferInfoChange,this),t.on(m.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const t=this.hls;t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(m.MEDIA_DETACHED,this.onMediaDetached,this),t.off(m.MEDIA_ENDED,this.onMediaEnded,this),t.off(m.ERROR,this.onError,this),t.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(m.LEVEL_SWITCHED,this.onLevelSwitched,this),t.off(m.BUFFER_APPENDED,this.onBufferInfoChange,this),t.off(m.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(t,e){const s=this.media=e.media;this.setPlayerState(this.media.autoplay?Yt.STARTING:Yt.PRELOADING),lt(s,"waiting",this.onWaiting),lt(s,"play",this.onPlay),lt(s,"playing",this.onPlaying),lt(s,"pause",this.onPause),lt(s,"seeking",this.onSeeking),lt(s,"seeked",this.onSeeked),lt(s,"ratechange",this.onRateChange)}onMediaDetached(){const t=this.media;t&&(ot(t,"waiting",this.onWaiting),ot(t,"play",this.onPlay),ot(t,"playing",this.onPlaying),ot(t,"pause",this.onPause),ot(t,"seeking",this.onSeeking),ot(t,"seeked",this.onSeeked),ot(t,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(t,e){this.setPlayerState(Yt.ENDED)}onManifestLoading(t,e){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Yt.PRELOADING)}onError(t,e){e.fatal&&(this.setPlayerState(Yt.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(qs.ERROR,{ec:[e.details]}))}onLevelSwitching(t,e){var s;if(!this.reporter)return;const i={br:[e.bitrate/1e3]},r=(s=e.details)==null?void 0:s.fragments[0];r&&(i.ot=this.getObjectType(r,e)),this.reporter.recordEvent(qs.BITRATE_CHANGE,i)}onLevelSwitched(t,e){const s=this.hls.levels[e.level];s&&(this.playheadLevel=s)}setPlayerState(t){this.playerState=t,this.reporter&&this.reporter.update({sta:t})}getStreamType(){const t=this.hls.latestLevelDetails;if(t)return t.live?t.partList&&t.canBlockReload?hr.LOW_LATENCY:hr.LIVE:hr.VOD}apply(t,e={}){var s;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(s=this.media)==null?void 0:s.playbackRate,st:this.getStreamType()});const i=e.ot===Pt.INIT||e.ot===Pt.VIDEO||e.ot===Pt.MUXED;this.starved&&i&&(e.bs=!0,e.su=!0,this.starved=!1),e.su==null&&(e.su=this.buffering);const r=this.reporter.createRequestReport({url:t.url,headers:t.headers},e);t.url=r.url,t.headers=r.headers}getNextFrag(t){var e;const s=(e=this.hls.levels[t.level])==null?void 0:e.details;if(s){const i=t.sn-s.startSN;return s.fragments[i+1]}}getNextPart(t){var e;const{index:s,fragment:i}=t,r=(e=this.hls.levels[i.level])==null||(e=e.details)==null?void 0:e.partList;if(r){const{sn:a}=i;for(let o=r.length-1;o>=0;o--){const l=r[o];if(l.index===s&&l.fragment.sn===a)return r[o+1]}}}getObjectType(t,e){const{type:s}=t;if(s==="subtitle")return Pt.TIMED_TEXT;if(t.sn==="initSegment")return Pt.INIT;if(s==="audio")return Pt.AUDIO;if(s==="main"){if(t.hasStreams){const i=t.elementaryStreams;if(i.audiovideo)return Pt.MUXED;if(i.video)return Pt.VIDEO;if(i.audio)return Pt.AUDIO}if(e){const{audioCodec:i,videoCodec:r}=e;if(!this.hls.audioTracks.length){if(i&&r)return Pt.MUXED;if(i)return Pt.AUDIO}if(r)return Pt.VIDEO}}}getTopBandwidth(){let t=0;const e=this.hls,s=e.maxAutoLevel,i=s>-1?s+1:e.levels.length;return e.levels.slice(0,i).forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getLowestBandwidth(){let t=1/0;const e=this.hls,s=e.maxAutoLevel,i=s>-1?s+1:e.levels.length;return e.levels.slice(0,i).forEach(r=>{r.bitrate<t&&(t=r.bitrate)}),$(t)?t:NaN}getBufferLength(t){if(!this.media)return NaN;const e=t.type==="audio"?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return e?e.len*1e3:NaN}getEventBufferLength(){if(!this.media)return NaN;const t=this.hls.mainForwardBufferInfo,e=this.hls.audioForwardBufferInfo;if(t&&e)return Math.min(t.len,e.len)*1e3;const s=t||e;return s?s.len*1e3:NaN}onBufferInfoChange(t,e){if(!this.reporter)return;const s=this.getEventBufferLength();$(s)&&this.reporter.update({bl:[s]})}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,s=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new s(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,r,a){e(i),this.loader.load(i,r,a)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=this.recordFragmentResponse,i=t||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new i(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){e(r);const{onSuccess:l}=o;this.loader.load(r,a,W(W({},o),{},{onSuccess:(h,d,c,u)=>{l(h,d,c,u),s(r.url,h,d)}}))}}}}const Bu=3e5;class $o extends xt{constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(t.indexOf(e.pathwayId)===-1&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=this.timeToLoad*1e3-(performance.now()-this.updated);if(t>0){this.scheduleRefresh(this.uri,t);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter(s=>s!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:s}=e;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:s}=e;if(s?.action===Dt.SendAlternateToPenaltyBox&&s.flags&bt.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,a=this.pathwayId;if(e.context){const{groupId:o,pathwayId:l,type:h}=e.context;o&&i?a=this.getPathwayForGroupId(o,h,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==a,!s.resolved&&(e.details!==R.BUFFER_APPEND_ERROR||e.fatal)&&this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${ft(r)} penalized: ${ft(this.penalizedPathways)}`))}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(e.length===0){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),e=this.getLevelsForPathway(s),this.pathwayId=s}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return this.levels===null?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){this._pathwayPriority=t;let e;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>Bu&&delete s[r]});for(let r=0;r<t.length;r++){const a=t[r];if(a in s)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(e=this.getLevelsForPathway(a),e.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Da(e),this.hls.trigger(m.LEVELS_UPDATED,{levels:e});const h=this.hls.levels[o];l&&h&&this.levels&&(h.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&h.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${h.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(t,e,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(e===st.AUDIO_TRACK&&i[r].hasAudioGroup(t)||e===st.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(t))return i[r].pathwayId;return s}clonePathways(t){const e=this.levels;if(!e)return;const s={},i={};t.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(e.some(d=>d.pathwayId===a))return;const h=this.getLevelsForPathway(o).map(d=>{const c=new vt(d.attrs);c["PATHWAY-ID"]=a;const u=c.AUDIO&&`${c.AUDIO}_clone_${a}`,f=c.SUBTITLES&&`${c.SUBTITLES}_clone_${a}`;u&&(s[c.AUDIO]=u,c.AUDIO=u),f&&(i[c.SUBTITLES]=f,c.SUBTITLES=f);const g=Bo(d.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new Pe({attrs:c,audioCodec:d.audioCodec,bitrate:d.bitrate,height:d.height,name:d.name,url:g,videoCodec:d.videoCodec,width:d.width});if(d.audioGroups)for(let v=1;v<d.audioGroups.length;v++)p.addGroupId("audio",`${d.audioGroups[v]}_clone_${a}`);if(d.subtitleGroups)for(let v=1;v<d.subtitleGroups.length;v++)p.addGroupId("text",`${d.subtitleGroups[v]}_clone_${a}`);return p});e.push(...h),Uo(this.audioTracks,s,l,a),Uo(this.subtitleTracks,i,l,a)})}loadSteeringManifest(t){const e=this.hls.config,s=e.loader;this.loader&&this.loader.destroy(),this.loader=new s(e);let i;try{i=new self.URL(t)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${t}`);return}if(i.protocol!=="data:"){const d=(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate)|0;ge(i,"_HLS_pathway",this.pathwayId),ge(i,"_HLS_throughput",""+d)}const r={type:st.STEERING_MANIFEST,responseType:"json",url:i.href},a=e.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},h={onSuccess:(d,c,u,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=d.data;if(g?.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":v,"PATHWAY-PRIORITY":E}=g;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||u.url),v&&this.clonePathways(v);const y={steeringManifest:g,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,y),E&&this.updatePathwayPriority(E)},onError:(d,c,u,f)=>{if(this.log(`Error loading steering manifest: ${d.code} ${d.text} (${c.url})`),this.stopLoad(),d.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let g=this.timeToLoad*1e3;if(d.code===429){const p=this.loader;if(typeof p?.getResponseHeader=="function"){const v=p.getResponseHeader("Retry-After");v&&(g=parseFloat(v)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,g)},onTimeout:(d,c,u)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,l,h)}scheduleRefresh(t,e=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},e)}}function Uo(n,t,e,s){n&&Object.keys(t).forEach(i=>{const r=n.filter(a=>a.groupId===i).map(a=>{const o=ht({},a);return o.details=void 0,o.attrs=new vt(o.attrs),o.url=o.attrs.URI=Bo(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",e),o.groupId=o.attrs["GROUP-ID"]=t[i],o.attrs["PATHWAY-ID"]=s,o});n.push(...r)})}function Bo(n,t,e,s){if(t){const{[e]:o}=s;if(o){const l=o[t];if(l)return l}}const{HOST:i,PARAMS:r}=s,a=new self.URL(n);return i&&(a.hostname=i),r&&Object.keys(r).sort().forEach(o=>{o&&ge(a,o,r[o])}),a.href}class Gu{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new Vi,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(t){this.error=t,this.emitter.eventNames().length&&this.emitter.emit("error",t)}get hasListeners(){return this.emitter.eventNames().length>0}get resolved(){return this.ok}resolve(){this.ok=!0,this.emitter.emit("resolved")}get useable(){return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((t,e)=>{this.emitter.on("error",e),this.emitter.on("resolved",t)})}reset(){this.emitter.removeAllListeners();const t=this.licenseXhr;t&&(t.readyState!==XMLHttpRequest.DONE&&t.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}}class Wt extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}class Ne extends xt{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysChain=Ne.CDMCleanupPromise||Promise.resolve(),this.onMediaEncrypted=e=>{const{initDataType:s,initData:i}=e,r=`"${e.type}" event: init data type: "${s}"`;if(this.log(r),i!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Je(this.config));const o=a.map(Ni).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o;const l=Ms(a),h=this.activeLevelKeys();if(l===gt.FAIRPLAY&&s==="sinf")try{const g=Vt(new Uint8Array(i)),p=pi(JSON.parse(g).sinf),v=hn(p);if(!v)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(v.subarray(8,24))}catch(g){this.warn(`${r} Failed to parse sinf: ${g}`);return}else if(l===gt.PLAYREADY)o=Ui(new Uint8Array(i));else if(l===gt.WIDEVINE){const g=gn(i).filter(p=>p.systemId===la.WIDEVINE);if(g.length){var d;const p=g[0];o=(d=p.kids)!=null&&d.length?p.kids[0]:null}}let c;if(o){const g=It(o);for(let p=0;p<h.length;p++){const v=h[p];if(v.keyId&&(ws(o,v.keyId)||v.uri.replace(/-/g,"").indexOf(g)!==-1)){v.pssh||(v.scheme=s,v.pssh=new Uint8Array(i),v.keyId=o,ae.setKeyIdForUri(v.uri,o)),c=this.getSessionForKey(v,"encrypted-event-key-match");break}}}if(!c){if(h.length){var u,f;return(u=h[0]).scheme||(u.scheme=s),(f=h[0]).pssh||(f.pssh=new Uint8Array(i)),this.getSessionForKey(h[0],"encrypted-event-no-match")}if(o)throw new Error(`Key ID ${It(o)} not encountered in playlist`);this.log(`Ignoring "${e.type}" event - could not determine keyId`)}return c}).catch(a=>this.handleError(a))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:t}=this;t&&(t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHED,this.onMediaDetached,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHED,this.onMediaDetached,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(m.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(t){if(!this.hls)return Promise.reject(new Error("destroyed"));const e=this.hls.levels,s=(a,o,l)=>!!a&&l.indexOf(a)===o,i=e.map(a=>a.audioCodec).filter(s),r=e.map(a=>a.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const l=h=>{const d=h.shift();this.getMediaKeysPromise(d,i,r).then(c=>a({keySystem:d,mediaKeys:c})).catch(c=>{h.length?l(h):c instanceof Wt?o(c):o(new Wt({type:Y.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:c,fatal:!0},c.message))})};l(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return $i===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(t,e)}getMediaKeysPromise(t,e,s){var i;const r=vd(t,e,s,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[t],o=(i=a)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${t}" key-system access with config: ${ft(r)}`),o=this.requestMediaKeySystemAccess(t,r);const l=a=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(h=>{this.log(`Failed to obtain access to key-system "${t}": ${h}`)}),o.then(h=>{this.throwIfDestroyed(),this.log(`Access for key-system "${h.keySystem}" obtained`);const d=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const c=l.mediaKeys=h.createMediaKeys().then(u=>(this.log(`Media-keys created for "${t}"`),l.createdMediaKeys=u,d.then(f=>f?this.setMediaKeysServerCertificate(u,t,f):u)));return c.catch(u=>{this.error(`Failed to create media-keys for "${t}"}: ${u}`)}),c})}return o.then(()=>a.mediaKeys)}getMediaKeySessionContext(t,e,s,i){const{mediaKeySessions:r}=this,a=` key-session "${t}" keyId: ${It(s.keyId||[])} keyUri: ${s.uri} for "${i}"`;for(let h=0;h<r.length;h++){const d=r[h];if(!d.initialized&&d.createdFor.levelKey.uri===s.uri)return this.log(`Reusing${a}`),d}this.log(`Creating${a}`);const o=e.createSession(),l={keySystem:t,mediaKeys:e,mediaKeysSession:o,keyRequests:{},keyStatuses:{},createdFor:{levelKey:s,reason:i},initialized:!1};return r.push(l),l}resetMediaKeys(){var t;const e=(t=this.mediaKeySessions[0])==null?void 0:t.keySystem,s=this.keySystemAccessPromises[e];s&&(this.log("reset mediaKeys"),this.mediaKeys=null,delete s.createdMediaKeys,delete s.mediaKeys,delete this.keySystemAccessPromises[e])}updateKeySession(t,e,s){const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${It(e.keyId||[])}
30
+ } (data length: ${s.byteLength})`),i.update(s)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:!!this.keySystemAccessPromises[t].createdMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Ni(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:e,mediaKeys:s})=>this.attemptSetMediaKeys(e,s))}selectKeySystem(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:e})=>{const s=Ni(e);if(!s)throw new Error(`Unable to find format for key-system "${e}"`);return s})}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){const e=Je(this.config),s=t.map(Ms).filter(i=>!!i&&e.indexOf(i)!==-1);return this.selectKeySystem(s)}loadClear(t,e,s){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(e.length)for(let i=0,r=e.length;i<r;i++){const a=e[i];if(t.cc<=a.cc&&(!Et(t)||!Et(a)||t.sn<a.sn)||!s&&i==r-1)return this.selectKeySystemFormat(a).then(o=>{if(!this.hls)return;a.setKeyFormat(o);const l=Ms(o);if(l)return this.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){const i=Je(this.config);if(i.length)return this.getKeySystemAccess(i)}}return null}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let s=0;s<e.length;s++){const i=dr(t,e[s]);if(i)return i}}loadKey(t){const e=t.decryptdata,s=this.getKeyStatus(e);if(s==="internal-error"){const o=Go(s,e);return o.data.frag=t,this.error(`${o.message} (${It(e.keyId||[])})`),Promise.reject(o)}const i=t.type,r=this.activeKeys,a=r[i];a&&!e.matches(a.decryptdata)&&(r.previous||(r.previous=[]),r.previous.push(a),delete r[i]),r[i]||(r[i]=t);for(let o=this.mediaKeySessions.length;o--;){const l=this.mediaKeySessions[o];if(e.keyId&&l.keyStatuses[It(e.keyId)]==="expired")return this.renewKeySession(e,l)}return this.updateUsablePromise(e,"playlist-key",t)}renewKeySession(t,e){return this.resetMediaKeys(),this.removeSession(e).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(t,"expired")))}updateUsablePromise(t,e,s){const i=this.getSessionForKey(t,e);return i.catch(r=>this.handleError(r,s)),i.then(r=>t)}getSessionForKey(t,e){const s=this.findContextForKey(t);if(s!==void 0)return Promise.resolve(s);const i=t.uri,r=this.sessionSetupByUri[i];let a;r===void 0?a=this.resolveSessionForKey(t,e):a=r.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(t,e))),this.sessionSetupByUri[i]=a;const o=()=>{this.sessionSetupByUri[i]===a&&delete this.sessionSetupByUri[i]};return a.then(o,o),a}findContextForKey(t){const{mediaKeySessions:e}=this;for(let s=e.length;s--;){const i=e[s];if(dr(t,i))return i}}resolveSessionForKey(t,e){return this.getKeySystemForKeyPromise(t).then(({keySystem:s,mediaKeys:i})=>{this.throwIfDestroyed();for(let r=this.mediaKeySessions.length;r--;){const a=this.mediaKeySessions[r];if(dr(t,a))return a;const o=this.getUsableKeyPromise(a,t,e);if(o)return o}return this.attemptSetMediaKeys(s,i).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(s,i,t,e))).then(r=>{this.throwIfDestroyed();const a=t.scheme||"cenc",o=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(r,t,a,o,e)})})}getUsableKeyPromise(t,e,s){const i=t.keyRequests[e.uri];if(i)return this.log(`Waiting for usable key (${s} keyId: ${Hu(e)} format: "${e.keyFormat}" URI: ${e.uri})`),i.useable.then(()=>t)}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof Wt){e&&(t.data.frag=e);const s=t.data.decryptdata;this.error(`${t.message}${s?` (${It(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,t.data)}else this.error(t.message),this.hls.trigger(m.ERROR,{type:Y.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0,reason:`${t.name}: ${t.message}`})}getKeySystemForKeyPromise(t){const e=Ms(t.keyFormat),s=e?[e]:Je(this.config);return this.attemptKeySystemAccess(s)}getKeySystemSelectionPromise(t){if(t.length||(t=Je(this.config)),t.length===0)throw new Wt({type:Y.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ft({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}activeLevelKeys(){const t=this.activeKeys,e=(t.previous||[]).map(s=>s.decryptdata);return t.audio&&e.unshift(t.audio.decryptdata),t.main&&e.unshift(t.main.decryptdata),e}queueSetMediaKeys(t){const e=this.setMediaKeysChain.then(t);return this.setMediaKeysChain=e.catch(s=>{this.log(`setMediaKeys failed: ${s}`)}),e}attemptSetMediaKeys(t,e){return this.mediaKeys===e?Promise.resolve():(this.log(`Setting media-keys for "${t}"`),this.mediaKeys=e,this.queueSetMediaKeys(()=>this.media?this.media.setMediaKeys(e):new Promise((s,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(s).catch(i)}})).then(()=>{this.log(`Media-keys set for "${t}"`)},s=>{throw this.mediaKeys===e&&(this.mediaKeys=null),s}))}filterInitData(t,e,s,i,r){var a;const o=(a=this.config.drmSystems)==null||(a=a[t.keySystem])==null?void 0:a.generateRequest;if(o)try{const h=o.call(this.hls,s,i,ht({},t,{decryptdata:e,reason:r}),r);if(!h)throw new Error("Invalid response from configured generateRequest filter");e.scheme=h.initDataType?h.initDataType:"cenc";const d=h.initData?h.initData:null;return e.pssh=d?new Uint8Array(d):null,h}catch(h){var l;if(this.warn(h.message),(l=this.hls)!=null&&l.config.debug)throw h}return{initDataType:s,initData:i}}generateRequestWithPreferredKeySession(t,e,s,i,r){const a=this.getUsableKeyPromise(t,e,r);if(a)return a;const o=this.filterInitData(t,e,s,i,r);if(o&&(i=o.initData?o.initData:null,s=o.initDataType),i===null)return r.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${r}"`)):(this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t));const l=e.uri,h=new Gu;t.keyRequests[l]=h;const d=c=>{const u=t.mediaKeysSession;if(!u){const p=new Error("invalid state");h.errored=p;return}const{messageType:f,message:g}=c;h.status=f,this.log(`"${f}" message event for session "${u.sessionId}" message size: ${g.byteLength}`),f==="license-request"||f==="license-renewal"?this.renewLicense(t,e,g).catch(p=>{h.errored=p,h.hasListeners||this.handleError(p),this.removeSession(t)}):f==="license-release"?t.keySystem===gt.FAIRPLAY&&this.updateKeySession(t,e,Fi("acknowledged")).then(()=>this.removeSession(t)).catch(p=>this.handleError(p)):this.warn(`unhandled media key message type "${f}"`)};return h.onmessage=d,lt(t.mediaKeysSession,"message",d),this.generateRequest(t,e,s,i,r,!1)}generateRequest(t,e,s,i,r,a){if(a){const f=this.filterInitData(t,e,s,i,r);f&&(i=f.initData?f.initData:i,s=f.initDataType)}const o=e.uri,l=t.keyRequests[o],h=It(e.keyId||[]),d=f=>{let g;f.startsWith("usable")?l.resolve():f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?g=Go(f,e):f==="expired"?g=new Error(`key expired (keyId: ${h})`):f==="released"?g=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${h})`),g&&(l.errored=g,l.hasListeners||this.handleError(g))},c=f=>{if(!t.mediaKeysSession){const T=new Error("invalid state");l.errored=T;return}const g=t.keyStatuses=this.getKeyStatuses(t);if(!Object.keys(g).some(T=>g[T]!=="status-pending"))return;const p=this.activeLevelKeys();for(let T=0;T<p.length;T++){const S=It(p[T].keyId||[]);if(g[S]==="expired"){var v;this.log(`Expired key ${ft(g)} in key-session "${(v=t.mediaKeysSession)==null?void 0:v.sessionId}"`),this.renewKeySession(e,t).catch(A=>this.handleError(A));break}}let E=g[h];if(E)d(E);else{var y;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(y=t.keyStatusTimeouts)[h]||(y[h]=self.setTimeout(()=>{var T;if(!t.mediaKeysSession)return;const S=this.getKeyStatus(e);if(S&&S!=="status-pending"){var A;return this.log(`No status for keyId ${h} in key-session "${(A=t.mediaKeysSession)==null?void 0:A.sessionId}". Using session key-status ${S} from other session.`),d(S)}this.log(`key status for ${h} in key-session "${(T=t.mediaKeysSession)==null?void 0:T.sessionId}" timed out after 1000ms`),E="internal-error",d(E)},1e3)),this.log(`No status for keyId ${h} (${ft(g)}).`)}};l.onkeystatuseschange=c,lt(t.mediaKeysSession,"keystatuseschange",c);const u=l.useable;return this.log(`Generating key-session request for "${r}" keyId: ${h} URI: ${o} (init data type: ${s} length: ${i.byteLength})`),l.status="started",t.initialized=!0,t.mediaKeysSession.generateRequest(s,i).then(()=>{var f;l.status="generated",this.log(`Request generated for key-session "${(f=t.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${h} URI: ${o}`)}).catch(f=>{throw this.log(`mediaKeysSession.generateRequest failed: ${f}`),new Wt({type:Y.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:e,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>u).catch(f=>{var g;this.log(`mediaKeysSession.generateRequest failed: ${f}`);const p=(g=f.data)==null?void 0:g.details;return(p===R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||p===R.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(t.keyStatuses).some(v=>t.keyStatuses[v]==="usable")?(this.handleError(f),t):this.removeSession(t).then(()=>{throw f})}).then(()=>t)}getKeyStatuses(t){const e={},s=t.mediaKeysSession.sessionId;return t.mediaKeysSession.keyStatuses.forEach((i,r)=>{if(typeof r=="string"&&typeof i=="object"){const l=r;r=i,i=l}const a="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(t.keySystem===gt.PLAYREADY&&a.length===16){const l=It(a);e[l]=i,aa(a)}const o=It(a);this.log(`key status change "${i}" for keyStatuses keyId: ${o} key-session "${s}"`),e[o]=i}),e}fetchServerCertificate(t){const e=this.config,s=e.loader,i=new s(e),r=Vu(t,e);return r?(this.log(`Fetching server certificate for "${t}"`),new Promise((a,o)=>{const l={type:st.SERVER_CERTIFICATE,responseType:"arraybuffer",url:r},h=e.certLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(u,f,g,p)=>{a(u.data)},onError:(u,f,g,p)=>{o(new Wt({type:Y.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:W({url:l.url,data:void 0},u)},`"${t}" certificate request failed (${r}). Status: ${u.code} (${u.text})`))},onTimeout:(u,f,g)=>{o(new Wt({type:Y.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${r})`))},onAbort:(u,f,g)=>{o(new Error("aborted"))}};i.load(l,d,c)})):(this.log(`No Server Certificate in config.drmSystems["${t}"]`),Promise.resolve())}setMediaKeysServerCertificate(t,e,s){return new Promise((i,r)=>{t.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${e}"`),i(t)}).catch(a=>{r(new Wt({type:Y.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(t,e,s){return this.requestLicense(t,e,new Uint8Array(s)).then(i=>this.updateKeySession(t,e,new Uint8Array(i)).catch(r=>{throw new Wt({type:Y.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(t,e){const s=Vt(new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let d;for(let c=0,u=r.length;c<u;c++){var a,o;d=r[c];const f=(a=d.querySelector("name"))==null?void 0:a.textContent,g=(o=d.querySelector("value"))==null?void 0:o.textContent;f&&g&&t.setRequestHeader(f,g)}}const l=i.querySelector("Challenge"),h=l?.textContent;if(!h)throw new Error("Cannot find <Challenge> in key message");return Fi(atob(h))}setupLicenseXHR(t,e,s,i,r){const a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,t,e,W(W({},s),{},{decryptdata:i}),r))).catch(o=>{if(!s.mediaKeysSession)throw o;return t.open("POST",e,!0),a.call(this.hls,t,e,W(W({},s),{},{decryptdata:i}),r)}).then(o=>(t.readyState||t.open("POST",e,!0),{xhr:t,licenseChallenge:o||r})):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,e,s){return new Promise((i,r)=>{const a=Ku(t.keySystem,this.config);if(!a)return r(new Error(`no license server URL configured for key-system "${t.keySystem}"`));const o=t.keyRequests[e.uri];if(!o)return r(new Error("License emitter removed"));this.log(`Sending license request to URL: ${a}`);const l=this.config.keyLoadPolicy.default,h=new XMLHttpRequest;h.responseType="arraybuffer",h.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return r(new Error("invalid state"));if(h.readyState===4)if(h.status===200){o.requestErrors=[];let d=h.response;this.log(`License received ${d instanceof ArrayBuffer?d.byteLength:d}`);const c=this.config.licenseResponseCallback;if(c)try{d=c.call(this.hls,h,a,W(W({},t),{},{decryptdata:e}))}catch(u){this.error(u)}i(d)}else{const d=l.errorRetry,c=d?d.maxNumRetry:0;if(o.requestErrors.push({status:h.status,message:h.statusText}),o.requestErrors.length>c||h.status>=400&&h.status<500)r(new Wt({type:Y.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e,fatal:!0,networkDetails:h,response:{url:a,data:void 0,code:h.status,text:h.statusText}},`License Request XHR failed (${a}). Status: ${h.status} (${h.statusText})`));else{const u=c-o.requestErrors.length;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(t,e,s).then(i,r)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=h,this.setupLicenseXHR(h,a,t,e,s).then(({xhr:d,licenseChallenge:c})=>{t.keySystem==gt.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(d,c)),d.send(c)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,lt(s,"encrypted",this.onMediaEncrypted),lt(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const t=this.media;t&&(ot(t,"encrypted",this.onMediaEncrypted),ot(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(t=!1){this.keyFormatPromise=null,t||(this.keySystemAccessPromises={}),this.activeKeys={},this.sessionSetupByUri={};const e=this.mediaResolved;if(e&&e(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,i=t&&this.config.reuseKeySessions,r=i?[]:this.mediaKeySessions.slice();i||(this.mediaKeySessions=[],ae.clearKeyUriToKeyIdMap()),t||(this.mediaKeys=null);const a=r.length,o=s&&!t?this.queueSetMediaKeys(()=>s.setMediaKeys(null)).catch(l=>{this.log(`Could not clear media keys: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${l}`)})}):Promise.resolve();Ne.CDMCleanupPromise=Promise.all(r.map(l=>this.removeSession(l)).concat(o)).catch(l=>{this.log(`Could not close sessions and clear media keys: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${l}`)})}).then(()=>{a&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){var t;const e=(t=this.hls)==null||(t=t.media)==null?void 0:t.mediaKeys,s=!!e&&Object.keys(this.keySystemAccessPromises).some(i=>{var r;return i!==gt.FAIRPLAY&&((r=this.keySystemAccessPromises[i])==null?void 0:r.createdMediaKeys)===e});this._clear(s),this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(!(!e||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=e.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s),this.keyFormatPromise.catch(()=>{})}}removeSession(t){const{mediaKeysSession:e}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}"`),Object.keys(t.keyRequests).forEach(a=>{const o=t.keyRequests[a];o.onmessage&&e.removeEventListener("message",o.onmessage),o.onkeystatuseschange&&e.removeEventListener("keystatuseschange",o.onkeystatuseschange),o.reset(),t.keyRequests[a]=void 0}),t.mediaKeysSession=void 0;const s=this.mediaKeySessions.indexOf(t);s>-1&&this.mediaKeySessions.splice(s,1);const{keyStatusTimeouts:i}=t;i&&Object.keys(i).forEach(a=>self.clearTimeout(i[a]));const{drmSystemOptions:r}=this.config;return(Ed(r)?new Promise((a,o)=>{self.setTimeout(()=>o(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(a).catch(o)}):Promise.resolve()).catch(a=>{this.log(`Could not remove session: ${a}`),this.hls&&this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${a}`)})}).then(()=>e.close()).then(()=>e.closed).catch(a=>{this.log(`Could not close session: ${a}`),this.hls&&this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${a}`)})})}return Promise.resolve()}}Ne.CDMCleanupPromise=void 0;function Ku(n,t){const{drmSystems:e,widevineLicenseUrl:s}=t,i=e?.[n];if(i)return i.licenseUrl;if(n===gt.WIDEVINE&&s)return s}function Vu(n,t){const{drmSystems:e}=t,s=e?.[n];if(s)return s.serverCertificateUrl}function Hu(n){if(n.keyFormat===kt.FAIRPLAY)return n.uri;if(n.keyId===null)throw new Error("keyId is null");return It(n.keyId)}function dr(n,t){const e=n.keyId,s=t.mediaKeysSession;if(e&&s){const i=t.mediaKeysSession.keyStatuses;if(i.size)return i.has(e)?i.get(e):t.keyStatuses[It(e)]}}function Go(n,t){const e=n==="output-restricted",s=e?R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Wt({type:Y.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:t},e?"HDCP level output restricted":`key status changed to "${n}"`)}class Ko{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,s){const i=performance.now();if(e){if(this.lastTime){const r=i-this.lastTime,a=s-this.lastDroppedFrames,o=e-this.lastDecodedFrames,l=1e3*a/r,h=this.hls;if(h.trigger(m.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>h.config.fpsDroppedMonitoringThreshold*o){let d=h.currentLevel;h.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(h.autoLevelCapping===-1||h.autoLevelCapping>=d)&&(d=d-1,h.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:h.currentLevel}),h.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}var cr=(function(){if(Os!=null&&Os.VTTCue)return self.VTTCue;const n=["","lr","rl"],t=["start","middle","end","left","right"];function e(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const h=l.toLowerCase();return~o.indexOf(h)?h:!1}function s(o){return e(n,o)}function i(o){return e(t,o)}function r(o,...l){let h=1;for(;h<arguments.length;h++){const d=arguments[h];for(const c in d)o[c]=d[c]}return o}function a(o,l,h){const d=this,c={enumerable:!0};d.hasBeenReset=!1;let u="",f=!1,g=o,p=l,v=h,E=null,y="",T=!0,S="auto",A="start",L=50,I="middle",b=50,k="middle";Object.defineProperty(d,"id",r({},c,{get:function(){return u},set:function(D){u=""+D}})),Object.defineProperty(d,"pauseOnExit",r({},c,{get:function(){return f},set:function(D){f=!!D}})),Object.defineProperty(d,"startTime",r({},c,{get:function(){return g},set:function(D){if(typeof D!="number")throw new TypeError("Start time must be set to a number.");g=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"endTime",r({},c,{get:function(){return p},set:function(D){if(typeof D!="number")throw new TypeError("End time must be set to a number.");p=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"text",r({},c,{get:function(){return v},set:function(D){v=""+D,this.hasBeenReset=!0}})),Object.defineProperty(d,"region",r({},c,{get:function(){return E},set:function(D){E=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"vertical",r({},c,{get:function(){return y},set:function(D){const C=s(D);if(C===!1)throw new SyntaxError("An invalid or illegal string was specified.");y=C,this.hasBeenReset=!0}})),Object.defineProperty(d,"snapToLines",r({},c,{get:function(){return T},set:function(D){T=!!D,this.hasBeenReset=!0}})),Object.defineProperty(d,"line",r({},c,{get:function(){return S},set:function(D){if(typeof D!="number"&&D!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"lineAlign",r({},c,{get:function(){return A},set:function(D){const C=i(D);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),Object.defineProperty(d,"position",r({},c,{get:function(){return L},set:function(D){if(D<0||D>100)throw new Error("Position must be between 0 and 100.");L=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"positionAlign",r({},c,{get:function(){return I},set:function(D){const C=i(D);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");I=C,this.hasBeenReset=!0}})),Object.defineProperty(d,"size",r({},c,{get:function(){return b},set:function(D){if(D<0||D>100)throw new Error("Size must be between 0 and 100.");b=D,this.hasBeenReset=!0}})),Object.defineProperty(d,"align",r({},c,{get:function(){return k},set:function(D){const C=i(D);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");k=C,this.hasBeenReset=!0}})),d.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})();class Yu{decode(t,e){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Vo(n){function t(s,i,r,a){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(a||0)}const e=n.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return e?parseFloat(e[2])>59?t(e[2],e[3],0,e[4]):t(e[1],e[2],e[3],e[4]):null}class Wu{constructor(){this.values=Object.create(null)}set(t,e){!this.get(t)&&e!==""&&(this.values[t]=e)}get(t,e,s){return s?this.has(t)?this.values[t]:e[s]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,s){for(let i=0;i<s.length;++i)if(e===s[i]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const s=parseFloat(e);if(s>=0&&s<=100)return this.set(t,s),!0}return!1}}function Ho(n,t,e,s){const i=s?n.split(s):[n];for(const r in i){if(typeof i[r]!="string")continue;const a=i[r].split(e);if(a.length!==2)continue;const o=a[0],l=a[1];t(o,l)}}const ur=new cr(0,0,""),zs=ur.align==="middle"?"middle":"center";function ju(n,t,e){const s=n;function i(){const o=Vo(n);if(o===null)throw new Error("Malformed timestamp: "+s);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){const h=new Wu;Ho(o,function(u,f){let g;switch(u){case"region":for(let p=e.length-1;p>=0;p--)if(e[p].id===f){h.set(u,e[p].region);break}break;case"vertical":h.alt(u,f,["rl","lr"]);break;case"line":g=f.split(","),h.integer(u,g[0]),h.percent(u,g[0])&&h.set("snapToLines",!1),h.alt(u,g[0],["auto"]),g.length===2&&h.alt("lineAlign",g[1],["start",zs,"end"]);break;case"position":g=f.split(","),h.percent(u,g[0]),g.length===2&&h.alt("positionAlign",g[1],["start",zs,"end","line-left","line-right","auto"]);break;case"size":h.percent(u,f);break;case"align":h.alt(u,f,["start",zs,"end","left","right"]);break}},/:/,/\s/),l.region=h.get("region",null),l.vertical=h.get("vertical","");let d=h.get("line","auto");d==="auto"&&ur.line===-1&&(d=-1),l.line=d,l.lineAlign=h.get("lineAlign","start"),l.snapToLines=h.get("snapToLines",!0),l.size=h.get("size",100),l.align=h.get("align",zs);let c=h.get("position","auto");c==="auto"&&ur.position===50&&(c=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=c}function a(){n=n.replace(/^\s+/,"")}if(a(),t.startTime=i(),a(),n.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);n=n.slice(3),a(),t.endTime=i(),a(),r(n,t)}function Yo(n){return n.replace(/<br(?: \/)?>/gi,`
31
+ `)}class qu{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Yu,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));function s(){let r=e.buffer,a=0;for(r=Yo(r);a<r.length&&r[a]!=="\r"&&r[a]!==`
32
+ `;)++a;const o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===`
33
+ `&&++a,e.buffer=r.slice(a),o}function i(r){Ho(r,function(a,o){},/:/)}try{let r="";if(e.state==="INITIAL"){if(!/\r\n|\n/.test(e.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let a=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(a?a=!1:r=s(),e.state){case"HEADER":/:/.test(r)?i(r):r||(e.state="ID");continue;case"NOTE":r||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){e.state="NOTE";break}if(!r)continue;if(e.cue=new cr(0,0,""),e.state="CUE",r.indexOf("-->")===-1){e.cue.id=r;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{ju(r,e.cue,e.regionList)}catch{e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(a=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(e.cue===null)continue;e.cue.text&&(e.cue.text+=`
34
+ `),e.cue.text+=r}continue;case"BADCUE":r||(e.state="ID")}}}catch{e.state==="CUETEXT"&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state=e.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||t.state==="HEADER")&&(t.buffer+=`
35
+
36
+ `,t.parse()),t.state==="INITIAL"||t.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}function ls(n){let t=5381,e=n.length;for(;e;)t=t*33^n.charCodeAt(--e);return(t>>>0).toString()}const Xu=/\r\n|\n\r|\n|\r/g,Wo="Missing initPTS for VTT ",zu=function(n){let t=parseInt(n.slice(-3));const e=parseInt(n.slice(-6,-4)),s=parseInt(n.slice(-9,-7)),i=n.length>9?parseInt(n.substring(0,n.indexOf(":"))):0;if(!$(t)||!$(e)||!$(s)||!$(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${n}`);return t+=1e3*e,t+=60*1e3*s,t+=3600*1e3*i,t};function fr(n,t,e){return ls(n.toString())+ls(t.toString())+ls(e)}function Qu(n,t,e,s,i,r,a){const o=new qu,l=Ft(new Uint8Array(n)).trim().replace(Xu,`
37
+ `).split(`
38
+ `),h=[],d=t?Sc(t.baseTime,t.timescale):0;let c="00:00.000",u=0,f=0,g=!1,p,v=!0;o.oncue=function(E){const y=e[s];let T=e.ccOffset;const S=(u-d)/9e4;if(g){if(y!=null&&y.new&&(T=e.ccOffset=y.start),S){if(!t){p=new Error(Wo+"MPEGTS");return}T=S-e.presentationOffset}}else if(t)T=-t.baseTime/t.timescale;else{p=new Error(Wo+"without X-TIMESTAMP-MAP");return}const A=E.endTime-E.startTime,L=Nt((E.startTime+T-f)*9e4,i*9e4)/9e4;E.startTime=Math.max(L,0),E.endTime=Math.max(L+A,0);const I=E.text.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");E.text=decodeURIComponent(encodeURIComponent(I)),E.id?s&&(E.id=`hlsjscc${s}_${E.id}`):E.id=fr(E.startTime,E.endTime,I.trim()),E.endTime>0&&h.push(E)},o.onparsingerror=function(E){p=E},o.onflush=function(){if(p){a(p);return}r(h)},l.forEach(E=>{if(v)if(E.startsWith("X-TIMESTAMP-MAP=")){v=!1,g=!0,E.slice(16).split(",").forEach(y=>{y.startsWith("LOCAL:")?c=y.slice(6):y.startsWith("MPEGTS:")&&(u=parseInt(y.slice(7)))});try{f=zu(c)/1e3}catch(y){p=y}return}else E===""&&(v=!1);o.parse(E+`
39
+ `)}),o.flush()}const gr="stpp.ttml.im1t",jo=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,qo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Ju={left:"start",center:"center",right:"end",start:"start",end:"end"};function Xo(n,t,e,s){const i=J(new Uint8Array(n),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>Ft(o)),a=Tc(t.baseTime,1,t.timescale);try{r.forEach(o=>e(Zu(o,a)))}catch(o){s(o)}}function Zu(n,t){const e=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!e)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,tickRate:1},i=Object.keys(s).reduce((d,c)=>(d[c]=e.getAttribute(`ttp:${c}`)||s[c],d),{}),r=(e.getAttribute("ttp:frameRateMultiplier")||"").trim().split(/\s+/).map(Number);r.length===2&&r[0]>0&&r[1]>0&&(i.frameRate=Number(i.frameRate)*r[0]/r[1]),!e.getAttribute("ttp:tickRate")&&e.getAttribute("ttp:frameRate")&&(i.tickRate=Number(i.frameRate)*Number(i.subFrameRate));const a=e.getAttribute("xml:space")!=="preserve",o=zo(mr(e,"styling","style")),l=zo(mr(e,"layout","region")),h=mr(e,"body","[begin]");return[].map.call(h,d=>{const c=tf(d,a);if(!c||!d.hasAttribute("begin"))return null;const u=vr(d.getAttribute("begin"),i),f=vr(d.getAttribute("dur"),i);let g=vr(d.getAttribute("end"),i);if(u===null)throw Jo(d);if(g===null){if(f===null)throw Jo(d);g=u+f}const p=new cr(u-t,g-t,c);p.id=fr(p.startTime,p.endTime,p.text);const v=l[d.getAttribute("region")],E=o[d.getAttribute("style")],y=ef(v,E,o),{textAlign:T}=y;if(T){const S=Ju[T];S&&(p.lineAlign=S),p.align=T}return ht(p,y),p}).filter(d=>d!==null)}function mr(n,t,e){const s=n.getElementsByTagName(t)[0];return s?[].slice.call(s.querySelectorAll(e)):[]}function zo(n){return n.reduce((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t},{})}function tf(n,t){const e=Qo(n,t);return t?e.split(`
40
+ `).map(s=>s.replace(/ {2,}/g," ").trim()).join(`
41
+ `):e}function Qo(n,t){return[].slice.call(n.childNodes).reduce((e,s,i)=>{var r;return s.nodeName==="br"&&i?e+`
42
+ `:(r=s.childNodes)!=null&&r.length?e+Qo(s,t):e+(t?s.textContent.replace(/\s+/g," "):s.textContent)},"")}function ef(n,t,e){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&e.hasOwnProperty(a)&&(i=e[a]),r.reduce((o,l)=>{const h=pr(t,s,l)||pr(n,s,l)||pr(i,s,l);return h&&(o[l]=h),o},{})}function pr(n,t,e){return n&&n.hasAttributeNS(t,e)?n.getAttributeNS(t,e):null}function Jo(n){return new Error(`Could not parse ttml timestamp ${n}`)}function vr(n,t){if(!n)return null;if(jo.test(n))return sf(n,t);let e=Vo(n);return e===null&&qo.test(n)&&(e=rf(n,t)),e}function sf(n,t){const e=jo.exec(n),s=(e[4]|0)+(e[5]|0)/t.subFrameRate;return(e[1]|0)*3600+(e[2]|0)*60+(e[3]|0)+s/t.frameRate}function rf(n,t){const e=qo.exec(n),s=Number(e[1]);switch(e[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s/1e3;case"f":return s/t.frameRate;case"t":return s/t.tickRate}return s}function yr(n,t,e,s="",i="disabled"){const r=n.ownerDocument.createElement("track");return r.kind=t,r.label=e,s&&(r.srclang=s),r.src="data:,WEBVTT",r.track.mode=i,n.appendChild(r),r}function nf(n){return n.forced&&bh()?"forced":n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function Er(n,t){const e=n.mode;if(e==="disabled"&&(n.mode="hidden"),n.cues&&!n.cues.getCueById(t.id))try{if(n.addCue(t),!n.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(s){at.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,n.addCue(i)}catch(i){at.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}e==="disabled"&&(n.mode=e)}function Tr(n,t,e,s){const i=n.mode;if(i==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=of(n.cues,t,e);for(let a=0;a<r.length;a++)(!s||s(r[a]))&&n.removeCue(r[a])}i==="disabled"&&(n.mode=i)}function af(n,t){if(t<=n[0].startTime)return 0;const e=n.length-1;if(t>n[e].endTime)return-1;let s=0,i=e,r;for(;s<=i;)if(r=Math.floor((i+s)/2),t<n[r].startTime)i=r-1;else if(t>n[r].startTime&&s<e)s=r+1;else return r;return n[s].startTime-t<t-n[i].startTime?s:i}function of(n,t,e){const s=[],i=af(n,t);if(i>-1)for(let r=i,a=n.length;r<a;r++){const o=n[r];if(o.startTime>=t&&o.endTime<=e)s.push(o);else if(o.startTime>e)return s}return s}class Zo extends Ws{constructor(t){super(t,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1,s=!1;if(this.currentTrack){var i;const o=(i=this.currentTrack.trackNode)==null?void 0:i.track.mode;o==="showing"?(e=this.trackId,s=!0):o==="hidden"&&(e=this.trackId)}if(!s)for(let o=0;o<this.tracksInGroup.length;o++){var r;const l=(r=this.tracksInGroup[o].trackNode)==null?void 0:r.track.mode;if(l==="showing"){e=o;break}else e<0&&l==="hidden"&&(e=o)}if(e>-1){var a;this._subtitleDisplay=((a=this.tracksInGroup[e].trackNode)==null?void 0:a.track.mode)==="showing"}this.setSubtitleTrack(e,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_PARSED,this.onManifestParsed,this),t.on(m.LEVEL_LOADING,this.onLevelLoading,this),t.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_PARSED,this.onManifestParsed,this),t.off(m.LEVEL_LOADING,this.onLevelLoading,this),t.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(m.ERROR,this.onError,this)}createTracksInGroup(){var t;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(s=>{s.trackNode||(s.trackNode=yr(this.media,nf(s),s.name,s.lang))});const e=(t=this.currentTrack)==null||(t=t.trackNode)==null?void 0:t.track;e?.mode==="disabled"&&(e.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(t,e){const s=e.media;this.media=s;let i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(s.textTracks&&"onchange"in s.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):s.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const s=this.media;if(!s)return;const i=!!e.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!i&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(r=>{const a=r.trackNode;a&&(a.track.mode="hidden",a.remove(),r.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,groupId:i,details:r}=e,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}const o=a.details;a.details=e.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,o)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(a=>i?.indexOf(a)===-1)){this.groupIds=s;const a=[];if(this.tracks.forEach(d=>{(d.textCodec===gr?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!s||s.indexOf(d.groupId)>-1?(d.id=a.length,a.push(d)):d.trackNode&&(d.trackNode.remove(),d.trackNode=void 0))}),a.length===this.tracksInGroup.length){let d=!1;for(let c=0;c<a.length;c++)if(a[c]!==this.tracksInGroup[c]){d=!0;break}if(!d)return}a.length&&this.selectDefaultTrack&&!a.some(d=>d.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=a,this.trackId=-1,this.currentTrack=null;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const d=se(o,a);if(d>-1)r=a[d];else{const c=se(o,this.tracks);r=this.tracks[c]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const h={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,h),this.setSubtitleTrack(l),this.createTracksInGroup()}}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<e.length;i++){const r=e[i];if(!(s&&!r.default||!s&&!t)&&(!t||Te(r,t)))return i}if(t){for(let i=0;i<e.length;i++){const r=e[i];if(as(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const r=e[i];if(as(t.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}onError(t,e){e.fatal||!e.context||e.context.type===st.SUBTITLE_TRACK&&e.context.id===this.trackId&&ze(e.context.groupId,this.groupIds)&&this.checkRetry(e)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t,!0)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(t.id===-1)return this.setSubtitleTrack(-1,!0),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const s=this.currentTrack;if(s&&Te(t,s))return s;const i=se(t,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),r}else{if(s)return null;{const r=se(t,e);if(r>-1)return e[r]}}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=t.id,i=t.groupId,r=this.getUrlWithDirectives(t.url,e),a=t.details,o=a?.age;this.log(`Loading subtitle ${s} "${t.name}" lang:${t.lang} group:${i}${e?.msn!==void 0?" at sn "+e.msn+" part "+e.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null,track:t})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const t=this.currentTrack;this.tracksInGroup.forEach(e=>{if(e.trackNode){const s=e===t?this._subtitleDisplay?"showing":"hidden":"disabled",i=e.trackNode.track;i.mode!==s&&(i.mode=s)}})}setSubtitleTrack(t,e=!1){const s=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=t),t<-1||t>=s.length||!$(t)){this.warn(`Invalid subtitle track id: ${t}`);return}const i=this.currentTrack,r=s[t]||null;if(this.trackId=t,this.currentTrack=r,e&&this.toggleTrackModes(),!r){i&&this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:t});return}const a=!!r.details&&!r.details.live;if(r===i&&a)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:o,groupId:l="",name:h,type:d,url:c}=r;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:h,type:d,url:c});const u=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(u)}}const Qs=2,lf=100;class hf extends ea{constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=e,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(lf),this.mediaSource=e.mediaSource;const s=this.media=e.media;lt(s,"playing",this.onMediaPlaying),lt(s,"waiting",this.onMediaWaiting),lt(s,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:s}=this;s&&(ot(s,"playing",this.onMediaPlaying),ot(s,"waiting",this.onMediaWaiting),ot(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var t;const e=((t=this.hls)==null?void 0:t.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,e):e}tick(){var t;if(!((t=this.media)!=null&&t.readyState)||!this.hasBuffered)return;const e=this.getCurrentTime();this.media.currentTime<e||(this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e)}poll(t,e){var s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const a=this.media;if(!a)return;const{seeking:o}=a,l=this.seeking&&!o,h=!this.seeking&&o,d=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,t!==e){e&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&t>e&&this.nudgeOnVideoHole(t,e)),this.waiting===0&&this.stallResolved(t);return}if(h||l){l&&this.stallResolved(t);return}if(d){this.skipRetry=this.nudgeRetry=0,this.stallResolved(t),!this.ended&&a.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!q.getBuffered(a).length){this.skipRetry=this.nudgeRetry=0;return}const c=q.bufferInfo(a,t,0),u=this.fragmentTracker;u&&this.hls&&sl(c,t,u,this.hls);const f=c.nextStart||0;if(o&&u&&this.hls){const L=tl(this.hls.inFlightFragments,t),I=c.len>Qs,b=!f||L||f-t>Qs&&!u.getPartialFragment(t);if(I||b)return;this.moved=!1}const g=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&u){if(!(c.len>0)&&!f)return;const L=Math.max(f,c.start||0)-t,I=g!=null&&g.live?g.targetduration*2:Qs,b=hs(t,u);if(L>0&&(L<=I||b)){a.paused||this._trySkipBufferHole(b);return}}const p=r.detectStallWithCurrentTimeMs,v=self.performance.now(),E=this.waiting;let y=this.stalled;if(y===null)if(E>0&&v-E<p)y=this.stalled=E;else{this.stalled=v;return}const T=v-y;if(!o&&(T>=p||E&&this.moved)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(t-(g?.edge||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return;if(a.currentTime!==t){const L=t;t=a.currentTime,this.moved=!0,this.log(`currentTime changed ${L} > ${t}`);return}}const A=q.bufferInfo(a,t,r.maxBufferHole);this._tryFixBufferStall(A,T,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&t>i.end(0)){const r=q.bufferedInfo(q.timeRangesToArray(this.buffered.audio),t,0);if(r.len>1&&e>=r.start){const a=q.timeRangesToArray(i),o=q.bufferedInfo(a,e,0).bufferedIndex;if(o>-1&&o<a.length-1){const l=q.bufferedInfo(a,t,0).bufferedIndex,h=a[o].end,d=a[o+1].start;if((l===-1||l>o)&&d-h<1&&t-h<2){const c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${h} -> ${d} buffered index: ${l}`);this.warn(c.message),this.media.currentTime+=1e-6;let u=hs(t,this.fragmentTracker);u&&"fragment"in u?u=u.fragment:u||(u=void 0);const f=q.bufferInfo(this.media,t,0);this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:u,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(t,e,s){var i,r;const{fragmentTracker:a,media:o}=this,l=(i=this.hls)==null?void 0:i.config;if(!o||!a||!l)return;const h=(r=this.hls)==null?void 0:r.latestLevelDetails,d=hs(s,a);if((d||h!=null&&h.live&&s<h.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;const c=t.buffered,u=this.adjacentTraversal(t,s);(c&&c.length>1&&t.len>l.maxBufferHole||t.nextStart&&(t.nextStart-s<l.maxBufferHole||u))&&(e>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const s=this.fragmentTracker,i=t.nextStart;if(s&&i){const r=s.getFragAtPos(e,K.MAIN),a=s.getFragAtPos(i,K.MAIN);if(r&&a)return a.sn-r.sn<2}return!1}_reportStall(t){const{hls:e,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&e){this.stallReported=!0;const a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ft(t)})`);this.warn(a.message),e.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:t.len,bufferInfo:t,stalled:{start:r}})}}_trySkipBufferHole(t){const{fragmentTracker:e,media:s,hls:i}=this,r=i?.config;if(!s||!e||!r)return 0;const a=s.currentTime,o=q.bufferInfo(s,a,0);sl(o,a,e,i);const l=a<o.start?o.start:o.nextStart;if(l){const d=o.len<=r.maxBufferHole,c=o.len>0&&o.len<1&&s.readyState<3,u=l-a;if(u>0&&(d||c)){if(u>r.maxBufferHole){let E=!1;if(a===0){const y=e.getAppendedFrag(0,K.MAIN);y&&l<y.end&&(E=!0)}if(!E&&t){var h;if(!((h=i.loadLevelObj)!=null&&h.details)||tl(i.inFlightFragments,l))return 0;let y=!1,T=t.end;for(;T<l;){const S=hs(T,e),A=S?S.duration:0;if(A>0)T+=A;else{y=!0;break}}if(y)return 0}}const{nudgeMaxRetry:f,skipBufferHolePadding:g}=r,p=++this.skipRetry>f,v=Math.max(l,a)+g;if(p||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${v}`),this.moved=!0,s.currentTime=v),!(t!=null&&t.gap)||p){const E=new Error(p?`Playhead still not moving after seeking over buffer hole from ${a} to ${v} after ${r.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${v}`),y={type:Y.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:p,error:E,reason:E.message,buffer:o.len,bufferInfo:o};t&&("fragment"in t?y.part=t:y.frag=t),i.trigger(m.ERROR,y)}return v}}return 0}_tryNudgeBuffer(t){const{hls:e,media:s,nudgeRetry:i}=this,r=e?.config;if(!s||!r)return 0;const a=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const o=a+(i+1)*r.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),s.currentTime=o,e.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:t.len,bufferInfo:t})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),e.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:t.len,bufferInfo:t})}}}function tl(n,t){const e=el(n.main);if(e&&e.start<=t)return e;const s=el(n.audio);return s&&s.start<=t?s:null}function el(n){if(!n)return null;switch(n.state){case P.IDLE:case P.STOPPED:case P.ENDED:case P.ERROR:return null}return n.frag}function hs(n,t){return t.getAppendedFrag(n,K.MAIN)||t.getPartialFragment(n)}function sl(n,t,e,s){const i=s.latestLevelDetails,r=hs(t,e);if($s(s.config)&&!n.nextStart&&i&&r&&s.interstitialsManager){const a="type"in r?r:r.fragment,o=xn(i,a.sn);o?.level===a.level&&Ca(o,s.interstitialsManager.playerQueue,t)&&(n.nextStart=o.start)}}const df=.25;function Sr(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Ar(n,t,e,s,i){let r=new n(t,e,"");try{r.value=s,i&&(r.type=i)}catch{r=new n(t,e,ft(i?W({type:i},s):s))}return r}const Js=(()=>{const n=Sr();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class cf{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(m.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){this.media=e.media}onMediaAttached(){var t;const e=(t=this.hls)==null?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null,!e.transferMedia&&(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){return yr(t,"metadata","id3","","hidden")}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=Sr();if(a)for(let o=0;o<r.length;o++){const l=r[o].type;if(l===_t.emsg&&!s||!i)continue;const h=Qr(r[o].data),d=r[o].pts;let c=d+r[o].duration;c>Js&&(c=Js),c-d<=0&&(c=d+df);for(let u=0;u<h.length;u++){const f=h[u];if(!Jr(f)){this.updateId3CueEnds(d,l);const g=Ar(a,d,c,f,l);g&&this.id3Track.track.addCue(g)}}}}updateId3CueEnds(t,e){var s;const i=(s=this.id3Track)==null?void 0:s.track.cues;if(i)for(let r=i.length;r--;){const a=i[r];a.type===e&&a.startTime<t&&a.endTime===Js&&(a.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:s,type:i}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(r&&(o||l)){let h;i==="audio"?h=d=>d.type===_t.audioId3&&l:i==="video"?h=d=>d.type===_t.emsg&&o:h=d=>d.type===_t.audioId3&&l||d.type===_t.emsg&&o,Tr(r.track,e,s,h)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;const o=Sr();if(s&&i&&!a){const{fragmentStart:p,fragmentEnd:v}=t;let E=this.assetCue;E?(E.startTime=p,E.endTime=v):o&&(E=this.assetCue=Ar(o,p,v,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:h}=t,d=Object.keys(h);let c=this.dateRangeCuesAppended;if(l&&e){var u;if((u=l.track.cues)!=null&&u.length){const p=Object.keys(c).filter(v=>d.indexOf(v)===-1);for(let v=p.length;v--;){var f;const E=p[v],y=(f=c[E])==null?void 0:f.cues;delete c[E],y&&Object.keys(y).forEach(T=>{const S=y[T];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(S)}catch{}}})}}else c=this.dateRangeCuesAppended={}}const g=t.fragments[t.fragments.length-1];if(!(d.length===0||!$(g?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<d.length;p++){const v=d[p],E=h[v],y=E.startTime,T=c[v],S=T?.cues||{};let A=T?.durationKnown||!1,L=Js;const{duration:I,endDate:b}=E;if(b&&I!==null)L=y+I,A=!0;else if(E.endOnNext&&!A){const D=d.reduce((C,w)=>{if(w!==E.id){const N=h[w];if(N.class===E.class&&N.startDate>E.startDate&&(!C||E.startDate<C.startDate))return N}return C},null);D&&(L=D.startTime,A=!0)}const k=Object.keys(E.attr);for(let D=0;D<k.length;D++){const C=k[D];if(!gd(C))continue;const w=S[C];if(w)A&&!(T!=null&&T.durationKnown)?w.endTime=L:Math.abs(w.startTime-y)>.01&&(w.startTime=y,w.endTime=L);else if(o){let N=E.attr[C];md(C)&&(N=Zr(N));const U=Ar(o,y,L,{key:C,data:N},_t.dateRange);U&&(U.id=v,this.id3Track.track.addCue(U),S[C]=U,a&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&U.addEventListener("enter",this.onEventCueEnter))}}c[v]={cues:S,dateRange:E,durationKnown:A}}}}}function il(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ir(){if(!le())return!1;const n=il();return!n||n.prototype&&typeof n.prototype.appendBuffer=="function"&&typeof n.prototype.remove=="function"}function rl(){if(!Ir())return!1;const n=le();return typeof n?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>n.isTypeSupported(qe(t,"video")))||["mp4a.40.2","fLaC"].some(t=>n.isTypeSupported(qe(t,"audio"))))}function uf(){var n;const t=il();return typeof(t==null||(n=t.prototype)==null?void 0:n.changeType)=="function"}var jt={DISABLED:0,SWITCHING:1,SWITCHED:2};const ff=100;class nl extends Ns{constructor(t,e,s){super(t,e,s,"stream-controller",K.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=jt.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,r=i?i.currentTime:null;if(r===null||!$(r)||(this.log(`Media seeked to ${r}`),!this.getBufferedFrag(r)))return;const a=this.getFwdBufferInfoAtPos(i,r,K.MAIN,0);if(!a||a.len===0){this.log(`Main buffer empty at ${r} on "seeked" event: ${a&&a.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;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)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;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)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(ff),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!e}s>0&&t===-1&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s}`),t=s),this.state=P.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,!e&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=P.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case P.WAITING_LEVEL:{const{levels:t,level:e}=this,s=t?.[e],i=s?.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=P.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=P.IDLE;break}break}case P.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===P.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:i}=this;if(e===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(s!=null&&s[r]))return;const a=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)&&this.altAudio!==jt.SWITCHING){const p={type:this.targetBufferType()};this.hls.trigger(m.BUFFER_EOS,p),this.state=P.ENDED;return}if(!this.buffering)return;t.loadLevel!==r&&t.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const h=a.details;if(!h||this.state===P.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=P.WAITING_LEVEL,this.startFragRequested=!1;return}const d=o.len,c=this.getMaxBufferLength(a.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);const u=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(u,h);if(this.couldBacktrack&&!this.fragPrevious&&f&&Et(f)&&this.fragmentTracker.getState(f)!==mt.OK){var g;const p=((g=this.backtrackFragment)!=null?g:f).sn-h.startSN,v=h.fragments[p-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,u)){if(!f.gap){const p=this.audioOnly&&!this.altAudio?ut.AUDIO:ut.VIDEO,v=(p===ut.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,p)}f=this.getNextFragmentLoopLoading(f,h,o,K.MAIN,c)}f&&(this.exceedsMaxBuffer(o,c,f)||this.loadFragment(f,a,u))}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);i===mt.NOT_LOADED||i===mt.PARTIAL?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,s):this.clearTrackerIfNeeded(t)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==jt.DISABLED){var t;(((t=this.getLevelDetails())==null?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===jt.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const e=this.fragPlaying;if(e){const s=e.level;this.hls.trigger(m.FRAG_CHANGED,{frag:e,previousFrag:t}),t?.level!==s&&this.hls.trigger(m.LEVEL_SWITCHED,{level:s})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(t){this._backtrackFragment=t}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(t){this._couldBacktrack=t}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.targetBufferType())}targetBufferType(){return this.altAudio===jt.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;lt(s,"playing",this.onMediaPlaying),lt(s,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:s}=this;s&&(ot(s,"playing",this.onMediaPlaying),ot(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(t,e),!e.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=jt.DISABLED,this.audioOnly=!1}onManifestParsed(t,e){let s=!1,i=!1;for(let r=0;r<e.levels.length;r++){const a=e.levels[r].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!uf(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:s}=this;if(!s||this.state!==P.IDLE)return;const i=e.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=P.WAITING_LEVEL)}onLevelLoaded(t,e){var s;const{levels:i,startFragRequested:r}=this,a=e.level,o=e.details,l=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const h=e.levelInfo,d=this.fragCurrent;d&&(this.state===P.FRAG_LOADING||this.state===P.FRAG_LOADING_WAITING_RETRY)&&d.level!==e.level&&d.loader&&this.abortCurrentFrag();let c=0;if(o.live||(s=h.details)!=null&&s.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,h.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(h.details=o,this.levelLastLoaded=h,r||this.setStartPosition(o,c),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:a}),this.state===P.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=P.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((f,g)=>{if(g>=o.startCC)return!0;delete this.initPTS[g]}),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.playhead,a=t.fragmentStart,o=t.edge,l=r>=a-e.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!l)){const d=e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!l&&s.readyState<4||r<o-d)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i}`),this.config.liveSyncMode==="buffered"){var h;const c=q.bufferInfo(s,i,0);if(!((h=c.buffered)!=null&&h.length)){s.currentTime=i;return}if(c.start<=r){s.currentTime=i;return}const{nextStart:u}=q.bufferedInfo(c.buffered,r,0);u&&(s.currentTime=u)}else s.currentTime=i}}_handleFragmentLoadProgress(t){var e;const s=t.frag,{part:i,payload:r}=t,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const h=o.videoCodec,d=l.PTSKnown||!l.live,c=(e=s.initSegment)==null?void 0:e.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new ro(this.hls,K.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,p=g!==-1,{decryptRange:v,byteRange:E}=Ps(s,i,this.iframesOnly),y=new _s(s.level,s.sn,s.stats.chunkCount,E?E.end-E.start:r.byteLength,g,p,s.duration,this.iframesOnly,v),T=this.initPTS[s.cc];f.push(r,c,u,h,s,i,l.totalduration,d,y,T)}onAudioTrackSwitching(t,e){const s=this.hls,i=this.altAudio!==jt.DISABLED;if(bs(e.url,s))this.altAudio=jt.SWITCHING;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 r=this.fragCurrent;r&&(this.log("Switching to main audio track, cancel main fragment load"),r.abortRequests(),this.fragmentTracker.removeFragment(r)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=jt.DISABLED,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,e)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=bs(e.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?jt.SWITCHED:jt.DISABLED,this.tick()}onBufferCreated(t,e){const s=e.tracks;let i,r,a=!1;for(const o in s){const l=s[o];if(l.id==="main"){if(r=o,i=l,o==="video"){const h=s[o];h&&(this.videoBuffer=h.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:i}=e,r=s.type===K.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===P.PARSED&&(this.state=P.IDLE);return}let l=!1;if(Et(s)&&(l=!!s.gap&&!s.tagList.some(h=>h[0]==="GAP")),this.fragBufferedComplete(s,i),l){var a;s.stats.retry++;const h=(a=this.levels)==null?void 0:a[s.level];h&&h.fragmentError++}}const o=this.media;o&&(!this._hasEnoughToStart&&q.getBuffered(o).length&&(this.seekToStartPos(),this._hasEnoughToStart=!0),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var s;if(e.fatal){this.state=P.ERROR;return}switch(e.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(K.MAIN,e);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!e.levelRetry&&this.state===P.WAITING_LEVEL&&((s=e.context)==null?void 0:s.type)===st.LEVEL&&(this.state=P.IDLE);break;case R.BUFFER_APPEND_NO_PROGRESS:if(e.parent!=="main")return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of level ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case R.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(K.MAIN,e);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(e.parent!=="main")return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(e.parent!=="main")return;this.reduceLengthAndFlushBuffer(e)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onFragLoadEmergencyAborted(){this.state=P.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==ut.AUDIO||!this.altAudio){const s=(e===ut.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,e),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let s=this.startPosition;if(s>=0&&e<s){if(t.seeking){this.log(`could not seek to ${s}, already seeking at ${e}`);return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),a=q.getBuffered(t),o=a.length?a.start(0):0,l=o-s,h=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<h||this.loadingParts&&l<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),s+=l,this.startPosition=s),e<s&&(this.log(`seek to target start position ${s} from current time ${e} buffer start ${o}`),t.currentTime=s)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e.indexOf("mp4a.40.5")!==-1?e="mp4a.40.2":e="mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(s=>{const{hls:i}=this,r=s?.frag;if(!r||this.fragContextChanged(r))return;e.fragmentError=0,this.state=P.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const e=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=t,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}const{frag:o,part:l,level:h}=a,{video:d,text:c,id3:u,initSegment:f}=i,{details:g}=h,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,f){const v=f.tracks;if(v){const S=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(h,v,S,r),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:e,tracks:v})}const E=f.initPTS,y=f.timescale,T=this.initPTS[o.cc];if($(E)&&(!T||T.baseTime!==E||T.timescale!==y)){const S=f.trackId;this.initPTS[o.cc]={baseTime:E,timescale:y,trackId:S};const A=this.initPTS.slice(0);s.trigger(m.INIT_PTS_FOUND,{timestampOffsets:A,frag:o,id:e,initPTS:E,timescale:y,trackId:S})}}if(d&&g){p&&d.type==="audiovideo"&&this.logMuxedErr(o);const v=g.fragments[o.sn-1-g.startSN],E=o.sn===g.startSN,y=!v||o.cc>v.cc;if(i.independent!==!1){const{startPTS:T,endPTS:S,startDTS:A,endDTS:L}=d;if(l)l.elementaryStreams[d.type]={startPTS:T,endPTS:S,startDTS:A,endDTS:L};else if(d.firstKeyFrame&&d.independent&&r.id===1&&!y&&(this.couldBacktrack=!0),d.dropped&&d.independent){const I=this.getMainFwdBufferInfo(),b=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,k=d.firstKeyFramePTS?d.firstKeyFramePTS:T;if(!E&&b<k-this.config.maxBufferHole&&!y){this.backtrack(o);return}else y&&(o.gap=!0);o.setElementaryStreamInfo(d.type,o.start,S,o.start,L,!0)}else E&&T-(g.appliedTimelineOffset||0)>Qs&&(o.gap=!0);o.setElementaryStreamInfo(d.type,T,S,A,L),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,l,r,E||y)}else if(E||y)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:v,endPTS:E,startDTS:y,endDTS:T}=p;l&&(l.elementaryStreams[ut.AUDIO]={startPTS:v,endPTS:E,startDTS:y,endDTS:T}),o.setElementaryStreamInfo(ut.AUDIO,v,E,y,T),this.bufferFragmentData(p,o,l,r)}if(g&&u!=null&&u.samples.length){const v={id:e,frag:o,details:g,samples:u.samples};s.trigger(m.FRAG_PARSING_METADATA,v)}if(g&&c){const v={id:e,frag:o,details:g,samples:c.samples};s.trigger(m.FRAG_PARSING_USERDATA,v)}}logMuxedErr(t){this.warn(`${Et(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,s,i){if(this.state!==P.PARSING)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(s));const{audio:r,video:a,audiovideo:o}=e;if(r){const h=t.audioCodec;let d=Ls(r.codec,h);if(d==="mp4a"&&(d="mp4a.40.5"),this.audioCodecSwitch){d&&(d.indexOf("mp4a.40.5")!==-1?d="mp4a.40.2":d="mp4a.40.5");const c=r.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&!Rh()&&(d="mp4a.40.5")}d&&d.indexOf("mp4a.40.5")!==-1&&Dh()&&r.container!=="audio/mpeg"&&(d="mp4a.40.2",this.log(`Android: force audio codec to ${d}`)),h&&h!==d&&this.log(`Swapping manifest audio codec "${h}" for "${d}"`),r.levelCodec=d,r.id=K.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${d||""}/${h||""}/${r.codec}]`),delete e.audiovideo}if(a){a.levelCodec=t.videoCodec,a.id=K.MAIN;const h=a.codec;if(h?.length===4)switch(h){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${t.videoCodec||""}/${h}]${a.codec!==h?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete e.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(s),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete e.video,delete e.audio);const l=Object.keys(e);if(l.length){if(this.hls.trigger(m.BUFFER_CODECS,e),!this.hls)return;l.forEach(h=>{const d=e[h].initSegment;d!=null&&d.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:h,data:d,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.getBufferOutput();return this.getFwdBufferInfo(t,K.MAIN)}get maxBufferLength(){const{levels:t,level:e}=this,s=t?.[e];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=P.IDLE}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;return $(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if($(e)){const s=this.getLevelDetails(),i=this.currentFrag||(s?_e(null,s.fragments,e):null);if(i){const r=i.programDateTime;if(r!==null){const a=r+(e-i.start)*1e3;return new Date(a)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class al extends nl{constructor(...t){super(...t),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const e=this.media;e!=null&&e.seeking&&(e.currentTime=e.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(t){this.initPTS=t.slice()}loadMediaAt(t,e){if(!this.hls)return;const{seekOnAppend:s}=e,i=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=i,this.startPosition=t,this.state){case P.STOPPED:case P.ENDED:case P.ERROR:this.state=P.IDLE}this.state===P.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[i,e]):this.nextOp=[i,e],this.hls.off(m.BUFFERED_TO_END,this.onBufferedToEnd);const r=this.media;s&&r&&this.seekTo(i)&&(this.currentOp=[i,e],this.nextOp=void 0,this.flushPipeline(i,!0))}seekTo(t){const e=this.media;if(e){var s;const i=(s=this.getLevelDetails())==null?void 0:s.edge,r=i!==void 0?i:e.duration;if(t>=r&&(t=r-.01),q.bufferInfo(e,t,0).len>0&&this.getBufferedAt(t))return e.currentTime=t,!0}return!1}getBufferedAt(t){return this.fragmentTracker.getBufferedFrag(t,K.MAIN)}cacheSet(t,e){if(!this.hls)return;t.data=e;const s=this.cached;s.push(t),this.cachedSize+=e.buffer.byteLength;const i=this.hls.config.iframeCacheLimit;for(;this.cachedSize>i&&s.length>1;){const r=s.shift();if(r.data)this.cachedSize-=r.data.byteLength,r.data=void 0;else{this.cached=s.filter(a=>!!a.data),this.cachedSize=s.reduce((a,{data:o})=>o?o.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(t){const e=t.frag,{part:s,payload:i}=t;this.cacheFragmentData&&!s&&i!=null&&i.byteLength&&!e.data&&Et(e)&&this.cacheSet(e,new Uint8Array(i.slice(0))),super._handleFragmentLoadProgress(t)}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);if((i===mt.NOT_LOADED||i===mt.PARTIAL)&&this.canReplayCached(t)){this.replayCachedFragment(t);return}super.loadFragment(t,e,s)}canReplayCached(t){var e;if(!this.cacheFragmentData||!((e=t.data)!=null&&e.byteLength))return!1;const s=t.decryptdata;return s?.keyFormat!=="identity"||!!s.key}replayCachedFragment(t){const e=t.data.slice().buffer;this.log(`Buffering cached ${t.type} sn: ${t.sn} of level ${t.level} (${e.byteLength} bytes)`),this.fragCurrent=t,this.startFragRequested=!0;const s=t.stats=new us;s.loading.start=s.loading.first=s.loading.end=self.performance.now(),s.loaded=s.total=e.byteLength,s.chunkCount=1,this.state=P.FRAG_LOADING;const i={frag:t,part:null,payload:e,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(m.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)}fragBufferedComplete(t,e){super.fragBufferedComplete(t,e);const{currentOp:s,nextOp:i}=this;this.currentOp=this.nextOp=void 0,this.state=P.STOPPED,s!=null&&s[1].seekOnAppend&&(this.flushPipeline(s[0],!i),this.seekTo(s[0])||this.log(`Could not seek to ${s[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?Ds(q.getBuffered(this.media)):"none"}`)),i&&this.loadMediaAt.apply(this,i)}flushPipeline(t,e){if(e){const s=this.media;if(s){const i=q.bufferInfo(s,t,0),r=i.len?i.nextStart:0;r&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,K.MAIN),this.flushMainBuffer(r,1/0))}this.hls.once(m.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(m.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const t=this.hls;t.nextLoadLevel=t.startLevel===-1?0:t.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(t,e,s){const i=this.initDetails;return this.initDetails=null,super.alignPlaylists(t,e,s||i||void 0)}getMainFwdBufferInfo(){const t=this.playhead,e=this.getBufferedAt(t);if(e){const s=e.duration;return{len:s,start:t,end:t+s,bufferedIndex:-1}}return{len:0,start:t,end:t,bufferedIndex:-1}}_streamEnded(){const t=this.playhead,e=this.fragmentTracker.getBufferedFrag(t,K.MAIN);return!!(e!=null&&e.endList)}}class gf extends al{constructor(...t){super(...t),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(t){var e;const s=(e=this._img)==null?void 0:e.src;s&&self.URL.revokeObjectURL(s),this._img=t}loadMediaAt(t){if(!this.hls)return;const e=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=e,this.startPosition=t,this.state){case P.STOPPED:case P.ENDED:case P.ERROR:this.state=P.IDLE}if(this.state===P.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===P.IDLE){const s=this.getBufferedAt(t);s&&(this.fragCurrent=s,this.updateImage(s,null))}}else{const s=this.fragCurrent;(!s||t>=s.start&&t<s.end)&&(this.queued=[e])}}updateImage(t,e,s){const i=t.data;i||this.fragmentTracker.removeFragment(t);const r=this._img;if(r&&i){const a=self.performance.now(),o=e?e.stats:t.stats;o.buffering.start=t.stats.buffering.start=a,r.onload=()=>{if(!this.hls)return;const d=this.hls.levels[t.level];d!=null&&d.fragmentError&&(d.fragmentError=0,t.stats.retry=0);const c=self.performance.now(),u=e?e.stats:t.stats;u.buffering.end=t.stats.buffering.end=c,this.hls.trigger(m.FRAG_BUFFERED,{frag:t,part:e,stats:u,id:t.type,chunkMeta:s})},r.onerror=()=>{this.handleError("Image decode error",t,e,s)};const l=r.src;l&&self.URL.revokeObjectURL(l);const h=new Blob([i],{type:"image/jpeg"});r.src=self.URL.createObjectURL(h)}else this.state=P.STOPPED,this.processQueued()}processQueued(){const t=this.queued;this.queued=void 0,t&&this.loadMediaAt.apply(this,t)}handleError(t,e,s,i){if(!this.hls)return;const r=new Error(t);this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:i,frag:e,part:s,fatal:!1,error:r,err:r})}_bufferInitSegment(){}bufferFragmentData(t,e,s,i){super.bufferFragmentData(t,e,s,i,!0);const r=J(new Uint8Array(t.data1),["mdat"]);if(r.length===0){this.handleError("Could not find I-Frame mdat",e,s,i);return}const a=e;this.cacheSet(a,r[0]),this.updateImage(a,s,i)}fragBufferedComplete(t,e){this.fragmentTracker.fragBuffered(t,!0),super.fragBufferedComplete(t,e),this.processQueued()}checkFragPlaying(){var t;const e=(t=this.fragPrevious)==null?void 0:t.start;if(e!==void 0){const s=this.getAppendedFrag(e);if(s&&!Ue(s,this.fragPlaying))return this.fragPlaying=s,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}const mf=10,pf="Image I-Frame player does not accept HTMLMediaElements",ol={seekOnAppend:!0};let Zs,Lr;class vf extends xt{constructor(t,e){super("iframes",t.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,Zs||(Zs=yf(e)),Lr||(Lr=Ef(Zs)),this.hls=t,this.iframeInstances=[],this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(m.MANIFEST_LOADING,this.clearAsset,this),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this),t.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(m.MANIFEST_LOADING,this.clearAsset,this),t.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this),t.off(m.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(t=>t.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(t,e){this.stats=e.stats,this.variableList=e.variableList}onLevelsUpdated(t,{levels:e}){var s;const i=(s=this.hls)==null?void 0:s.pathwayPriority;e.length&&i&&this.iframeInstances.forEach(r=>{r.pathwayPriority=i})}onInitPtsFound(t,{id:e,timestampOffsets:s}){e===K.MAIN&&(this.initPTS=s)}onFragBuffered(t,e){var s;const i=this.hls;i&&i.hasEnoughToStart&&(((s=i.mainForwardBufferInfo)==null?void 0:s.len)||0)>mf&&this.iframeInstances.forEach(r=>{if(!r.loadingEnabled){var a;r.startLoad(((a=this.hls)==null||(a=a.media)==null?void 0:a.currentTime)||0)}})}createIFramePlayer(t){var e;return this.createInstance(Zs,(e=this.hls)==null?void 0:e.iframeVariants,t)}createImageIFramePlayer(t){var e;const s=(e=this.hls)==null?void 0:e.iframeVariants.filter(i=>i.imageCodec);return this.createInstance(Lr,s,t,"image-")}createInstance(t,e,s,i){const{hls:r}=this;if(!r)return null;const{url:a,userConfig:o,latestLevelDetails:l,loadLevelObj:h,loadLevel:d,bandwidthEstimate:c,sessionId:u}=r,{stats:f,variableList:g}=this;if(!(e!=null&&e.length)||!f||!a)return null;const p=`${i||""}iframe-player-${this.instanceCounter++}`,v=r.levels,E=h||v[d],y=_n(E,o.videoPreference),T=E?.pathwayId||".",S=W(W({},o),{},{loggerId:p,primarySessionId:u,videoPreference:y,abrEwmaDefaultEstimate:c,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},s),A=new t(S,a,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(L=>!L.url),this.iframeInstances.push(A),A.trigger(m.MANIFEST_LOADED,{levels:e,contentSteering:{uri:"",pathwayId:T},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:g}),A}}function yf(n){return class extends n{constructor(t,e,s,i){t.streamController||(t.streamController=al),super(t),this._url=e,this.streamController.setInitPts(s),this.streamController.initDetails=i}loadSource(){}loadMediaAt(t,e=ol){if(t<0)return;const s=W(W({},ol),e);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,s)}}}function Ef(n){return class extends n{constructor(t,e,s,i){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=gf),t.capLevelController=void 0,t.bufferController=void 0,super(t,e,s,i)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(pf)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}const ve=.025;let ti=(function(n){return n[n.Point=0]="Point",n[n.Range=1]="Range",n})({});function Tf(n,t,e){return`${n.identifier}-${e+1}-${ls(t)}`}class Sf{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,(t=this.assetListLoader)==null||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const s=this.playoutLimit;return t<=0||isNaN(s)?!1:s===0?!0:(((e=this.assetList[t])==null?void 0:e.startOffset)||0)>s}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return ll(e,t)?ei(t,e):t}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime,s=ei(e,t);return e-s<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,e=$(t)?t:this.duration;return this.cumulativeDuration+e}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return ll(e,t)?ei(t,e):t}return t}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<ve))}set appendInPlace(t){if(this.appendInPlaceStarted){this.resetOnResume=!t;return}this.appendInPlaceDisabled=!t}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;return this._duration!==null?e=this._duration:this.dateRange.duration?e=this.dateRange.duration:e=this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?ti.Range:ti.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return Af(this)}}function ei(n,t){return n-t.start<t.duration/2&&!(Math.abs(n-(t.start+t.duration))<ve)?t.start:t.start+t.duration}function ll(n,t){return t>n.start-ve&&t<n.start+n.duration+ve}function hl(n,t,e){const s=new self.URL(n,e);return s.protocol!=="data:"&&ge(s,"_HLS_primary_id",t),s}function Rr(n,t){for(;(e=n.assetList[++t])!=null&&e.error;)var e;return t}function Af(n){return`["${n.identifier}" ${n.cue.pre?"<pre>":n.cue.post?"<post>":""}${n.timelineStart.toFixed(2)}-${n.resumeTime.toFixed(2)}]`}function Fe(n){const t=n.timelineStart,e=n.duration||0;return`["${n.identifier}" ${t.toFixed(2)}-${(t+e).toFixed(2)}]`}class If{constructor(t,e,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(m.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=s,this.assetItem=i;const a=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,a),r.once(m.AUDIO_TRACK_LOADED,a),r.once(m.SUBTITLE_TRACK_LOADED,a),r.on(m.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(m.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(m.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let e=this.assetItem.uri;try{e=hl(e,t.config.primarySessionId||"").href}catch{}t.loadSource(e)}}bufferedInPlaceToEnd(t,e){var s;if(!this.appendInPlace)return!1;if((s=this.hls)!=null&&s.bufferedToEnd)return!0;if(!t)return!1;const i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset+(e||0),a=q.bufferInfo(t,r,.02);return this.getAssetTime(a.end)>=i-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!((t=this.hls)!=null&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return((t=this.hls)==null?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=q.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const s=e-this.startOffset;if(s>0&&s<t)return s}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return((t=this.hls)==null?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const s=t-e;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,t-e),s)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var t;(t=this.hls)!=null&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),(e=this.hls)==null||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,(t=this.hls)==null||t.detachMedia()}resumeBuffering(){var t;(t=this.hls)==null||t.resumeBuffering()}pauseBuffering(){var t;(t=this.hls)==null||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),((t=this.hls)==null?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=s=>delete s.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,s){var i;(i=this.hls)==null||i.on(t,e)}once(t,e,s){var i;(i=this.hls)==null||i.once(t,e)}off(t,e,s){var i;(i=this.hls)==null||i.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${Fe(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const br=.033;class Lf extends xt{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((s,i)=>t<=i.startOffset&&e>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let s=-1;t.nextEvent?s=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(s=this.findEventIndex(t.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(e===void 0&&(e=t.start),s=this.findItemIndexAtTime(e));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(t,e){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];e&&e!=="primary"&&(r=r[e]);const a=r.start,o=s[i].event,l=o!=null&&o.cue.pre?o.duration:r.end;if(t===a||t>a&&t<l)return i}return-1}findJumpRestrictedIndex(t,e){const s=this.items;if(s)for(let i=t;i<=e&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(t){const e=this.items;if(e)for(let i=e.length;i--;){var s;if(((s=e[i].event)==null?void 0:s.identifier)===t)return i}return-1}findAssetIndex(t,e){const s=t.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const a=s[r];if(!a.error){const o=a.timelineStart;if(e===o||e>o&&(e<o+(a.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var t;const e=(t=this.items)==null||(t=t[this.length-1])==null?void 0:t.event;if(e){const s=e.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,e,s=0){const i=t.main.details,{dateRanges:r}=i,a=this.events,o=this.parseDateRanges(r,{url:i.url},e),l=Object.keys(r),h=a?a.filter(d=>l.indexOf(d.identifier)===-1):[];o.length&&o.sort((d,c)=>{const u=d.cue.pre,f=d.cue.post,g=c.cue.pre,p=c.cue.post;if(u&&!g)return-1;if(g&&!u||f&&!p)return 1;if(p&&!f)return-1;if(!u&&!g&&!f&&!p){const v=d.startTime,E=c.startTime;if(v!==E)return v-E}return d.dateRange.tagOrder-c.dateRange.tagOrder}),this.events=o,h.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(t,h,s)}updateSchedule(t,e=[],s=0,i=!1){const r=this.events||[];if(r.length||e.length||this.length<2){const a=this.items,o=this.parseSchedule(r,t,s);(i||e.length||a?.length!==o.length||o.some((l,h)=>Math.abs(l.playout.start-a[h].playout.start)>.005||Math.abs(l.playout.end-a[h].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(e,a))}}parseDateRanges(t,e,s){const i=[],r=Object.keys(t);for(let a=0;a<r.length;a++){const o=r[a],l=t[o];if(l.isInterstitial){let h=this.eventMap[o];h?h.setDateRange(l):(h=new Sf(l,e),this.eventMap[o]=h,s===!1&&(h.appendInPlace=s)),i.push(h)}}return i}parseSchedule(t,e,s=0){const i=[],r=e.main.details,a=r.live?1/0:r.edge;let o=0;if(t=t.filter(h=>!h.error&&!(h.cue.once&&h.hasPlayed)),t.length){this.resolveOffsets(t,e);let h=0,d=0;if(t.forEach((c,u)=>{const f=c.cue.pre,g=c.cue.post,p=t[u-1]||null,v=c.appendInPlace,E=g?a:c.startOffset,y=c.duration,T=c.timelineOccupancy===ti.Range?y:0,S=f&&r.live?s+(c.resumeOffset||0):0,A=S||c.resumptionOffset,L=p?.startTime===E,I=E+c.cumulativeDuration;let b=v?I+y:E+A;if(f||!g&&E<=0){const D=d;d+=T,c.timelineStart=I;const C=o;o+=y,i.push({event:c,start:I,end:b,playout:{start:C,end:o},integrated:{start:D,end:d}})}else if(E<=a){if(!L){const w=E-h;if(w>br){const N=h,U=d;d+=w;const G=o;o+=w;const M={previousEvent:t[u-1]||null,nextEvent:c,start:N,end:N+w,playout:{start:G,end:o},integrated:{start:U,end:d}};i.push(M)}else w>0&&p&&(p.cumulativeDuration+=w,i[i.length-1].end=E)}g&&(b=I),c.timelineStart=I;const D=d;d+=T;const C=o;o+=y,i.push({event:c,start:I,end:b,playout:{start:C,end:o},integrated:{start:D,end:d}})}else return;const k=S||c.resumeTime;g||k>a?h=a:!f&&b&&c.appendInPlaceStarted&&k-b>br?h=b:h=k}),h<a){var l;const c=h,u=d,f=a-h;d+=f;const g=o;o+=f,i.push({previousEvent:((l=i[i.length-1])==null?void 0:l.event)||null,nextEvent:null,start:h,end:c+f,playout:{start:g,end:o},integrated:{start:u,end:d}})}this.setDurations(a,o,d)}else i.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return i}setDurations(t,e,s){this.durations={primary:t,playout:e,integrated:s}}resolveOffsets(t,e){const s=e.main.details,i=s.live?1/0:s.edge;let r=0,a=-1;t.forEach((o,l)=>{const h=o.cue.pre,d=o.cue.post,c=h?0:d?i:o.startTime;this.updateAssetDurations(o),a===c?o.cumulativeDuration=r:(r=0,a=c),!d&&o.snapOptions.in&&(o.resumeAnchor=_e(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,e)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<t.length&&t[l+1].startTime-t[l].resumeTime<br&&(t[l+1].appendInPlace=!1,t[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const u=$(o.resumeOffset)?o.resumeOffset:o.duration;r+=u})}primaryCanResumeInPlaceAt(t,e){const s=t.resumeTime,i=t.startTime+t.resumptionOffset;return Math.abs(s-i)>ve?(this.log(`"${t.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(e).some(r=>{const a=e[r].details,o=a.edge;if(s>=o)return this.log(`"${t.identifier}" resumption ${s} past ${r} playlist end ${o}`),!1;const l=_e(null,a.fragments,s);if(!l)return this.log(`"${t.identifier}" resumption ${s} does not align with any fragments in ${r} playlist (${a.fragStart}-${a.fragmentEnd})`),!0;const h=r==="audio"?.175:0;return Math.abs(l.start-s)<ve+h||Math.abs(l.end-s)<ve+h?!1:(this.log(`"${t.identifier}" resumption ${s} not aligned with ${r} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let s=0,i=!1,r=!1;for(let a=0;a<t.assetList.length;a++){const o=t.assetList[a],l=e+s;o.startOffset=s,o.timelineStart=l,i||(i=o.duration===null),r||(r=!!o.error);const h=o.error?0:o.duration||0;s+=h}i&&!r?t.duration=Math.max(s,t.duration):t.duration=s}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function Mt(n){return`[${n.event?'"'+n.event.identifier+'"':"primary"}: ${n.start.toFixed(2)}-${n.end.toFixed(2)}]`}class Rf{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const s=t.assetListUrl;let i;try{i=hl(s,this.hls.sessionId,t.baseUrl)}catch(u){const f=this.assignAssetListError(t,R.ASSET_LIST_LOAD_ERROR,u,s);this.hls.trigger(m.ERROR,f);return}e&&i.protocol!=="data:"&&ge(i,"_HLS_start_offset",""+e);const r=this.hls.config,a=r.loader,o=new a(r),l={type:st.INTERSTITIAL_ASSET_LIST,responseType:"json",url:i.href},h=r.interstitialAssetListLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(u,f,g,p)=>{const v=u.data,E=v?.ASSETS;if(!Array.isArray(E)){const y=this.assignAssetListError(t,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,p);this.hls.trigger(m.ERROR,y);return}t.assetListResponse=v,this.hls.trigger(m.ASSET_LIST_LOADED,{event:t,assetListResponse:v,networkDetails:p})},onError:(u,f,g,p)=>{const v=this.assignAssetListError(t,R.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${u.code} ${u.text} (${f.url})`),f.url,p,g);this.hls.trigger(m.ERROR,v)},onTimeout:(u,f,g)=>{const p=this.assignAssetListError(t,R.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,u,g);this.hls.trigger(m.ERROR,p)}};return o.load(l,d,c),this.hls.trigger(m.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,e,s,i,r,a){return t.error=s,{type:Y.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:i,error:s,networkDetails:a,stats:r}}}function dl(n){var t;n==null||(t=n.play())==null||t.catch(()=>{})}function Ie(n,t){return`[${n}] Advancing timeline position to ${t}`}class bf extends xt{constructor(t,e){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const r=i<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=s,this.bufferedPos=s;const a=this.playingItem;if(!a){this.checkBuffer();return}if(r&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),r&&s<a.start||s>=a.end){var o;const u=this.findItemIndex(a);let f=this.schedule.findItemIndexAtTime(s);if(f===-1&&(f=u+(r?-1:1),this.log(`seeked ${r?"back ":""}to position not covered by schedule ${s} (resolving from ${u} to ${f})`)),!this.isInterstitial(a)&&(o=this.media)!=null&&o.paused&&(this.shouldPlay=!1),!r&&f>u){const g=this.schedule.findJumpRestrictedIndex(u+1,f);if(g>u){this.setSchedulePosition(g);return}}this.setSchedulePosition(f);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(a)){const u=a.event.assetList[0];u&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,u))}return}const h=l.timelineStart,d=l.duration||0;if(r&&s<h||s>=h+d){var c;(c=a.event)!=null&&c.appendInPlace&&(this.clearAssetPlayers(a.event,a),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const a=r.timelineStart+(r.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const a=this.playingItem,o=r.events||[],l=r.items||[],h=r.durations,d=s.map(v=>v.identifier),c=!!(o.length||d.length);(c||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
43
+ Schedule: ${l.map(v=>Mt(v))} pos: ${this.timelinePos}`),d.length&&this.log(`Removed events ${d}`);let u=null,f=null;a&&(u=this.updateItem(a,this.timelinePos),this.itemsMatch(a,u)?this.playingItem=u:this.waitingItem=null);const g=this.waitingItem;g&&(this.waitingItem=this.updateItem(g),!this.waitingItem&&!a&&(this.log(`INTERSTITIAL_ENDED unresolved ${Mt(g)}`),this.hls.trigger(m.INTERSTITIAL_ENDED,{event:g.event,schedule:l.slice(0),scheduleIndex:-1})));const p=this.bufferingItem;if(p&&(f=this.updateItem(p,this.bufferedPos),this.itemsMatch(p,f)?this.bufferingItem=f:p.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(p.event,null))),s.forEach(v=>{v.assetList.forEach(E=>{this.clearAssetPlayer(E.identifier,null)})}),this.playerQueue.forEach(v=>{if(v.interstitial.appendInPlace){const E=v.assetItem.timelineStart,y=v.timelineOffset-E;if(y)try{v.timelineOffset=E}catch(T){Math.abs(y)>ve&&this.warn(`${T} ("${v.assetId}" ${v.timelineOffset}->${E})`)}}}),c||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:h,removedIds:d}),this.isInterstitial(a)&&d.indexOf(a.event.identifier)>-1){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(u,a),p&&f!==u&&this.trimInPlace(f,p),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new Rf(t),this.schedule=new Lf(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(m.BUFFER_APPENDED,this.onBufferAppended,this),t.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(m.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(m.MEDIA_ENDED,this.onMediaEnded,this),t.on(m.ERROR,this.onError,this),t.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(m.BUFFER_CODECS,this.onBufferCodecs,this),t.off(m.BUFFER_APPENDED,this.onBufferAppended,this),t.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(m.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(m.MEDIA_ENDED,this.onMediaEnded,this),t.off(m.ERROR,this.onError,this),t.off(m.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;(t=this.getBufferingPlayer())==null||t.resumeBuffering()}pauseBuffering(){var t;(t=this.getBufferingPlayer())==null||t.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){ot(t,"play",this.onPlay),ot(t,"pause",this.onPause),ot(t,"seeking",this.onSeeking),ot(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const s=this.media=e.media;lt(s,"seeking",this.onSeeking),lt(s,"timeupdate",this.onTimeupdate),lt(s,"play",this.onPlay),lt(s,"pause",this.onPause)}onMediaAttached(t,e){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const s=!!e.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,s=c=>c&&t.getAssetPlayer(c.identifier),i=(c,u,f,g,p)=>{if(c){let v=c[u].start;const E=c.event;if(E){if(u==="playout"||E.timelineOccupancy!==ti.Point){const y=s(f);y?.interstitial===E&&(v+=y.assetItem.startOffset+y[p])}}else{const y=g==="bufferedPos"?a():t[g];v+=y-c.start}return v}return 0},r=(c,u)=>{var f;if(c!==0&&u!=="primary"&&(f=t.schedule)!=null&&f.length){var g;const p=t.schedule.findItemIndexAtTime(c),v=(g=t.schedule.items)==null?void 0:g[p];if(v){const E=v[u].start-v.start;return c+E}}return c},a=()=>{const c=t.bufferedPos;return c===Number.MAX_VALUE?o("primary"):Math.max(c,0)},o=c=>{var u,f;return(u=t.primaryDetails)!=null&&u.live?t.primaryDetails.edge:((f=t.schedule)==null?void 0:f.durations[c])||0},l=(c,u)=>{var f,g;const p=t.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!t.schedule)return;t.log(`seek to ${c} "${u}"`);const v=t.effectivePlayingItem,E=t.schedule.findItemIndexAtTime(c,u),y=(g=t.schedule.items)==null?void 0:g[E],T=t.getBufferingPlayer(),S=T?.interstitial,A=S?.appendInPlace,L=v&&t.itemsMatch(v,y);if(v&&(A||L)){const I=s(t.playingAsset),b=I?.media||t.primaryMedia;if(b){const k=u==="primary"?b.currentTime:i(v,u,t.playingAsset,"timelinePos","currentTime"),D=c-k,C=(A?k:b.currentTime)+D;if(C>=0&&(!I||A||C<=I.duration)){b.currentTime=C;return}}}if(y){let I=c;if(u!=="primary"){const k=y[u].start,D=c-k;I=y.start+D}const b=!t.isInterstitial(y);if((!t.isInterstitial(v)||v.event.appendInPlace)&&(b||y.event.appendInPlace)){const k=t.media||(A?T?.media:null);k&&(k.currentTime=I)}else if(v){const k=t.findItemIndex(v);if(E>k){const C=t.schedule.findJumpRestrictedIndex(k+1,E);if(C>k){t.setSchedulePosition(C);return}}let D=0;if(b)t.timelinePos=I,t.checkBuffer();else{const C=y.event.assetList,w=c-(y[u]||y).start;for(let N=C.length;N--;){const U=C[N];if(U.duration&&w>=U.startOffset&&w<U.startOffset+U.duration){D=N;break}}}t.setSchedulePosition(E,D)}}},h=()=>{const c=t.effectivePlayingItem;if(t.isInterstitial(c))return c;const u=e();return t.isInterstitial(u)?u:null},d={get bufferedEnd(){const c=e(),u=t.bufferingItem;if(u&&u===c){var f;return i(u,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-u.playout.start||((f=t.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const c=h(),u=t.effectivePlayingItem;return u&&u===c?i(u,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-u.playout.start:0},set currentTime(c){const u=h(),f=t.effectivePlayingItem;f&&f===u&&l(c+f.playout.start,"playout")},get duration(){const c=h();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;const u=(c=h())==null?void 0:c.event.assetList;return u?u.map(f=>t.getAssetPlayer(f.identifier)):[]},get playingIndex(){var c;const u=(c=h())==null?void 0:c.event;return u&&t.effectivePlayingAsset?u.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return h()}};return this.manager={get events(){var c;return((c=t.schedule)==null||(c=c.events)==null?void 0:c.slice(0))||[]},get schedule(){var c;return((c=t.schedule)==null||(c=c.items)==null?void 0:c.slice(0))||[]},get interstitialPlayer(){return h()?d:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const c=e();return t.findItemIndex(c)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const c=t.effectivePlayingItem;return t.findItemIndex(c)},primary:{get bufferedEnd(){return a()},get currentTime(){const c=t.timelinePos;return c>0?c:0},set currentTime(c){l(c,"primary")},get duration(){return o("primary")},get seekableStart(){return t.seekableStart}},integrated:{get bufferedEnd(){return i(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){l(c,"integrated")},get duration(){return o("integrated")},get seekableStart(){return r(t.seekableStart,"integrated")}},skip:()=>{const c=t.effectivePlayingItem,u=c?.event;if(u&&!u.restrictions.skip){const f=t.findItemIndex(c);if(u.appendInPlace){const g=c.playout.start+c.event.duration;l(g+.001,"playout")}else t.advanceAfterAssetEnded(u,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,s=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!e||!s?!1:this.findItemIndex(e)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,e;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(t=this.bufferingItem)!=null&&(t=t.event)!=null&&t.appendInPlace&&(i=this.primaryMedia);const r=(e=i)==null?void 0:e.currentTime;if(!(r===void 0||!$(r)))return r}get primaryMedia(){var t;return this.media||((t=this.detachedData)==null?void 0:t.media)||null}isInterstitial(t){return!!(t!=null&&t.event)}retreiveMediaSource(t,e){const s=this.getAssetPlayer(t);s&&this.transferMediaFromPlayer(s,e)}transferMediaFromPlayer(t,e){const s=t.interstitial.appendInPlace,i=t.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&i){this.detachedData={media:i};return}const r=t.transferMedia();this.log(`transfer MediaSource from ${t} ${ft(r)}`),this.detachedData=r}else e&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(t,e){var s,i;if(t.media===e)return;let r=null;const a=this.hls,o=t!==a,l=o&&t.interstitial.appendInPlace,h=(s=this.detachedData)==null?void 0:s.mediaSource;let d;if(a.media)l&&(r=a.transferMedia(),this.detachedData=r),d="Primary";else{const g=this.getBufferingPlayer();g?(r=g.transferMedia(),this.detachedData=r,d=`${g}`):h?d="detached MediaSource":d="detached media"}if(!r){if(h)r=this.detachedData,this.log(`using detachedData: MediaSource ${ft(r)}`);else if(!this.detachedData||a.media===e){const g=this.playerQueue;g.length>1&&g.forEach(p=>{if(o&&p.interstitial.appendInPlace!==l){const v=p.interstitial;this.clearInterstitial(p.interstitial,null),v.appendInPlace=!1,v.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${v}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}}const c=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed";if(this.log(`${c?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${d} (media.currentTime: ${e.currentTime})`),!c&&!o){t.attachMedia(e);return}const u=c&&r?W({},r):{media:e},f=this.schedule;if(f&&o){const g=t.assetId===f.assetIdAtEnd;u.overrides={duration:f.duration,endOfStream:g||t.appendInPlace===!1}}if(!c&&l){const g=t,p=g.assetItem.timelineStart;if(p){const v=g.hls,E=Math.max(this.timelinePos-p,Number.EPSILON);v.startPosition!==E&&(this.log(`Set ${g} startPosition: ${E}`),v.config.startPosition=E,v.loadingEnabled&&v.startLoad(E))}}t.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=t?.events,s=this.hls;if(!e||this.playbackDisabled||!this.media||!s)return;this.bufferedPos===-1&&(this.bufferedPos=0);const i=this.timelinePos,r=this.effectivePlayingItem;if(i===-1){if(!s.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}const a=s.startPosition;if(this.timelinePos=a,e.length===0)this.setSchedulePosition(0);else if(e[0].cue.pre){this.log(Ie("checkStart (preroll)",a));const o=t.findEventIndex(e[0].identifier);this.setSchedulePosition(o)}else if(a>=0||!this.primaryLive){this.log(Ie("checkStart",a));const o=this.timelinePos=a>0?a:0,l=t.findItemIndexAtTime(o);this.setSchedulePosition(l)}else s.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(Ie("checkStart (playing item)",r.start));const a=t.findItemIndex(r);this.setSchedulePosition(a)}}advanceAssetBuffering(t,e){const s=t.event,i=s.findAssetIndex(e),r=Rr(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(t,r);else if(this.schedule){var a;const o=this.getNextItemIndex(t,!0),l=(a=this.schedule.items)==null?void 0:a[o];l&&this.bufferedToItem(l)}}livePrerollResumption(t,e){if(t.cue.pre&&this.primaryLive&&!$(t.resumeOffset)&&this.hls){const s=this.getLiveStartPos();if(e){const i=this.getBufferingPlayer(),r=i!=null&&i.interstitial.cue.pre?i.remaining:0;return s+r}return s}}getNextItemIndex(t,e){if(this.schedule){const s=this.livePrerollResumption(t.event,e);if(s!==void 0)return this.log(`find next item index @${s}`),this.schedule.findItemIndexAtTime(s)}return this.findItemIndex(t)+1}advanceAfterAssetEnded(t,e,s){const i=Rr(t,s);if(t.isAssetPastPlayoutLimit(i)){if(this.schedule){const r=this.schedule.items;if(r){const a=r[e],o=a.event?this.getNextItemIndex(a):e+1,l=r.length;if(o>=l){this.setSchedulePosition(-1);return}const h=t.resumeTime;this.timelinePos<h&&(this.log(Ie("advanceAfterAssetEnded",h)),this.timelinePos=h,t.appendInPlace&&!r[o].event&&this.hls.startLoad(h+.01),this.checkBuffer(this.bufferedPos<h)),this.setSchedulePosition(o)}}}else{if(t.appendInPlace){const r=t.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(e,i)}}setScheduleToAssetAtTime(t,e){const s=this.schedule;if(!s)return;const i=e.parentIdentifier,r=s.getEvent(i);if(r){const a=s.findEventIndex(i),o=s.findAssetIndex(r,t);this.advanceAfterAssetEnded(r,a,o-1)}}setSchedulePosition(t,e){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const r=t>=0?i[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${r&&Mt(r)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const c=a.event,u=this.playingAsset,f=u?.identifier,g=f?this.getAssetPlayer(f):null;if(g&&f&&(!this.eventItemsMatch(a,r)||e!==void 0&&f!==c.assetList[e].identifier)){var l;const p=c.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${p+1}/${c.assetList.length} ${Fe(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:p,event:c,schedule:i.slice(0),scheduleIndex:t,player:g}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(c,this.findItemIndex(this.playingItem),p);return}this.retreiveMediaSource(f,r),g.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${c} ${Mt(a)}`),c.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:c,schedule:i.slice(0),scheduleIndex:t}),c.cue.once&&this.hls)){var h;this.updateSchedule();const p=(h=this.schedule)==null?void 0:h.items;if(r&&p){const v=this.findItemIndex(r),E=this.livePrerollResumption(c);if(E!==void 0){let y=E;const T=this.getNextItemIndex(a);if(!this.isInterstitial(i[T])){var d;const S=(d=this.primaryDetails)==null?void 0:d.fragments;if(c.snapOptions.in&&S){const A=_e(null,S,E);A&&(y=Math.min(Math.max(i[T].start,ei(y,A)),i[T].end))}}if(this.log(Ie("live join (preroll)",y)),this.timelinePos=y,T!==v&&(T||T===0)){this.advanceSchedule(T,p,void 0,a,o);return}}this.advanceSchedule(v,p,e,a,o)}return}}this.advanceSchedule(t,i,e,a,o)}advanceSchedule(t,e,s,i,r){const a=this.schedule;if(!a)return;const o=e[t]||null,l=this.primaryMedia,h=this.playerQueue;if(h.length&&h.forEach(d=>{const c=d.interstitial,u=a.findEventIndex(c.identifier);(u<t||u>t+1)&&this.clearInterstitial(c,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const d=o.event;if(s===void 0){s=d.cue.pre?0:a.findAssetIndex(d,this.timelinePos);const g=Rr(d,s-1);if(d.isAssetPastPlayoutLimit(g)||d.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(d,t,s);return}s=g}const c=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let u=this.preloadAssets(d,s);if(this.eventItemsMatch(o,c||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Mt(o)} ${d.appendInPlace?"append in place":""}`),d.hasPlayed=!1,this.hls.trigger(m.INTERSTITIAL_STARTED,{event:d,schedule:e.slice(0),scheduleIndex:t})),!d.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${d}`);return}if(d.assetListLoader&&(d.assetListLoader.destroy(),d.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${d}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=d.assetList[s];if(!f){this.advanceAfterAssetEnded(d,t,s||0);return}if(u||(u=this.getAssetPlayer(f.identifier)),u===null||u.destroyed){const g=d.assetList.length;this.warn(`asset ${s+1}/${g} player destroyed ${d}`),u=this.createAssetPlayer(d,f,s),u.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(u,s,e,t,l),this.shouldPlay&&dl(u.media)}else o?(this.resumePrimary(o,t,i),this.shouldPlay&&dl(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var t;return(t=this.mediaSelection)==null?void 0:t.main.details}get primaryLive(){var t;return!!((t=this.primaryDetails)!=null&&t.live)}resumePrimary(t,e,s){var i,r;this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(t),this.endedItem=null,this.log(`resuming ${Mt(t)}`);let a=this.timelinePos;if((i=this.detachedData)!=null&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<t.start||a>=t.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(t,e),this.log(Ie("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,t)),!s)return;const o=(r=this.schedule)==null?void 0:r.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Mt(t)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:e}),this.checkBuffer())}get seekableStart(){var t;return this.primaryLive&&((t=this.primaryDetails)==null?void 0:t.fragmentStart)||0}getPrimaryResumption(t,e,s){const i=t.start;if(this.primaryLive){if(e===0)return this.hls.startPosition;const r=this.endedItem||this.playingItem,a=r!=null&&r.event?this.livePrerollResumption(r.event,s):void 0;if(a!==void 0)return a;const o=this.primaryDetails;if(o){const{fragmentStart:l,edge:h}=o;if(i<l||i>h&&!s){const d=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${i} [${l}-${h}]) snapping to liveSync ${d}`),d||l}}}return this.log(`primary resumption itemStart: ${i}`),i}getLiveStartPos(){var t;const e=this.hls.startPosition,s=this.hls.liveSyncPosition||0,i=(((t=this.primaryDetails)==null?void 0:t.targetduration)||10)*3;return e===-1||s&&s-e<i?s||0:e}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);return e!=null&&e.hls?e.hls.bufferedToEnd:q.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,s){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(t,s)),s||(this.log(Ie("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,s))}startLoadingPrimaryAt(t,e){const s=this.hls,{loadingEnabled:i,bufferingEnabled:r,startPosition:a}=s,o=s.hasEnoughToStart;if(this.log(`Start loading primary @${t} bufferedPos: ${this.bufferedPos} startPosition: ${a} skip seek: ${e} has enough ${o} loadingEnabled: ${i} bufferingEnabled: ${r}`),!e&&o||!i||Math.abs(a-t)>.1){const l=this.primaryDetails;if(l!=null&&l.live&&t+.5>=l.edge){const h=this.bufferingItem;this.log(`Resume primary loading when live passes ${t} buffering item: ${h?Mt(h):null}`),s.pauseBuffering(),this.bufferPastEdge=!0;return}s.startLoad(t,e)}else r||s.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),(t=this.schedule)==null||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(m.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(m.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(e.level===-1||!this.schedule)return;const s=this.hls.levels[e.level];if(!s.details)return;const i=W(W({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i;const r=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,r===-1?0:r),!!this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){const a=this.primaryDetails,o=this.bufferedPos;if(a!=null&&a.live&&o+.5<a.edge){this.bufferPastEdge=!1;const l=this.bufferingItem;if(this.log(`Live edge ${a.edge} passed buffer: ${o} buffering item: ${l?Mt(l):null}`),l?.end===1/0){const h=this.playingItem,d=this.isInterstitial(h)&&h.event.appendInPlace;this.hls.startLoad(Math.max(o,l.start),d)}else{const h=this.getBufferingPlayer();h&&h.bufferedInPlaceToEnd(this.primaryMedia,h.currentTime)&&h.hls&&h.hls.trigger(m.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(t,e){const s=this.hls.audioTracks[e.id],i=this.mediaSelection;if(!i){this.altSelection=W(W({},this.altSelection),{},{audio:s});return}const r=W(W({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(t,e){const s=this.hls.subtitleTracks[e.id],i=this.mediaSelection;if(!i){this.altSelection=W(W({},this.altSelection),{},{subtitles:s});return}const r=W(W({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(t,e){const s=kn(e);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(e)||i.setAudioOption(s)))}onSubtitleTrackSwitch(t,e){const s=kn(e);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(e)||e.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(t,e){const s=e.tracks;s&&(this.requiredTracks=s)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let s=0;s<e.length;s++){const i=e[s];if(i.cue.post){const r=this.getEventItem(i.identifier);r&&this.eventItemsMatch(r,this.bufferingItem)&&this.bufferedToItem(r,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const s=this.findItemIndex(e);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(t,e){var s;const i=(s=this.schedule)==null?void 0:s.items;if(t&&i){const r=this.findItemIndex(t,e);return i[r]||null}return null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((r,a)=>{t.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});const s=t.end+.25,i=q.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Mt(t)} (was ${Mt(e)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var s;return!!e&&(t===e||t.event.identifier===((s=e.event)==null?void 0:s.identifier))}findEventIndex(t){return this.schedule?this.schedule.findEventIndex(t):-1}getEventItem(t){if(this.schedule){var e;const s=(e=this.schedule.items)==null?void 0:e[this.findEventIndex(t)];if(this.isInterstitial(s)&&s.event.identifier===t)return s}}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e,s;const i=this.mediaSelection;if(!i)return;const r=((e=this.hls)==null?void 0:e.liveSyncPosition)||0;(s=this.schedule)==null||s.updateSchedule(i,[],r,t)}checkBuffer(t){var e;const s=(e=this.schedule)==null?void 0:e.items;if(!s)return;const i=q.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=i.len<1),this.updateBufferedPos(i.end,s,t)}updateBufferedPos(t,e,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t||!i)return;if(e.length===1&&this.itemsMatch(e[0],r)){this.bufferedPos=t;return}const a=this.playingItem,o=this.findItemIndex(a);let l=i.findItemIndexAtTime(t);if(this.bufferedPos<t){var h;const d=this.findItemIndex(r),c=Math.min(d+1,e.length-1),u=e[c];if((l===-1&&r&&t>=r.end||(h=u.event)!=null&&h.appendInPlace&&t+.01>=u.start)&&(l=c),this.isInterstitial(r)){const f=r.event;if(c-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=t,l>d&&l>o)this.bufferedToItem(u);else{const f=this.primaryDetails;this.primaryLive&&f&&t>f.edge-f.targetduration&&u.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(u)&&this.preloadAssets(u.event,0)}}else s&&a&&!this.itemsMatch(a,r)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(e[l]))}assetsBuffered(t,e){return t.event.assetList.length===0?!1:!t.event.assetList.some(s=>{const i=this.getAssetPlayer(s.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(t,e)&&s){const{items:i,events:r}=s;if(!i||!r)return e;const a=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const l=o?o.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Mt(t)}`+(e?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const h=s.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((d,c)=>{const u=this.getAssetPlayer(d.identifier);u&&(c===h&&u.loadSource(),u.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(h=>h.pauseBuffering());this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const s=this.setBufferingItem(t);if(!this.playbackDisabled){if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(s!==null){this.bufferingAsset=null;const i=this.getPrimaryResumption(t,this.findItemIndex(t),!0),r=this.bufferedPos=Math.max(i,Math.min(this.bufferedPos,t.end),this.timelinePos,t.start),a=this.detachedData;if(a)a.mediaSource?this.attachPrimary(r,t,!0):this.startLoadingPrimaryAt(r);else{const o=this.playingItem,l=this.isInterstitial(o)&&o.event.appendInPlace;this.startLoadingPrimaryAt(r,l)}}}}bufferedToEvent(t,e){const s=t.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const a=this.preloadAssets(s,e);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(t,e){const s=t.assetUrl,i=t.assetList.length,r=i===0&&!t.assetListLoader,a=t.cue.once;if(r){const l=t.timelineStart,h=this.playingItem,d=this.getBufferingPlayer();if(t.appendInPlace){var o;!this.isInterstitial(h)&&(h==null||(o=h.nextEvent)==null?void 0:o.identifier)===t.identifier&&this.flushFrontBuffer(l+.25)}let c,u=0;if((!d||d.interstitial.cue.pre)&&this.primaryLive&&(u=this.getLiveStartPos(),d&&(u+=d.remaining)),u&&!(t.cue.pre||t.cue.post)){const g=u-l;g>0&&(c=Math.round(g*1e3)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${s?1:i} ${t}${u?` live-start: ${u} start-offset: ${c} (timeline-start: ${l})`:""}`),s)return this.createAsset(t,0,0,l,t.duration,s);const f=this.assetListLoader.loadAssetList(t,c);f&&(t.assetListLoader=f)}else if(!a&&i){for(let h=e;h<i;h++){const d=t.assetList[h],c=this.getAssetPlayerQueueIndex(d.identifier);(c===-1||this.playerQueue[c].destroyed)&&!d.error&&this.createAssetPlayer(t,d,h)}const l=t.assetList[e];if(l){const h=this.getAssetPlayer(l.identifier);return h&&h.loadSource(),h}}return null}flushFrontBuffer(t){const e=this.requiredTracks;if(!e)return;const s=this.primaryDetails;s&&t>=s.edge||(this.log(`Removing front buffer starting at ${t}`),Object.keys(e).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:i})}))}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let s=0;s<e.length;s++)if(t===e[s].assetId)return s;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e){for(let s=0;s<t.length;s++)if(t[s].media===e)return t[s]}return null}createAsset(t,e,s,i,r,a){const o={parentIdentifier:t.identifier,identifier:Tf(t,a,e),duration:r,startOffset:s,timelineStart:i,uri:a};return this.createAssetPlayer(t,o,e)}createAssetPlayer(t,e,s){const i=this.hls,r=i.userConfig,a=i.loadLevelObj||i.levels[i.currentLevel],o=_n(a,r.videoPreference),l=i.audioTracks[i.audioTrack],h=i.subtitleTracks[i.subtitleTrack];let d=0;if(this.primaryLive||t.appendInPlace){const S=this.timelinePos-e.timelineStart;if(S>=0){const A=e.duration;A&&S<A&&(d=S)}}const c=e.identifier,u=W(W({},r),{},{maxMaxBufferLength:Math.min(15,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:d,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||r.audioPreference,subtitlePreference:h||r.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(u.timelineOffset=e.timelineStart));const f=u.cmcd;f!=null&&f.sessionId&&f.contentId&&(u.cmcd=ht({},f,{contentId:ls(e.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${t} and asset ${c}`);const g=new If(this.HlsPlayerClass,u,t,e);this.playerQueue.push(g),t.assetList[s]=e;let p=!0;const v=S=>{if(S.live){const I=new Error(`Interstitials MUST be VOD assets ${t}`),b={fatal:!0,type:Y.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},k=this.findEventIndex(t.identifier);this.handleAssetItemError(b,t,k,s,I.message);return}const A=S.edge-S.fragmentStart,L=e.duration;(p||L===null||A>L)&&(p=!1,this.log(`Interstitial asset "${c}" duration change ${L} > ${A}`),e.duration=A,this.updateSchedule())};g.on(m.LEVEL_UPDATED,(S,{details:A})=>v(A)),g.on(m.LEVEL_PTS_UPDATED,(S,{details:A})=>v(A)),g.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const E=(S,A)=>{const L=this.getAssetPlayer(c);if(L&&A.tracks){L.off(m.BUFFER_CODECS,E),L.tracks=A.tracks;const I=this.primaryMedia;this.bufferingAsset===L.assetItem&&I&&!L.media&&this.bufferAssetPlayer(L,I)}};g.on(m.BUFFER_CODECS,E);const y=()=>{const S=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${S}`),!S||!this.schedule)return;const A=this.getEventItem(t.identifier);A&&this.advanceAssetBuffering(A,S.assetItem)};g.on(m.BUFFERED_TO_END,y);const T=S=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;const A=this.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,A,S)};return g.once(m.MEDIA_ENDED,T(s)),g.once(m.PLAYOUT_LIMIT_REACHED,T(1/0)),g.on(m.ERROR,(S,A)=>{if(!this.schedule)return;const L=this.getAssetPlayer(c);if(A.details===R.BUFFER_STALLED_ERROR){if(L!=null&&L.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(A.details===R.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(A,t,this.findEventIndex(t.identifier),s,`Asset player error ${A.error} ${t}`)}),g.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;const S=new Error(`Asset player destroyed unexpectedly ${c}`),A={fatal:!0,type:Y.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:S};this.handleAssetItemError(A,t,this.findEventIndex(t.identifier),s,S.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Fe(e)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:s,event:t,player:g}),g}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,e)})}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(e!==-1){this.log(`reset asset player "${t}" after error`);const s=this.playerQueue[e];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(t,e){const s=this.getAssetPlayerQueueIndex(t);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${e&&Mt(e)}`),this.transferMediaFromPlayer(i,e),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,s,i,r){const{interstitial:a,assetItem:o,assetId:l}=t,h=a.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=o,d?.identifier!==l&&(d&&(this.clearAssetPlayer(d.identifier,s[i]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${h} ${Fe(o)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:e,event:a,schedule:s.slice(0),scheduleIndex:i,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var s;if(!this.schedule)return;const{interstitial:i,assetItem:r}=t,a=this.getEventItem(i.identifier);if(!a)return;if(t.loadSource(),this.setBufferingItem(a),this.bufferingAsset=r,t.bufferedInPlaceToEnd(this.primaryMedia,t.currentTime)){this.advanceAssetBuffering(a,r);return}const o=this.getBufferingPlayer();if(o===t)return;const l=i.appendInPlace;if(l&&o?.interstitial.appendInPlace===!1)return;const h=o?.tracks||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(l&&r!==this.playingAsset){if(!t.tracks){this.log(`Waiting for track info before buffering ${t}`);return}if(h&&!Wr(h,t.tracks)){const d=new Error(`Asset ${Fe(r)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),c={fatal:!0,type:Y.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},u=i.findAssetIndex(r);this.handleAssetItemError(c,i,this.findEventIndex(i.identifier),u,d.message);return}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,s=this.primaryMedia;if(!e||!s)return;const i=s.currentTime,r=e.findAssetIndex(t,i),a=t.assetList[r];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const l=o.currentTime||i-a.timelineStart,h=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+h} in ${o} ${t} (media.currentTime: ${i})`),l&&(h/s.playbackRate<.5||o.bufferedInPlaceToEnd(s,o.currentTime))&&o.hls){const d=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,d,r)}}}}advanceInPlace(t){const e=this.primaryMedia;if(e&&e.currentTime<t){const s=`advance currentTime to ${t}, duration: ${e.duration}`;e.duration>t?(this.log(s),e.currentTime=t):this.log(`Cannot ${s}`)}}handleAssetItemError(t,e,s,i,r){if(t.details===R.BUFFER_STALLED_ERROR)return;const a=e.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Fe(a)} ${t.error}`),!this.schedule)return;const o=a?.identifier||"",l=this.getAssetPlayerQueueIndex(o),h=this.playerQueue[l]||null,d=this.schedule.items,c=ht({},t,{fatal:!1,errorAction:Qe(!0),asset:a,assetListIndex:i,event:e,schedule:d,scheduleIndex:s,player:h});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,c),!t.fatal)return;const u=this.playingAsset,f=this.bufferingAsset,g=new Error(r);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!e.assetList.some(p=>!p.error))e.error=g;else for(let p=i;p<e.assetList.length;p++)this.resetAssetPlayer(e.assetList[p].identifier);this.updateSchedule(!0),e.error?this.primaryFallback(e):u?.identifier===o?this.advanceAfterAssetEnded(e,s,i):f?.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(t){const e=t.timelineStart,s=this.effectivePlayingItem,i=this.playingItem,r=this.seekableStart,a=this.hls.startPosition;let o=this.timelinePos;if(this.isInterstitial(s)){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${o} playing: ${Mt(s)} startPosition: ${a} seekableStart: ${r} error: ${t.error}`),o===-1&&(o=a),o=Math.max(o,r);const h=this.updateItem(s,o);this.itemsMatch(s,h)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(o===-1){this.checkStart();return}if(!this.schedule||i&&!this.isInterstitial(i))return;const l=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(l)}onAssetListLoaded(t,e){var s,i;const r=e.event,a=r.identifier,o=e.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;const l=r.timelineStart,h=r.duration;let d=0;o.forEach((g,p)=>{const v=parseFloat(g.DURATION);this.createAsset(r,p,d,l+d,v,g.URI),d+=v}),r.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${h}) ${r}`);const c=this.waitingItem,u=c?.event.identifier===a;this.updateSchedule();const f=(i=this.bufferingItem)==null?void 0:i.event;if(u){const g=this.findEventIndex(a),p=this.getEventItem(a);if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){r.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(p)}this.setSchedulePosition(g)}else if(f?.identifier===a){const g=r.assetList[0];if(g){const p=this.getAssetPlayer(g.identifier);if(f.appendInPlace){const v=this.primaryMedia;p&&v&&this.bufferAssetPlayer(p,v)}else p&&p.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case R.ASSET_LIST_PARSING_ERROR:case R.ASSET_LIST_LOAD_ERROR:case R.ASSET_LIST_LOAD_TIMEOUT:{const s=e.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case R.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}const i=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${i?.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}class Df{constructor(t){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var e;const{media:s}=this,i=this.levelDetails;if(!s||!i||!this.hls)return;this.currentTime=s.currentTime;const r=this.hls.config,a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:o,maxLiveSyncPlaybackRate:l}=r;if(!o||l===1||!i.live)return;const h=this.targetLatency;if(h===null)return;const d=a-h,c=Math.min(this.maxLatency,h+i.targetduration),u=d<c,f=$s(r)&&!!((e=this.hls.interstitialsManager)!=null&&(e=e.playingItem)!=null&&e.event);if(u&&d>.05&&this.forwardBufferLength>1&&!f){const g=Math.min(2,Math.max(1,l)),p=Math.round(2/(1+Math.exp(-.75*d-this.edgeStalled))*20)/20,v=Math.min(g,Math.max(1,p));this.changeMediaPlaybackRate(s,v)}else s.playbackRate!==1&&s.playbackRate!==0&&this.changeMediaPlaybackRate(s,1)},this.hls=t,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var t;const e=(t=this.hls)==null?void 0:t.config;if(!e)return 0;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const s=this.levelDetails;return s?e.liveMaxLatencyDurationCount*s.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||!this.hls)return null;const e=this.hls.config,{holdBack:s,partHoldBack:i,targetduration:r}=t,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:l}=e,h=this.hls.userConfig;let d=l&&i||s;(this._targetLatencyUpdated||h.liveSyncDuration||h.liveSyncDurationCount||d===0)&&(d=a!==void 0?a:o*r);const c=r;return d+Math.min(this.stallCount*e.liveSyncOnStallIncrease,c)}set targetLatency(t){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=t,this._targetLatencyUpdated=!0)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(t===null||e===null||!this.hls)return null;const s=this.levelDetails;if(s===null)return null;const i=s.edge,r=t-e-this.edgeStalled,a=i-s.totalduration,o=i-(this.hls.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,r),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(t===null||!this.hls)return 0;const e=(this.hls.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const s=t.buffered.length;return(s?t.buffered.end(s-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(m.ERROR,this.onError,this),t.on(m.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(m.ERROR,this.onError,this),t.off(m.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(t,e){var s;const i=this.hls,r=this.media||e.event.appendInPlace&&(i==null||(s=i.interstitialsManager)==null?void 0:s.playerQueue.reduce((a,o)=>a||o.media,null));i&&r&&r.playbackRate>1&&r.playbackRate<=i.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(r,1)}onError(t,e){var s;e.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var s,i;t.playbackRate!==e&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}const cl=500,kf=1e-6;class ul extends Ns{constructor(t,e,s){super(t,e,s,"subtitle-stream-controller",K.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(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)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;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)}startLoad(t,e){this.stopLoad(),this.state=P.IDLE,this.setInterval(cl),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){var s,i;const{frag:r,part:a,success:o}=e;if(!o)return;const l=(s=this.tracksBuffered)[i=r.level]||(s[i]=[]);if(!l)return;let h;const d=(a||r).start;for(let u=0;u<l.length;u++)if(d>=l[u].start&&d<=l[u].end){h=l[u];break}const c=d+(a||r).duration;if(h?h.end=c:(h={start:d,end:c},l.push(h)),!a||c>=r.end-kf){const u=this.fragmentTracker.fragBuffered(r);a&&u&&(u.range.subs={time:[{startPTS:r.start,endPTS:c}],partial:!0}),Et(r)&&!this.fragContextChanged(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,a),this.media&&this.tickImmediate()}}onBufferFlushing(t,e){const{startOffset:s,endOffset:i}=e;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;e.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{if(a)for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,K.SUBTITLE)}}onError(t,e){const s=e.frag;s?.type===K.SUBTITLE&&(e.details===R.FRAG_GAP&&this.fragmentTracker.addAsGap(s),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==P.STOPPED&&(this.state=P.IDLE))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){if(this.levels&&oo(this.levels,e)){this.levels=e.map(s=>new Pe(s));return}this.tracksBuffered=[],this.levels=e.map(s=>new Pe(s)),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,K.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.id,this.abortCurrentFrag(),!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];if(!(i!=null&&i.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==P.STOPPED&&this.setInterval(cl)}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:i,levels:r}=this,{details:a,id:o}=e;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const h=this.mainDetails;let d=0;if(a.live||(s=l.details)!=null&&s.live){if(a.deltaUpdateFailed)return;if(!h){this.startFragRequested=!1;return}if(l.details){var c;d=this.alignPlaylists(a,l.details,(c=this.levelLastLoaded)==null?void 0:c.details)}a.alignedSliding||(Fs(h,a,this),d=a.fragmentStart)}l.details=a,this.levelLastLoaded=l,h&&!this.startFragRequested&&this.setStartPosition(h,d),o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:e.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(t){const{frag:e,part:s,payload:i}=t;!s||!(i!=null&&i.byteLength)||!this.shouldDecrypt(e)||this.decryptPayload(i,e,s)}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t;this.fragContextChanged(e)||!(s!=null&&s.byteLength)||!this.shouldDecrypt(e)||this.decryptPayload(s,e,null)}shouldDecrypt(t){const e=t.decryptdata;return!!(e!=null&&e.key&&e.iv&&we(e.method))}decryptPayload(t,e,s){const i=e.decryptdata,r=performance.now();this.decrypter.decrypt(new Uint8Array(t),i.key.buffer,i.iv.buffer,xi(i.method)).then(a=>{this.fragContextChanged(e)||this.hls.trigger(m.FRAG_DECRYPTED,{frag:e,part:s,payload:a,stats:{tstart:r,tdecrypt:performance.now()}})}).catch(a=>{this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:e,part:s}),s||(this.warn(`${a.name}: ${a.message}`),this.state=P.IDLE)})}doTick(){if(this.state===P.IDLE&&this.levels){var t;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:s,levels:i}=this,r=i[s],a=r?.details;if(!a||this.waitForLive(r)||this.waitForCdnTuneIn(a)){this.startFragRequested=!1;return}const{config:o}=this,l=this.playhead,h=q.bufferedInfo(this.tracksBuffered[s]||[],l,o.maxBufferHole),{end:d,len:c}=h,u=Math.max(this.hls.maxBufferLength+a.levelTargetDuration,((t=this.hls.mainForwardBufferInfo)==null?void 0:t.len)||0);if(c>u||c&&!this.buffering)return;let f=this.getNextFragment(d,a);if(!f)return;if(Et(f)){var e;if(f.end===h.end)return;const g=f.sn-a.startSN,p=a.fragments[g-1];f.cc===p?.cc&&!((e=a.partList)!=null&&e.length)&&this.fragmentTracker.getState(p)===mt.NOT_LOADED&&(f=p)}this.loadFragment(f,r,d)}}loadFragment(t,e,s){const i=this.fragmentTracker.getState(t);(i===mt.NOT_LOADED||i===mt.PARTIAL)&&super.loadFragment(t,e,s)}get mediaBufferTimeRanges(){return new Pf(this.tracksBuffered[this.currentTrackId]||[])}}class Pf{constructor(t){this.buffered=void 0;const e=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return t[i][s]};this.buffered={get length(){return t.length},end(s){return e("end",s,t.length)},start(s){return e("start",s,t.length)}}}}const _f={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=n=>String.fromCharCode(_f[n]||n),qt=15,Xt=42,Cf={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},wf={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Of={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Mf={25:2,26:4,29:6,30:8,31:10,27:13,28:15},xf=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ff{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const s=typeof e=="function"?e():e;at.log(`${this.time} [${t}] ${s}`)}}}const Le=function(n){const t=[];for(let e=0;e<n.length;e++)t.push(n[e].toString(16));return t},Dr=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class gl{constructor(){this.styles=Dr}get foreground(){return this.styles.foreground}set foreground(t){const e=this.styles;this.styles={foreground:t,underline:e.underline,italics:e.italics,background:e.background,flash:e.flash}}get underline(){return this.styles.underline}set underline(t){const e=this.styles;this.styles={foreground:e.foreground,underline:t,italics:e.italics,background:e.background,flash:e.flash}}get italics(){return this.styles.italics}set italics(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:t,background:e.background,flash:e.flash}}get background(){return this.styles.background}set background(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:e.italics,background:t,flash:e.flash}}get flash(){return this.styles.flash}set flash(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:e.italics,background:e.background,flash:t}}reset(){this.styles=Dr}setStyles(t){const e=this.styles,s=Object.prototype.hasOwnProperty;this.styles={foreground:s.call(t,"foreground")?t.foreground:e.foreground,underline:s.call(t,"underline")?t.underline:e.underline,italics:s.call(t,"italics")?t.italics:e.italics,background:s.call(t,"background")?t.background:e.background,flash:s.call(t,"flash")?t.flash:e.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Nf{constructor(){this.uchar=" ",this.penState=new gl}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.styles=e.styles}setPenState(t){this.penState.styles=t.styles}copy(t){this.uchar=t.uchar,this.penState.styles=t.penState.styles}}class $f{constructor(t){this.chars=[],this.pos=0,this.currPenState=new gl,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<Xt;e++)this.chars.push(new Nf);this.logger=t}equals(t){const e=this.chars,s=t.chars;for(let i=0;i<Xt;i++){const r=e[i],a=s[i];if(r.uchar!==a.uchar)return!1;const o=r.penState.styles,l=a.penState.styles;if(o!==l&&(o.foreground!==l.foreground||o.underline!==l.underline||o.italics!==l.italics||o.background!==l.background||o.flash!==l.flash))return!1}return!0}copy(t){for(let e=0;e<Xt;e++)this.chars[e].copy(t.chars[e])}isEmpty(){const t=this.chars;for(let e=0;e<Xt;e++){const s=t[e];if(s.uchar!==" ")return!1;const i=s.penState.styles;if(i!==Dr&&(i.foreground!=="white"||i.underline||i.italics||i.background!=="black"||i.flash))return!1}return!0}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=Xt&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Xt-1)}moveCursor(t){const e=Math.min(this.pos+t,Xt);if(t>1)for(let s=this.pos+1;s<e;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=fl(t);if(this.pos>=Xt){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1)}clearFromPos(t){let e;for(e=t;e<Xt;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let s=0;s<Xt;s++){const i=this.chars[s].uchar;i!==" "&&(e=!1),t.push(i)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)}}class kr{constructor(t){this.rows=[],this.currRow=qt-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<qt;e++)this.rows.push(new $f(t));this.logger=t}reset(){for(let t=0;t<qt;t++)this.rows[t].clear();this.currRow=qt-1}equals(t){let e=!0;for(let s=0;s<qt;s++)if(!this.rows[s].equals(t.rows[s])){e=!1;break}return e}copy(t){for(let e=0;e<qt;e++){const s=this.rows[e].chars,i=t.rows[e].chars;for(let r=0;r<Xt;r++){const a=s[r],o=i[r];a.uchar=o.uchar,a.penState.styles=o.penState.styles}}}isEmpty(){let t=!0;for(let e=0;e<qt;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t),this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+ft(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let o=0;o<qt;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[r].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let h=0;h<this.nrRollUpRows;h++)this.rows[e-this.nrRollUpRows+h+1].copy(a.rows[r+h])}}this.currRow=e;const s=this.rows[this.currRow];if(t.indent!==null){const r=t.indent,a=Math.max(r-1,0);s.setCursor(t.indent),t.color=s.chars[a].penState.foreground}const i={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+ft(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let s="",i=-1;for(let r=0;r<qt;r++){const a=this.rows[r].getTextString();a&&(i=r+1,t?e.push("Row "+i+": '"+a+"'"):e.push(a.trim()))}return e.length>0&&(t?s="["+e.join(" | ")+"]":s=e.join(`
44
+ `)),s}getTextAndFormat(){return this.rows}}class Uf{constructor(t,e,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new kr(s),this.nonDisplayedMemory=new kr(s),this.lastOutputScreen=new kr(s),this.currRollUpRow=this.displayedMemory.rows[qt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[qt-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let s=0;s<t.length;s++)this.writeScreen.insertChar(t[s]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2===1,e.italics=t>=46,e.italics)e.foreground="white";else{const s=Math.floor(t/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=i[s]}this.logger.log(2,"MIDROW: "+ft(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;e!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=e:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class ml{constructor(t,e,s){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=Gf(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Ff,this.field=t,this.outputFilters=[null,e,s]}getHandler(t){return this.outputFilters[t]}setHandler(t,e){var s;this.outputFilters[t]=e,(s=this.channels[t])==null||s.setHandler(e)}getChannel(t){let e=this.channels[t];return e||(e=this.channels[t]=new Uf(this.field+t-1,this.outputFilters[t],this.logger)),e}addData(t,e){this.logger.time=t;for(let s=0;s<e.length;s+=2){const i=e[s]&127,r=e[s+1]&127;let a=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+Le([e[s],e[s+1]])+"] -> ("+Le([i,r])+")");const l=this.cmdHistory;if(i>=16&&i<=31){if(Bf(i,r,l)){si(null,null,l),this.logger.log(3,()=>"Repeated command ("+Le([i,r])+") is dropped");continue}si(i,r,this.cmdHistory),a=this.parseCmd(i,r),a||(a=this.parseMidrow(i,r)),a||(a=this.parsePAC(i,r)),a||(a=this.parseBackgroundAttributes(i,r))}else si(null,null,l);if(!a&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.getChannel(h).insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Le([i,r])+" orig: "+Le([e[s],e[s+1]]))}}parseCmd(t,e){const s=(t===20||t===28||t===21||t===29)&&e>=32&&e<=47,i=(t===23||t===31)&&e>=33&&e<=35;if(!(s||i))return!1;const r=t===20||t===21||t===23?1:2,a=this.getChannel(r);return t===20||t===21||t===28||t===29?e===32?a.ccRCL():e===33?a.ccBS():e===34?a.ccAOF():e===35?a.ccAON():e===36?a.ccDER():e===37?a.ccRU(2):e===38?a.ccRU(3):e===39?a.ccRU(4):e===40?a.ccFON():e===41?a.ccRDC():e===42?a.ccTR():e===43?a.ccRTD():e===44?a.ccEDM():e===45?a.ccCR():e===46?a.ccENM():e===47&&a.ccEOC():a.ccTO(e-32),this.currentChannel=r,!0}parseMidrow(t,e){let s=0;if((t===17||t===25)&&e>=32&&e<=47){if(t===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+Le([t,e])+")"),!0):!1}return!1}parsePAC(t,e){let s;const i=(t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127,r=(t===16||t===24)&&e>=64&&e<=95;if(!(i||r))return!1;const a=t<=23?1:2;return e>=64&&e<=95?s=a===1?Cf[t]:Of[t]:s=a===1?wf[t]:Mf[t],this.getChannel(a).setPAC(this.interpretPAC(s,e)),this.currentChannel=a,!0}interpretPAC(t,e){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:t};return e>95?s=e-96:s=e-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(t,e){let s,i=null,r=null;if(t>=25?(s=2,r=t-8):(s=1,r=t),r>=17&&r<=19){let a;r===17?a=e+80:r===18?a=e+112:a=e+144,this.logger.log(2,()=>"Special char '"+fl(a)+"' in channel "+s),i=[a]}else t>=32&&t<=127&&(i=e===0?[t]:[t,e]);return i&&this.logger.log(3,()=>"Char codes = "+Le(i).join(",")),i}parseBackgroundAttributes(t,e){const s=(t===16||t===24)&&e>=32&&e<=47,i=(t===23||t===31)&&e>=45&&e<=47;if(!(s||i))return!1;let r;const a={};t===16||t===24?(r=Math.floor((e-32)/2),a.background=xf[r],e%2===1&&(a.background=a.background+"_semi")):e===45?a.background="transparent":(a.foreground="black",e===47&&(a.underline=!0));const o=t<=23?1:2;return this.getChannel(o).setBkgData(a),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}si(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const s=this.channels[e];s&&s.cueSplitAtTime(t)}}}function si(n,t,e){e.a=n,e.b=t}function Bf(n,t,e){return e.a===n&&e.b===t}function Gf(){return{a:null,b:null}}class ii{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,s){(this.startTime===null||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class pl{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=vl(),this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(m.FRAG_LOADING,this.onFragLoading,this),t.on(m.FRAG_LOADED,this.onFragLoaded,this),t.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(m.BUFFER_APPENDED,this.onBufferAppended,this),t.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(m.FRAG_LOADING,this.onFragLoading,this),t.off(m.FRAG_LOADED,this.onFragLoaded,this),t.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(m.BUFFER_APPENDED,this.onBufferAppended,this),t.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new ii(this,"textTrack1"),e=new ii(this,"textTrack2"),s=new ii(this,"textTrack3"),i=new ii(this,"textTrack4");this.cea608Parser1=new ml(1,t,e),this.cea608Parser2=new ml(3,s,i)}addCues(t,e,s,i,r){let a=!1;for(let l=r.length;l--;){const h=r[l],d=Kf(h[0],h[1],e,s);if(d>=0&&(h[0]=Math.min(h[0],e),h[1]=Math.max(h[1],s),a=!0,d/(s-e)>.5))return}if(a||r.push([e,s]),this.config.renderTextTracksNatively){const l=this.cueCache[t];if(l){const h=this.Cues.newCue(null,e,s,i);h.length&&l.push.apply(l,h)}else{const h=this.captionsTracks[t].track;this.Cues.newCue(h,e,s,i)}}else{var o;const l=this.Cues.newCue(null,e,s,i),h=(o=this.captionsProperties[t])==null?void 0:o.media;this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:l,track:t,closedCaptions:h})}}onInitPtsFound(t,{id:e,timestampOffsets:s}){const{unparsedFrags:i}=this;e===K.MAIN&&(this.initPTS=s),i.length&&(this.unparsedFrags=[],i.forEach(r=>{this.initPTS[r.frag.cc]?this.onFragLoaded(m.FRAG_LOADED,r):this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:s,cueCache:i,media:r}=this,{label:a,languageCode:o}=e[t];r&&(i[t]=[],s[t]=yr(r,"captions",a,o,"hidden"))}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const s=e.label,i={_id:t,label:s,kind:"captions",default:e.media?!!e.media.default:!1,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}onMediaAttaching(t,e){this.media=e.media}onMediaDetaching(t,e){const s=!!e.transferMedia;if(this.media=null,!s){if(this.config.renderTextTracksNatively){const{captionsTracks:i,cueCache:r}=this;for(const a in i)i[a].remove(),delete r[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=vl(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(t,e){const s=e.subtitleTracks||[];if(s.length&&!this.config.renderTextTracksNatively&&!oo(this.tracks,s)){const i=s.map(r=>({label:r.name,kind:r.type.toLowerCase(),default:r.default,subtitleTrack:r}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:i})}this.tracks=s}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,a=this.captionsProperties[r];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return e?.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===K.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:h}=e.frag,d=(s=(i=e.part)==null?void 0:i.index)!=null?s:-1;r&&a&&(h!==o+1||h===o&&d!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=l,this.lastSn=h,this.lastPartIndex=d}}onFragLoaded(t,e){const{frag:s,payload:i}=e;if(s.level<this.tracks.length&&s.type===K.SUBTITLE){var r;if(i.byteLength||(r=s.initSegment)!=null&&(r=r.data)!=null&&r.byteLength){const a=s.decryptdata,o="stats"in e;if(a==null||!a.encrypted||o){const l=this.tracks[s.level],h=this.vttCCs;h[s.cc]||(h[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),l?.textCodec===gr?this._parseIMSC1(e):this._parseVTTs(e)}}else{const a="part"in e?e.part:null;this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:a,error:new Error("Empty subtitle payload")})}}}_parseIMSC1(t){const{frag:e,payload:s}=t,i="part"in t?t.part:null;if(!this.initPTS[e.cc]){this.unparsedFrags.push(t);return}const r=this.hls;Xo(s,this.initPTS[e.cc],a=>{this._appendCues(a,e.level),r.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e,part:i})},a=>{r.logger.log(`Cannot parse IMSC1 (sn: ${e.sn} @${e.start}): ${a}`),r.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,part:i,error:a})})}_parseVTTs(t){var e;const{frag:s,payload:i}=t,r="part"in t?t.part:null,{initPTS:a,unparsedFrags:o}=this,l=a.length-1;if(!a[s.cc]&&l===-1){o.push(t);return}const h=this.hls,d=(e=s.initSegment)==null?void 0:e.data,c=d?Gt(d,new Uint8Array(i)).buffer:i;Qu(c,this.initPTS[s.cc],this.vttCCs,s.cc,(r&&!d?r:s).start,u=>{this._appendCues(u,s.level),h.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s,part:r})},u=>{const f=u.message.startsWith("Missing initPTS");if(h.logger.log(`${f?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${s.sn} @${s.start}): ${u}`),f){o.push(t);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(t);h.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:r,error:u})})}_fallbackToIMSC1(t){const{frag:e,payload:s}=t,i=this.tracks[e.level];i.textCodec||Xo(s,this.initPTS[e.cc],()=>{i.textCodec=gr,this._parseIMSC1(t)},()=>{i.textCodec="wvtt"})}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){var i;const r=(i=this.tracks[e].trackNode)==null?void 0:i.track;if(!r||r.mode==="disabled")return;t.forEach(a=>Er(r,a))}else{const r=this.tracks[e];if(!r)return;const a=r.default?"default":"subtitles"+e;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:t,track:a,subtitleTrack:r})}}onFragDecrypted(t,e){const{frag:s}=e;s.type===K.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=e;if(!(s.type===K.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const a=i[r].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferAppended(t,e){if(this.config.renderTextTracksNatively){var s;const{type:i,timeRanges:r}=e;if(i==="video"&&(s=r[i])!=null&&s.length){const{captionsTracks:a,cueCache:o}=this;Object.keys(o).forEach(l=>{var h;const d=(h=a[l])==null?void 0:h.track;if(d){const c=o[l];for(let u=0;u<c.length;u++)Er(d,c[u])}delete o[l]})}}}onBufferFlushing(t,e){const{startOffset:s,endOffset:i,endOffsetSubtitles:r,type:a}=e,{media:o}=this;if(!(!o||o.currentTime<i)){if(!a||a==="video"){const{captionsTracks:l,cueCache:h}=this;Object.keys(l).forEach(d=>Tr(l[d].track,s,i)),Object.keys(h).forEach(d=>{const c=h[d];for(let u=c.length;u--;){const f=c[u];f.startTime>=s&&f.endTime<=i&&c.splice(u,1)}})}this.config.renderTextTracksNatively&&s===0&&r!==void 0&&this.tracks.forEach(l=>{var h;const d=(h=l.trackNode)==null?void 0:h.track;d&&Tr(d,s,r)})}}extractCea608Data(t){const e=[[],[]],s=t[0]&31;let i=2;for(let r=0;r<s;r++){const a=t[i++],o=127&t[i++],l=127&t[i++];if(!(o===0&&l===0)&&(4&a)!==0){const h=3&a;(h===0||h===1)&&(e[h].push(o),e[h].push(l))}}return e}}function Kf(n,t,e,s){return Math.min(t,s)-Math.max(n,e)}function vl(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Vf=/\s/,yl={newCue(n,t,e,s){const i=[];let r,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(r=s.rows[u],o=!0,l=0,h="",!r.isEmpty()){var c;for(let p=0;p<r.chars.length;p++)Vf.test(r.chars[p].uchar)&&o?l++:(h+=r.chars[p].uchar,o=!1);r.cueStartTime=t,t===e&&(e+=1e-4),l>=16?l--:l++;const f=Yo(h.trim()),g=fr(t,e,f);n!=null&&(c=n.cues)!=null&&c.getCueById(g)||(a=new d(t,e,f),a.id=g,a.line=u+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(a))}return n&&i.length&&(i.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),i.forEach(u=>Er(n,u))),i}};class Pr{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new us}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(t,e,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=s,this.loadInternal()}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,e=this.stats.retry;if(Ge(t,e,!0))this.retry(t);else{var s;at.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(t){const{context:e,stats:s}=this;this.retryDelay=hi(t,s.retry),s.retry++,at.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${e?.url}, retrying ${s.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}function El(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Hf=/(\d+)-(\d+)\/(\d+)/;class _r extends Pr{constructor(t){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=t.fetchSetup||qf}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:t,context:e,stats:s}=this;if(!t||!e)return;s.loading.first=0,s.loaded=0,s.aborted=!1,this.controller=new self.AbortController;const i=Yf(e,this.controller.signal),r=e.responseType==="arraybuffer",a=r?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=o&&$(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},t.timeout),(ns(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var d;this.response=h;const c=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(c-s.loading.start)),!h.ok){const{status:f,statusText:g}=h;throw new Xf(g||"fetch, bad network response",f,h)}s.loading.first=c,s.total=jf(h.headers)||s.total;const u=(d=this.callbacks)==null?void 0:d.onProgress;return u&&$(t.highWaterMark)?this.loadProgressively(h,s,e,t.highWaterMark,u):r?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{var d,c;const u=this.response;if(!u)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const f=h[a];f&&(s.loaded=s.total=f);const g={url:u.url,data:h,code:u.status},p=(d=this.callbacks)==null?void 0:d.onProgress;p&&!$(t.highWaterMark)&&p(s,e,h,u),(c=this.callbacks)==null||c.onSuccess(g,s,e,u)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const d=h&&h.code||0,c=h?h.message:null,u=t.loadPolicy.errorRetry,f=s.retry,g={url:e.url,data:void 0,code:d};if(Ge(u,f,!1,g))this.retry(u);else{var p;at.error(`${d} while loading ${e.url}`),(p=this.callbacks)==null||p.onError({code:d,text:c},e,h?h.details:null,s)}})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,s,i=0,r){const a=new wa,o=t.body.getReader(),l=()=>o.read().then(h=>{if(h.done)return a.dataLength&&r(e,s,a.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const d=h.value,c=d.length;return e.loaded+=c,c<i||a.dataLength?(a.push(d),a.dataLength>=i&&r(e,s,a.flush().buffer,t)):r(e,s,d.buffer,t),l()}).catch(()=>Promise.reject());return l()}}function Yf(n,t){const e={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(ht({},n.headers))};return n.rangeEnd&&e.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),e}function Wf(n){const t=Hf.exec(n);if(t)return parseInt(t[2])-parseInt(t[1])+1}function jf(n){const t=n.get("Content-Range");if(t){const s=Wf(t);if($(s))return s}const e=n.get("Content-Length");if(e)return parseInt(e)}function qf(n,t){return new self.Request(n.url,t)}class Xf extends Error{constructor(t,e,s){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=s}}const zf=(n,t,e)=>Math.max(t,Math.min(n,e)),Qf=/^age:\s*[\d.]+\s*$/im;class Cr extends Pr{constructor(t){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=t.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,t.readyState!==4&&(this.stats.aborted=!0,t.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r.call(this,s,e.url,e)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",e.url,!0),r.call(this,s,e.url,e)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,e,t)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},e,s,i)}):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const i=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(const o in i)t.setRequestHeader(o,i[o]);e.rangeEnd&&t.setRequestHeader("Range",`bytes=${e.rangeStart}-${e.rangeEnd-1}`),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&$(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:s}=this;if(!t||!e)return;const i=e.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const h=e.status,d=e.responseType==="text"?e.responseText:null;if(h>=200&&h<300){const g=d??e.response;if(g!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=e.responseType==="arraybuffer"?g.byteLength:g.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const v=(a=this.callbacks)==null?void 0:a.onProgress;v&&v(s,t,g,e);const E={url:e.responseURL,data:g,code:h};t.rangeEnd&&p!==t.rangeEnd-t.rangeStart&&at.warn(`Payload length ${p} does not match requested Range: bytes=${t.rangeStart}-${t.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(E,s,t,e);return}}const c=r.loadPolicy.errorRetry,u=s.retry,f={url:t.url,data:void 0,code:h};if(Ge(c,u,!1,f))this.retry(c);else{var l;at.error(`${h} while loading ${t.url}`),(l=this.callbacks)==null||l.onError({code:h,text:e.statusText},t,e,s)}}}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Qf.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const Jf={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Zf=W(W({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh: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,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:Cr,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:$i,requireKeySystemAccessOnStart:!1,reuseKeySessions:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2*1024*1024,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:Jf},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,streamController:nl,abrController:Cn,bufferController:Yn,capLevelController:ri,errorController:Fn,fpsController:Ko,id3TrackController:cf,gapController:hf,latencyController:Df},tg()),{},{subtitleStreamController:ul,subtitleTrackController:Zo,timelineController:pl,audioStreamController:ao,audioTrackController:lo,emeController:Ne,cmcdController:No,contentSteeringController:$o,iframeController:vf,interstitialsController:bf});function tg(){return{cueHandler:yl,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 eg(n,t,e){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(t.liveMaxUnchangedPlaylistRefresh!==void 0){const a=t.liveMaxUnchangedPlaylistRefresh,o=zf(a,2,1/0);o!==a&&e.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${a} to ${o}.`),t.liveMaxUnchangedPlaylistRefresh=o}const s=wr(n),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=t[o]===void 0,h=[];r.forEach(d=>{const c=`${a}Loading${d}`,u=t[c];if(u!==void 0&&l){h.push(c);const f=s[o].default;switch(t[o]={default:f},d){case"TimeOut":f.maxLoadTimeMs=u,f.maxTimeToFirstByteMs=u;break;case"MaxRetry":f.errorRetry.maxNumRetry=u,f.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":f.errorRetry.retryDelayMs=u,f.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=u,f.timeoutRetry.maxRetryDelayMs=u;break}}}),h.length&&e.warn(`hls.js config: "${h.join('", "')}" setting(s) are deprecated, use "${o}": ${ft(t[o])}`)}),W(W({},s),t)}function wr(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(wr):Object.keys(n).reduce((t,e)=>(t[e]=wr(n[e]),t),{}):n}function sg(n,t){const e=n.loader;e!==_r&&e!==Cr?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):El()&&(n.loader=_r,n.progressive=!0,n.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}class ig extends Ws{constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(m.LEVEL_LOADED,this.onLevelLoaded,this),t.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(m.FRAG_BUFFERED,this.onFragBuffered,this),t.on(m.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(m.LEVEL_LOADED,this.onLevelLoaded,this),t.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(m.FRAG_BUFFERED,this.onFragBuffered,this),t.off(m.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const s=this.hls.config.preferManagedMediaSource,i=[],r={},a={};let o=!1,l=!1,h=!1,d=!1;e.levels.forEach(c=>{const u=c.attrs,f=Al(c,s),{audioCodec:g,videoCodec:p,imageCodec:v,width:E,height:y}=c;if(!f){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}o||(o=!!(E&&y)),l||(l=!!p),h||(h=!!g),d||(d=!!v);const{CODECS:T,"FRAME-RATE":S,"HDCP-LEVEL":A,"PATHWAY-ID":L,RESOLUTION:I,"VIDEO-RANGE":b}=u,k=`${`${L||"."}-`}${c.bitrate}-${I}-${S}-${T}-${b}-${A}`;if(r[k])if(r[k].uri!==c.url&&!c.attrs["PATHWAY-ID"]){const D=a[k]+=1;c.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const C=this.createLevel(c);r[k]=C,i.push(C)}else c.iframes||(r[k].addGroupId("audio",u.AUDIO),r[k].addGroupId("text",u.SUBTITLES));else{const D=this.createLevel(c);r[k]=D,a[k]=1,i.push(D)}}),this.filterAndSortMediaOptions(i,e,o,l,h,d)}createLevel(t){const e=new Pe(t),s=t.supplemental;if(s!=null&&s.videoCodec&&!Sl(s.videoCodec,this.hls.config.preferManagedMediaSource)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),e.supportedResult=Sn(i,[])}return e}filterAndSortMediaOptions(t,e,s,i,r,a){var o;let l=[],h=[],d=t;const c=((o=e.stats)==null?void 0:o.parsing)||{},u=this.hls.config.preferManagedMediaSource;if((s||i)&&r&&(d=d.filter(({videoCodec:A,videoRange:L,width:I,height:b})=>(!!A||!!(I&&b))&&Bh(L))),i&&a&&(d=d.filter(A=>!A.imageCodec)),d.length===0){Promise.resolve().then(()=>{if(this.hls){let A="no level with compatible codecs found in manifest",L=A;e.levels.length&&(L=`one or more CODECS in variant not supported: ${ft(e.levels.map(b=>b.attrs.CODECS).filter((b,k,D)=>D.indexOf(b)===k))}`,this.warn(L),A+=` (${L})`);const I=new Error(A);this.hls.trigger(m.ERROR,{type:Y.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:I,reason:L})}}),c.end=performance.now();return}e.audioTracks&&(l=e.audioTracks.filter(A=>!A.audioCodec||Tl(A.audioCodec,u)),Il(l)),e.subtitles&&(h=e.subtitles,Il(h));const f=d.slice(0);d.sort((A,L)=>{if(A.attrs["HDCP-LEVEL"]!==L.attrs["HDCP-LEVEL"])return(A.attrs["HDCP-LEVEL"]||"")>(L.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&A.height!==L.height)return A.height-L.height;if(A.frameRate!==L.frameRate)return A.frameRate-L.frameRate;if(A.videoRange!==L.videoRange)return Rs.indexOf(A.videoRange)-Rs.indexOf(L.videoRange);if(A.videoCodec!==L.videoCodec){const I=vn(A.videoCodec),b=vn(L.videoCodec);if(I!==b)return b-I}if(A.uri===L.uri&&A.codecSet!==L.codecSet){const I=As(A.codecSet),b=As(L.codecSet);if(I!==b)return b-I}return A.averageBitrate!==L.averageBitrate?A.averageBitrate-L.averageBitrate:0});let g=f[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==f.length)){for(let A=0;A<f.length;A++)if(f[A].pathwayId===d[0].pathwayId){g=f[A];break}}this._levels=d;for(let A=0;A<d.length;A++)if(d[A]===g){var p;this._firstLevel=A;const L=g.bitrate,I=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${L}`),((p=this.hls.userConfig)==null?void 0:p.abrEwmaDefaultEstimate)===void 0){const b=Math.min(L,this.hls.config.abrEwmaDefaultEstimateMax);b>I&&I===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=b)}break}const v=e.iframeVariants.filter(A=>Al(A,u));this._iframeVariants=v;const E=r&&!i,y=this.hls.config,T=!!(y.audioStreamController&&y.audioTrackController),S={levels:d,audioTracks:l,subtitleTracks:h,iframeVariants:v,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:i,altAudio:T&&!E&&l.some(A=>!!A.url)};c.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,S)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(e.length===0)return;if(t<0||t>=e.length){const d=new Error("invalid level idx"),c=t<0;if(this.hls.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:t,fatal:c,error:d,reason:d.message}),c)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,a=e[t],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=a,s===t&&i&&r===o)return;this.log(`Switching to level ${t} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const l={level:t,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(m.LEVEL_SWITCHING,l);const h=a.details;if(!h||h.live){const d=this.switchParams(a.uri,i?.details,h);this.loadPlaylist(d)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){const t=this.hls.config.startLevel;return t!==void 0?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),s=t.filter(i=>e.indexOf(i)!==-1);if(t.length<1){this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);return}this.steering.pathwayPriority=s}}onError(t,e){e.fatal||!e.context||e.context.type===st.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(e.type===K.MAIN){const s=e.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[e.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(t,e){var s;const{level:i,details:r}=e,a=e.levelInfo;if(!a){var o;this.warn(`Invalid level index ${i}`),(o=e.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||e.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===e.details&&l.advanced&&(l=void 0),this.playlistLoaded(i,e,l)}else(s=e.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const s=this.getUrlWithDirectives(t.uri,e),i=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],a=t.details,o=a?.age;this.log(`Loading level index ${i}${e?.msn!==void 0?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){const e=this.currentLevelIndex;if(this.manualLevelIndex===-1&&t!==e&&t!==-1){const s=this.hls.config.abrSwitchInterval;if(s>0){const i=performance.now(),r=i-this.lastABRSwitchTime,a=s*1e3;if(this.lastABRSwitchTime>-1&&r<a){this.warn(`Preventing ABR level switch: ${e} -> ${t} (${Math.round(r)}ms < ${a}ms / ${s}s)`);return}this.lastABRSwitchTime=i,this.log(`Allowing ABR level switch: ${e} -> ${t} (${Math.round(r)}ms >= ${a}ms / ${s}s)`)}}this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(this._levels.length===1)return;const s=this._levels.filter((r,a)=>a!==t?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));Da(s),this._levels=s,this.currentLevelIndex>-1&&(e=this.currentLevel)!=null&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(m.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Tl(n,t){return je(n,"audio",t)}function Sl(n,t){return je(n,"video",t)}function Al(n,t){let{audioCodec:e,videoCodec:s}=n;e&&(n.audioCodec=e=Is(e,t)||void 0),s&&(s=n.videoCodec=Ch(s));const{unknownCodecs:i}=n;return!(i?.length||e&&!Tl(e,t)||s&&!Sl(s,t))}function Il(n){const t={};n.forEach(e=>{const s=e.groupId||"";e.id=t[s]=t[s]||0,t[s]++})}class rg extends xt{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyLoaderInfo){const i=this.keyLoaderInfo[s].loader;if(i){var e;if(t&&t!==((e=i.context)==null?void 0:e.frag.type))return;i.abort()}}}destroy(){for(const t in this.keyLoaderInfo){const e=this.keyLoaderInfo[t].loader;e&&e.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(t,e,s){return this.emeController?this.emeController.loadClear(t,e,s):null}load(t,e){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(s=>this.loadInternal(t,e,s)):this.loadInternal(t,e)}loadInternal(t,e,s){s&&t.setKeyFormat(s);const i=t.decryptdata;if(!i){const a=new Error(s?`Expected frag.decryptdata to be defined after setting format ${s}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(ye(t,R.KEY_LOAD_ERROR,a))}const r=t;switch(i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return i.keyFormat==="identity"?this.loadKeyHTTP(r):e?e.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(ye(t,R.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t){if(this.emeController&&this.config.emeEnabled){var e;if(!t.decryptdata.keyId&&(e=t.initSegment)!=null&&e.data){const s=ch(t.initSegment.data);if(s.length){let i=s[0];const r=t.decryptdata.uri;if(i.some(a=>a!==0))this.log(`Using keyId found in init segment ${It(i)} keyUri: ${r}`),ae.setKeyIdForUri(r,i);else{const a=ae.addKeyIdForUri(r);this.log(`Patching empty keyId with ${It(a)} keyUri: ${r}`),i=a}t.decryptdata.keyId=i}}return this.emeController.loadKey(t).then(()=>({frag:t,keyInfo:{decryptdata:t.decryptdata}}))}return Promise.reject(ye(t,R.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(t){const e=t.decryptdata,s=e.uri;if(!s)return Promise.reject(ye(t,R.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));const i=this.keyLoaderInfo[s];if(i){if(i.decryptdata.key)return e.key=i.decryptdata.key,i.keyLoadPromise=null,Promise.resolve({frag:t,keyInfo:i});if(i.keyLoadPromise)return i.keyLoadPromise.then(h=>(e.key=i.decryptdata.key,W(W({},h),{},{frag:t})))}this.log(`Loading${e.keyId?" keyId: "+It(e.keyId):""} URI: ${e.uri} from ${t.type} ${t.level}`);const r=this.config,a=r.loader,o=new a(r);t.keyLoader=o;const l=this.keyLoaderInfo[s]={decryptdata:e,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((h,d)=>{const c={type:st.KEY,keyInfo:l,frag:t,responseType:"arraybuffer",url:s},u=r.keyLoadPolicy.default,f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(p,v,E,y)=>{const{frag:T,keyInfo:S,url:A}=E;if(!T.decryptdata||S!==this.keyLoaderInfo[A])return this.resetLoader(E),d(ye(T,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),y));S.decryptdata.key=T.decryptdata.key=new Uint8Array(p.data),T.keyLoader=S.loader=S.keyLoadPromise=null,h({frag:T,keyInfo:S})},onError:(p,v,E,y)=>{this.resetLoader(v),d(ye(t,R.KEY_LOAD_ERROR,new Error(`HTTP Error ${p.code} loading key ${p.text}`),E,W({url:s,data:void 0},p)))},onTimeout:(p,v,E)=>{this.resetLoader(v),d(ye(t,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),E))},onAbort:(p,v,E)=>{this.resetLoader(v),d(ye(t,R.INTERNAL_ABORTED,new Error("key loading aborted"),E))}};o.load(c,f,g)})}resetLoader(t){const{frag:e,keyInfo:s,url:i}=t,r=s.loader;e.keyLoader===r&&(e.keyLoader=s.loader=s.keyLoadPromise=null),delete this.keyLoaderInfo[i],r&&r.destroy()}}function ye(n,t=R.KEY_LOAD_ERROR,e,s,i){return new ie({type:Y.NETWORK_ERROR,details:t,fatal:!1,frag:n,response:i,error:e,networkDetails:s||null})}function Ll(n){const{type:t}=n;switch(t){case st.AUDIO_TRACK:return K.AUDIO;case st.SUBTITLE_TRACK:return K.SUBTITLE;default:return K.MAIN}}function Or(n,t){let e=n.url;return(e===void 0||e.indexOf("data:")===0)&&(e=t.url),e}class ng{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(m.MANIFEST_LOADING,this.onManifestLoading,this),t.on(m.LEVEL_LOADING,this.onLevelLoading,this),t.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(m.MANIFEST_LOADING,this.onManifestLoading,this),t.off(m.LEVEL_LOADING,this.onLevelLoading,this),t.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,i=e.loader,r=s||i,a=new r(e);return this.loaders[t.type]=a,a}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:s}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:st.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:s,level:i,pathwayId:r,url:a,deliveryDirectives:o,levelInfo:l}=e;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:st.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:st.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(t,e){const{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=e;this.load({id:s,groupId:i,level:null,responseType:"text",type:st.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(t,e){const s=this.loaders[st.LEVEL];if(s){const i=s.context;i&&!e.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[st.LEVEL])}}load(t){var e;const s=this.hls.config;let i=this.getInternalLoader(t);if(i){const h=this.hls.logger,d=i.context;if(d?.levelOrTrack===t.levelOrTrack&&(d.url===t.url||d.deliveryDirectives&&!t.deliveryDirectives)){d.url===t.url?h.log(`[playlist-loader]: ignore ${t.url} ongoing request`):h.log(`[playlist-loader]: ignore ${t.url} in favor of ${d.url}`);return}h.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),i.abort()}let r;if(t.type===st.MANIFEST?r=s.manifestLoadPolicy.default:r=ht({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(t),$((e=t.deliveryDirectives)==null?void 0:e.part)){let h;if(t.type===st.LEVEL&&t.level!==null?h=this.hls.levels[t.level].details:t.type===st.AUDIO_TRACK&&t.id!==null?h=this.hls.audioTracks[t.id].details:t.type===st.SUBTITLE_TRACK&&t.id!==null&&(h=this.hls.subtitleTracks[t.id].details),h){const d=h.partTarget,c=h.targetduration;if(d&&c){const u=Math.max(d*3,c*.8)*1e3;r=ht({},r,{maxTimeToFirstByteMs:Math.min(u,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(h,d,c,u)=>{const f=this.getInternalLoader(c);this.resetInternalLoader(c.type);const g=h.data;d.parsing.start=performance.now(),zt.isMediaPlaylist(g)||c.type!==st.MANIFEST?this.handleTrackOrLevelPlaylist(h,d,c,u||null,f):this.handleMasterPlaylist(h,d,c,u)},onError:(h,d,c,u)=>{this.handleNetworkError(d,c,!1,h,u)},onTimeout:(h,d,c)=>{this.handleNetworkError(d,c,!0,void 0,h)}};i.load(t,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:s}=this.hls;(t||s)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,s,i){const r=this.hls,a=t.data,o=Or(t,s),l=zt.parseMasterPlaylist(a,o);if(l.playlistParsingError){e.parsing.end=performance.now(),this.handleManifestParsingError(t,s,l.playlistParsingError,i,e);return}const{contentSteering:h,levels:d,iframeVariants:c,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:p}=l;this.variableList=p,d.forEach(T=>{const{unknownCodecs:S}=T;if(S){const{preferManagedMediaSource:A}=this.hls.config;let{audioCodec:L,videoCodec:I}=T;for(let b=S.length;b--;){const k=S[b];je(k,"audio",A)?(T.audioCodec=L=L?`${L},${k}`:k,ke.audio[L.substring(0,4)]=2,S.splice(b,1)):je(k,"video",A)&&(T.videoCodec=I=I?`${I},${k}`:k,ke.video[I.substring(0,4)]=2,S.splice(b,1))}}});const{AUDIO:v=[],SUBTITLES:E,"CLOSED-CAPTIONS":y}=zt.parseMasterPlaylistMedia(a,o,l);v.length&&!v.some(T=>!T.url)&&d[0].audioCodec&&!d[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),v.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new vt({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:d,audioTracks:v,subtitles:E,iframeVariants:c,captions:y,contentSteering:h,url:o,stats:e,networkDetails:i,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:p})}handleTrackOrLevelPlaylist(t,e,s,i,r){const a=this.hls,{id:o,level:l,type:h}=s,d=Or(t,s),c=$(l)?l:$(o)?o:0,u=Ll(s),f=zt.parseLevelPlaylist(t.data,d,c,u,0,this.variableList);if(h===st.MANIFEST){const g={attrs:new vt({}),bitrate:0,details:f,name:"",url:d};f.requestScheduled=e.loading.start+La(f,0),a.trigger(m.MANIFEST_LOADED,{levels:[g],audioTracks:[],iframeVariants:[],url:d,stats:e,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,t,e,s,i,r)}handleManifestParsingError(t,e,s,i,r){this.hls.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:e.type===st.MANIFEST,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:i,stats:r})}handleNetworkError(t,e,s=!1,i,r){let a=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===st.LEVEL?a+=`: ${t.level} id: ${t.id}`:(t.type===st.AUDIO_TRACK||t.type===st.SUBTITLE_TRACK)&&(a+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=R.UNKNOWN,h=!1;const d=this.getInternalLoader(t);switch(t.type){case st.MANIFEST:l=s?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,h=!0;break;case st.LEVEL:l=s?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,h=!1;break;case st.AUDIO_TRACK:l=s?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,h=!1;break;case st.SUBTITLE_TRACK:l=s?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,h=!1;break}d&&this.resetInternalLoader(t.type);const c={type:Y.NETWORK_ERROR,details:l,fatal:h,url:t.url,loader:d,context:t,error:o,networkDetails:e,stats:r};if(i){let u=t.url;e&&"url"in e&&(u=e.url),c.response=W({url:u,data:void 0},i)}this.hls.trigger(m.ERROR,c)}handlePlaylistLoaded(t,e,s,i,r,a){const o=this.hls,{type:l,level:h,levelOrTrack:d,id:c,groupId:u,deliveryDirectives:f}=i,g=Or(e,i),p=Ll(i);let v=typeof i.level=="number"&&p===K.MAIN?h:void 0;d&&"iframes"in d&&d.iframes&&!t.iframesOnly&&(t.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),t.iframesOnly=!0);const E=t.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:e,context:i,level:v,parent:p,networkDetails:r,stats:s});return}t.playlistParsingError=null}if(!t.fragments.length){const y=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:Y.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:y,reason:y.message,response:e,context:i,level:v,parent:p,networkDetails:r,stats:s});return}switch(t.live&&a&&(a.getCacheAge&&(t.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),l){case st.MANIFEST:case st.LEVEL:if(v){if(!d)v=0;else if(d!==o.levels[v]){const y=o.levels.indexOf(d);y>-1&&(v=y)}}o.trigger(m.LEVEL_LOADED,{details:t,levelInfo:d||o.levels[0],level:v||0,id:c||0,stats:s,networkDetails:r,deliveryDirectives:f,withoutMultiVariant:l===st.MANIFEST,context:i});break;case st.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:t,track:d,id:c||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:f,context:i});break;case st.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:t,track:d,id:c||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:f,context:i});break}}}class oe{static get version(){return ts}static isMSESupported(){return Ir()}static isSupported(){return rl()}static getMediaSource(){return le()}static get Events(){return m}static get MetadataSchema(){return _t}static get ErrorTypes(){return Y}static get ErrorDetails(){return R}static get DefaultConfig(){return oe.defaultConfig?oe.defaultConfig:Zf}static set DefaultConfig(t){oe.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Vi,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const e=this.logger=$l(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),s=this.config=eg(oe.DefaultConfig,t,e);this.userConfig=t,s.progressive&&sg(s,e);const{streamController:i,abrController:r,bufferController:a,capLevelController:o,errorController:l,fpsController:h,id3TrackController:d,iframeController:c,gapController:u}=s,f=new l(this),g=this.abrController=new r(this),p=new id(this),v=s.interstitialsController,E=v?this.interstitialsController=new v(this,oe):null,y=a?this.bufferController=new a(this,p):null,T=o?this.capLevelController=new o(this):null,S=h?new h(this):null,A=s.cmcdController,L=A?this.cmcdController=new A(this):null,I=new ng(this),b=s.contentSteeringController,k=b?new b(this):null,D=this.levelController=new ig(this,k),C=d?new d(this):void 0,w=new rg(this.config,this.logger),N=this.streamController=new i(this,p,w),U=this.gapController=u?new u(this,p):void 0;T&&T.setStreamController(N);const G=[I,D,N];E&&G.splice(1,0,E),k&&G.splice(1,0,k),this.networkControllers=G;const M=[g];y&&M.push(y),U&&M.push(U),T&&M.push(T),S&&(S.setStreamController(N),M.push(S)),C&&M.push(C),M.push(p),this.audioTrackController=this.createController(s.audioTrackController,G);const F=s.audioStreamController;F&&G.push(this.audioStreamController=new F(this,p,w)),this.subtitleTrackController=this.createController(s.subtitleTrackController,G);const x=s.subtitleStreamController;x&&G.push(this.subtititleStreamController=new x(this,p,w)),this.createController(s.timelineController,M),w.emeController=this.emeController=this.createController(s.emeController,M),L&&M.push(L),this.latencyController=this.createController(s.latencyController,M),this.coreComponents=M,this.iframeController=c?new c(this,oe):void 0,G.push(f);const _=f.onErrorOut;typeof _=="function"&&this.on(m.ERROR,_,f),this.on(m.MANIFEST_LOADED,I.onManifestLoaded,I)}createController(t,e){if(t){const s=new t(this);return e&&e.push(s),s}return null}on(t,e,s=this){this._emitter.on(t,e,s)}once(t,e,s=this){this._emitter.once(t,e,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,s=this,i){this._emitter.off(t,e,s,i)}listeners(t){return this._emitter.listeners(t)}emit(t,e,s){return this._emitter.emit(t,e,s)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(s){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=t===m.ERROR;this.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:i,event:t,error:s}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(m.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,this.iframeController=void 0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const r=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(m.ERROR,{type:Y.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,s=e?t.media:t,i=e?t:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia");const t={};this.trigger(m.MEDIA_DETACHING,t),this._media=null,this.trigger(m.MEDIA_DETACHED,t)}transferMedia(){var t;this._media=null;const e=((t=this.bufferController)==null?void 0:t.transferMedia())||null,s={transferMedia:e};return this.trigger(m.MEDIA_DETACHING,s),this.trigger(m.MEDIA_DETACHED,s),e}loadSource(t){var e;this.stopLoad();const s=this.media,i=this._url,r=this._url=ai.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),s&&i&&(i!==r||(e=this.bufferController)!=null&&e.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),this.trigger(m.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(t,e),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!(this.started||!this.networkControllers));t++);}get loadingEnabled(){return this.started&&this.streamController.state!==P.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[K.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[K.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[K.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=this.started,s=t?.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&(s?this.startLoad(s):this.config.autoStartLoad||this.startLoad()))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=Xr()),t}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=this.capLevelController,s=!!t;e&&s!==this.config.capLevelToPlayerSize&&(s?e.startCapping():(e.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){Uh(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const s=t.length;for(let i=0;i<s;i++)if(t[i].maxBitrate>=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let i;if(e===-1&&t!=null&&t.length?i=t.length-1:i=e,s)for(let r=i;r--;){const a=t[r].attrs["HDCP-LEVEL"];if(a&&a<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var t;return((t=this.audioStreamController)==null?void 0:t.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return((e=this.audioTrackController)==null?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return((e=this.subtitleTrackController)==null?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get nextAudioTrack(){var t,e;return(t=(e=this.audioStreamController)==null?void 0:e.nextAudioTrack)!=null?t:-1}set nextAudioTrack(t){const{audioTrackController:e}=this;e&&(e.nextAudioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){var t,e;return(t=(e=this.latencyController)==null?void 0:e.liveSyncPosition)!=null?t:null}get latency(){var t;return((t=this.latencyController)==null?void 0:t.latency)||0}get maxLatency(){var t;return((t=this.latencyController)==null?void 0:t.maxLatency)||0}get targetLatency(){var t;return((t=this.latencyController)==null?void 0:t.targetLatency)||null}set targetLatency(t){this.latencyController&&(this.latencyController.targetLatency=t)}get drift(){var t;return((t=this.latencyController)==null?void 0:t.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){return this.levelController.iframeVariants||[]}createIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(t):null}createImageIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(t):null}getMediaDecodingInfo(t,e=this.allAudioTracks){const s=Dn(e);return An(t,s,navigator.mediaCapabilities)}}oe.defaultConfig=void 0;export{Cn as AbrController,vt as AttrList,ao as AudioStreamController,lo as AudioTrackController,Pr as BaseLoader,Ws as BasePlaylistController,oi as BaseSegment,Ns as BaseStreamController,Yn as BufferController,No as CMCDController,ri as CapLevelController,_s as ChunkMetadata,$o as ContentSteeringController,yl as Cues,Mi as DateRange,Ne as EMEController,bt as ErrorActionFlags,Fn as ErrorController,R as ErrorDetails,Y as ErrorTypes,m as Events,Ko as FPSController,_r as FetchLoader,Be as Fragment,oe as Hls,Xe as HlsSkip,ki as HlsUrlParameters,kt as KeySystemFormats,gt as KeySystems,Pe as Level,Bn as LevelDetails,ae as LevelKey,us as LoadStats,st as LoaderContextType,zt as M3U8Parser,_t as MetadataSchema,Dt as NetworkErrorAction,Nr as Part,K as PlaylistLevelType,ul as SubtitleStreamController,Zo as SubtitleTrackController,pl as TimelineController,Cr as XhrLoader,oe as default,El as fetchSupported,le as getMediaSource,Ir as isMSESupported,rl as isSupported,$i as requestMediaKeySystemAccess};
45
+ //# sourceMappingURL=hls-DAtZkTUi.js.map