@zeniai/web-cockpit-ui 2.0.62-dev → 2.0.62-next

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 (68) hide show
  1. package/dist/assets/CreditAgentRoutes-DF_JOjZH.js +4 -0
  2. package/dist/assets/Preview-Ciq7dXYi-C6UHJ-dG.js +1 -0
  3. package/dist/assets/ScreenRoutes-xhS5KnwE.js +185 -0
  4. package/dist/assets/SignInScreen-t_oI3_zX.js +1 -0
  5. package/dist/assets/__vite-browser-external-FmFgRqLi-Bre4IUow.js +1 -0
  6. package/dist/assets/{analytics-D2hq1pB4.js → analytics-D0nfjXSz.js} +1 -1
  7. package/dist/assets/{analyticsHelper-Duy8p9G0.js → analyticsHelper-BidapgRT.js} +1 -1
  8. package/dist/assets/core-Jhwj2cWt.js +12 -0
  9. package/dist/assets/dash.all.min-D0CkNF8g-0432FG2N.js +21 -0
  10. package/dist/assets/epic-CauFcFaa.js +2 -0
  11. package/dist/assets/hls-fD7GzkMr-CIetwlf6.js +40 -0
  12. package/dist/assets/index-C_rFPbpi-DsH_Uf7X.js +3299 -0
  13. package/dist/assets/index-CnaD4GI7.js +80686 -0
  14. package/dist/assets/index-CsCrKvDl-C675kzjP.js +2 -0
  15. package/dist/assets/index-DVThwdcI.css +1 -0
  16. package/dist/assets/lexical-CDqLTwdI.js +1 -0
  17. package/dist/assets/{liveblocks-DtPrLDJS.js → liveblocks-2qCiW-lz.js} +15 -15
  18. package/dist/assets/lottie-DsFjtNAa.js +1 -0
  19. package/dist/assets/mixin-XJuHfVsL-BC7tPWd5.js +43 -0
  20. package/dist/assets/mui-DK0XZjs0.js +9 -0
  21. package/dist/assets/react-3LeYKPCr-PCrhYwP8.js +6 -0
  22. package/dist/assets/react-6Tvfe2S2-AIR7GwlO.js +19 -0
  23. package/dist/assets/react-B2-P-PS--D8HoPiLp.js +19 -0
  24. package/dist/assets/react-CWXWcDMY-gRCgPi-n.js +17 -0
  25. package/dist/assets/react-CWt3gw2R-DR3R7x_6.js +21 -0
  26. package/dist/assets/react-CytUn6Kg-eWmFZ2Rf.js +22 -0
  27. package/dist/assets/react-G6j-OGKl-BmOQta5r.js +34 -0
  28. package/dist/assets/react-kuaGVSkA-DCIamgmw.js +7 -0
  29. package/dist/assets/recharts-CDqLTwdI.js +1 -0
  30. package/dist/assets/{sentry-DGdrGMts.js → sentry-Gbc14BJL.js} +2 -2
  31. package/dist/assets/utils-1Oo38JiV.js +36 -0
  32. package/dist/assets/{zeni-epic-state-BrXQ4qCB.js → zeni-epic-state-CvtUqjnz.js} +6 -6
  33. package/dist/index.html +1 -1
  34. package/package.json +1 -1
  35. package/dist/assets/CreditAgentRoutes-Dfd0Kd6I.js +0 -4
  36. package/dist/assets/Preview-IR8wZl18.js +0 -1
  37. package/dist/assets/ScreenRoutes-CWwjG5zs.js +0 -180
  38. package/dist/assets/SignInScreen-D3CJKpcD.js +0 -1
  39. package/dist/assets/core-Bd7Ijkb8.js +0 -12
  40. package/dist/assets/dash.all.min-DEn1t6rn.js +0 -21
  41. package/dist/assets/empty-BWs4yw6m.js +0 -1
  42. package/dist/assets/empty-Cuv-JavI.js +0 -1
  43. package/dist/assets/epic-BEruqsXy.js +0 -2
  44. package/dist/assets/hls-DifHSkbp.js +0 -40
  45. package/dist/assets/index-B4tJfZBM.js +0 -1
  46. package/dist/assets/index-BHnFF6Mj.js +0 -3304
  47. package/dist/assets/index-Ddpazk8i.js +0 -1
  48. package/dist/assets/index-ICxwMH4m.js +0 -1
  49. package/dist/assets/index-IYkmdsJO.js +0 -80176
  50. package/dist/assets/index-aPW1WLF7.js +0 -2
  51. package/dist/assets/index-aa1-CqLI.js +0 -1
  52. package/dist/assets/index-y98xvd7i.css +0 -1
  53. package/dist/assets/lexical-DUprPrXL.js +0 -21
  54. package/dist/assets/lottie-CxiyciuX.js +0 -2
  55. package/dist/assets/mixin-BPAPQfSE.js +0 -43
  56. package/dist/assets/mui-7i_-G9Wo.js +0 -9
  57. package/dist/assets/react-BP_tYIvG.js +0 -17
  58. package/dist/assets/react-BUCt2wJF.js +0 -21
  59. package/dist/assets/react-BmixicuU.js +0 -34
  60. package/dist/assets/react-D0Ona832.js +0 -19
  61. package/dist/assets/react-D1eycK3j.js +0 -7
  62. package/dist/assets/react-DZOlfJ3z.js +0 -6
  63. package/dist/assets/react-Da7CbJkT.js +0 -19
  64. package/dist/assets/react-Dy5N-1E1.js +0 -22
  65. package/dist/assets/recharts-ukUg8EgD.js +0 -65
  66. package/dist/assets/url-B6X-Y6dN.js +0 -6
  67. package/dist/assets/url-BHD2x5lb.js +0 -1
  68. package/dist/assets/utils-DOKAIlnQ.js +0 -36
@@ -0,0 +1,40 @@
1
+ (function(){try{var i=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new i.Error().stack;e&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[e]="6d4e87a3-95ec-41b4-bf51-f26550e2f7a8",i._sentryDebugIdIdentifier="sentry-dbid-6d4e87a3-95ec-41b4-bf51-f26550e2f7a8")}catch{}})();const U=Number.isFinite||function(i){return typeof i=="number"&&isFinite(i)},co=Number.isSafeInteger||function(i){return typeof i=="number"&&Math.abs(i)<=fo},fo=Number.MAX_SAFE_INTEGER||9007199254740991;let H=function(i){return i.NETWORK_ERROR="networkError",i.MEDIA_ERROR="mediaError",i.KEY_SYSTEM_ERROR="keySystemError",i.MUX_ERROR="muxError",i.OTHER_ERROR="otherError",i}({}),I=function(i){return i.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",i.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",i.KEY_SYSTEM_NO_SESSION="keySystemNoSession",i.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",i.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",i.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",i.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",i.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",i.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",i.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",i.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",i.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",i.MANIFEST_LOAD_ERROR="manifestLoadError",i.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",i.MANIFEST_PARSING_ERROR="manifestParsingError",i.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",i.LEVEL_EMPTY_ERROR="levelEmptyError",i.LEVEL_LOAD_ERROR="levelLoadError",i.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",i.LEVEL_PARSING_ERROR="levelParsingError",i.LEVEL_SWITCH_ERROR="levelSwitchError",i.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",i.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",i.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",i.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",i.FRAG_LOAD_ERROR="fragLoadError",i.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",i.FRAG_DECRYPT_ERROR="fragDecryptError",i.FRAG_PARSING_ERROR="fragParsingError",i.FRAG_GAP="fragGap",i.REMUX_ALLOC_ERROR="remuxAllocError",i.KEY_LOAD_ERROR="keyLoadError",i.KEY_LOAD_TIMEOUT="keyLoadTimeOut",i.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",i.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",i.BUFFER_APPEND_ERROR="bufferAppendError",i.BUFFER_APPENDING_ERROR="bufferAppendingError",i.BUFFER_STALLED_ERROR="bufferStalledError",i.BUFFER_FULL_ERROR="bufferFullError",i.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",i.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",i.ASSET_LIST_LOAD_ERROR="assetListLoadError",i.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",i.ASSET_LIST_PARSING_ERROR="assetListParsingError",i.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",i.INTERNAL_EXCEPTION="internalException",i.INTERNAL_ABORTED="aborted",i.ATTACH_MEDIA_ERROR="attachMediaError",i.UNKNOWN="unknown",i}({}),m=function(i){return i.MEDIA_ATTACHING="hlsMediaAttaching",i.MEDIA_ATTACHED="hlsMediaAttached",i.MEDIA_DETACHING="hlsMediaDetaching",i.MEDIA_DETACHED="hlsMediaDetached",i.MEDIA_ENDED="hlsMediaEnded",i.STALL_RESOLVED="hlsStallResolved",i.BUFFER_RESET="hlsBufferReset",i.BUFFER_CODECS="hlsBufferCodecs",i.BUFFER_CREATED="hlsBufferCreated",i.BUFFER_APPENDING="hlsBufferAppending",i.BUFFER_APPENDED="hlsBufferAppended",i.BUFFER_EOS="hlsBufferEos",i.BUFFERED_TO_END="hlsBufferedToEnd",i.BUFFER_FLUSHING="hlsBufferFlushing",i.BUFFER_FLUSHED="hlsBufferFlushed",i.MANIFEST_LOADING="hlsManifestLoading",i.MANIFEST_LOADED="hlsManifestLoaded",i.MANIFEST_PARSED="hlsManifestParsed",i.LEVEL_SWITCHING="hlsLevelSwitching",i.LEVEL_SWITCHED="hlsLevelSwitched",i.LEVEL_LOADING="hlsLevelLoading",i.LEVEL_LOADED="hlsLevelLoaded",i.LEVEL_UPDATED="hlsLevelUpdated",i.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",i.LEVELS_UPDATED="hlsLevelsUpdated",i.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",i.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",i.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",i.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",i.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",i.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",i.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",i.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",i.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",i.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",i.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",i.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",i.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",i.CUES_PARSED="hlsCuesParsed",i.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",i.INIT_PTS_FOUND="hlsInitPtsFound",i.FRAG_LOADING="hlsFragLoading",i.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",i.FRAG_LOADED="hlsFragLoaded",i.FRAG_DECRYPTED="hlsFragDecrypted",i.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",i.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",i.FRAG_PARSING_METADATA="hlsFragParsingMetadata",i.FRAG_PARSED="hlsFragParsed",i.FRAG_BUFFERED="hlsFragBuffered",i.FRAG_CHANGED="hlsFragChanged",i.FPS_DROP="hlsFpsDrop",i.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",i.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",i.ERROR="hlsError",i.DESTROYING="hlsDestroying",i.KEY_LOADING="hlsKeyLoading",i.KEY_LOADED="hlsKeyLoaded",i.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",i.BACK_BUFFER_REACHED="hlsBackBufferReached",i.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",i.ASSET_LIST_LOADING="hlsAssetListLoading",i.ASSET_LIST_LOADED="hlsAssetListLoaded",i.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",i.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",i.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",i.INTERSTITIAL_STARTED="hlsInterstitialStarted",i.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",i.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",i.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",i.INTERSTITIAL_ENDED="hlsInterstitialEnded",i.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",i.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",i.EVENT_CUE_ENTER="hlsEventCueEnter",i}({});var nt="manifest",et="level",Be="audioTrack",qe="subtitleTrack",Z="main",ke="audio",_e="subtitle";class St{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class go{constructor(e,t,s,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new St(e),this.fast_=new St(t),this.defaultTTFB_=r,this.ttfb_=new St(e)}update(e,t){const{slow_:s,fast_:r,ttfb_:n}=this;s.halfLife!==e&&(this.slow_=new St(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.fast_=new St(t,r.getEstimate(),r.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new St(e,n.getEstimate(),n.getTotalWeight()))}sample(e,t){const s=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/s;this.fast_.sample(s,r),this.slow_.sample(s,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function mo(i,e,t){return(e=function(s){var r=function(n,a){if(typeof n!="object"||!n)return n;var o=n[Symbol.toPrimitive];if(o!==void 0){var h=o.call(n,a);if(typeof h!="object")return h;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(n)}(s,"string");return typeof r=="symbol"?r:r+""}(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function ae(){return ae=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(i[s]=t[s])}return i},ae.apply(null,arguments)}function hr(i,e){var t=Object.keys(i);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(i);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(i,r).enumerable})),t.push.apply(t,s)}return t}function re(i){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?hr(Object(t),!0).forEach(function(s){mo(i,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(i,Object.getOwnPropertyDescriptors(t)):hr(Object(t)).forEach(function(s){Object.defineProperty(i,s,Object.getOwnPropertyDescriptor(t,s))})}return i}class Fe{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=lt,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const lt=function(){},po={trace:lt,debug:lt,log:lt,warn:lt,info:lt,error:lt};function vi(){return ae({},po)}function dr(i,e,t){return e[i]?e[i].bind(e):function(s,r){const n=self.console[s];return n?n.bind(self.console,`${r?"["+r+"] ":""}[${s}] >`):lt}(i,t)}const yi=vi(),ne=yi;function ut(i=!0){if(!(typeof self>"u"))return(i||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ur(i,e){const t=Object.keys(i),s=Object.keys(e),r=t.length,n=s.length;return!r||!n||r===n&&!t.some(a=>s.indexOf(a)===-1)}function we(i,e=!1){if(typeof TextDecoder<"u"){const h=new TextDecoder("utf-8").decode(i);if(e){const l=h.indexOf("\0");return l!==-1?h.substring(0,l):h}return h.replace(/\0/g,"")}const t=i.length;let s,r,n,a="",o=0;for(;o<t;){if(s=i[o++],s===0&&e)return a;if(s!==0&&s!==3)switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:r=i[o++],a+=String.fromCharCode((31&s)<<6|63&r);break;case 14:r=i[o++],n=i[o++],a+=String.fromCharCode((15&s)<<12|(63&r)<<6|63&n)}}return a}function Le(i){let e="";for(let t=0;t<i.length;t++){let s=i[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function Hn(i){return Uint8Array.from(i.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function vo(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var cr,fr={exports:{}},gr,mr,pr,vr,Ue,Ki=cr?fr.exports:(cr=1,gr=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,mr=/^(?=([^\/?#]*))\1([^]*)$/,pr=/(?:\/|^)\.(?=\/)/g,vr=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,fr.exports=Ue={buildAbsoluteURL:function(i,e,t){if(t=t||{},i=i.trim(),!(e=e.trim())){if(!t.alwaysNormalize)return i;var s=Ue.parseURL(i);if(!s)throw new Error("Error trying to parse base URL.");return s.path=Ue.normalizePath(s.path),Ue.buildURLFromParts(s)}var r=Ue.parseURL(e);if(!r)throw new Error("Error trying to parse relative URL.");if(r.scheme)return t.alwaysNormalize?(r.path=Ue.normalizePath(r.path),Ue.buildURLFromParts(r)):e;var n=Ue.parseURL(i);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&n.path[0]!=="/"){var a=mr.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:r.netLoc,path:null,params:r.params,query:r.query,fragment:r.fragment};if(!r.netLoc&&(o.netLoc=n.netLoc,r.path[0]!=="/"))if(r.path){var h=n.path,l=h.substring(0,h.lastIndexOf("/")+1)+r.path;o.path=Ue.normalizePath(l)}else o.path=n.path,r.params||(o.params=n.params,r.query||(o.query=n.query));return o.path===null&&(o.path=t.alwaysNormalize?Ue.normalizePath(r.path):r.path),Ue.buildURLFromParts(o)},parseURL:function(i){var e=gr.exec(i);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(i){for(i=i.split("").reverse().join("").replace(pr,"");i.length!==(i=i.replace(vr,"")).length;);return i.split("").reverse().join("")},buildURLFromParts:function(i){return i.scheme+i.netLoc+i.path+i.params+i.query+i.fragment}});class Hi{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var Oe="audio",Ge="video",Ei="audiovideo";class Vn{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,function(t,s){const r=Yn(t,s);r&&(r.enumerable=!0,Object.defineProperty(t,s,r))}(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let r;r=s.length===1?t?.byteRangeEndOffset||0:parseInt(s[1]),this._byteRange=[r,parseInt(s[0])+r]}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={[Oe]:null,[Ge]:null,[Ei]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Hi),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ki.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Oe]=null,e[Ge]=null,e[Ei]=null}}function ve(i){return i.sn!=="initSegment"}class qs extends Vn{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(U(e)&&U(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if((e=this._decryptdata)==null||!e.keyId){const s=Object.keys(t);if(s.length===1){const r=this._decryptdata=t[s[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=U(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),r=s.length;if(r>1||r===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){U(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}get ref(){return ve(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const r=t[e];!r||(s=this._decryptdata)!=null&&s.keyId||(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,r,n,a=!1){const{elementaryStreams:o}=this,h=o[e];h?(h.startPTS=Math.min(h.startPTS,t),h.endPTS=Math.max(h.endPTS,s),h.startDTS=Math.min(h.startDTS,r),h.endDTS=Math.max(h.endDTS,n)):o[e]={startPTS:t,endPTS:s,startDTS:r,endDTS:n,partial:a}}}class yo extends Vn{constructor(e,t,s,r,n){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,n),n&&(this.fragOffset=n.fragOffset+n.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function Yn(i,e){const t=Object.getPrototypeOf(i);if(t)return Object.getOwnPropertyDescriptor(t,e)||Yn(t,e)}const yr=Math.pow(2,32)-1,Eo=[].push,Wn={video:1,audio:2,id3:3,text:4};function Se(i){return String.fromCharCode.apply(null,i)}function jn(i,e){const t=i[e]<<8|i[e+1];return t<0?65536+t:t}function q(i,e){const t=qn(i,e);return t<0?4294967296+t:t}function Er(i,e){let t=q(i,e);return t*=Math.pow(2,32),t+=q(i,e+4),t}function qn(i,e){return i[e]<<24|i[e+1]<<16|i[e+2]<<8|i[e+3]}function ee(i,e){const t=[];if(!e.length)return t;const s=i.byteLength;for(let r=0;r<s;){const n=q(i,r),a=n>1?r+n:s;if(Se(i.subarray(r+4,r+8))===e[0])if(e.length===1)t.push(i.subarray(r+8,a));else{const o=ee(i.subarray(r+8,a),e.slice(1));o.length&&Eo.apply(t,o)}r=a}return t}function To(i){const e=[],t=i[0];let s=8;const r=q(i,s);s+=4;let n=0,a=0;t===0?(n=q(i,s),a=q(i,s+4),s+=8):(n=Er(i,s),a=Er(i,s+8),s+=16),s+=2;let o=i.length+a;const h=jn(i,s);s+=2;for(let l=0;l<h;l++){let d=s;const u=q(i,d);d+=4;const c=2147483647&u;if((2147483648&u)>>>31===1)return ne.warn("SIDX has hierarchical references (not supported)"),null;const f=q(i,d);d+=4,e.push({referenceSize:c,subsegmentDuration:f,info:{duration:f/r,start:o,end:o+c-1}}),o+=c,d+=4,s=d}return{earliestPresentationTime:n,timescale:r,version:t,referencesCount:h,references:e}}function Tr(i){const e=[],t=ee(i,["moov","trak"]);for(let s=0;s<t.length;s++){const r=t[s],n=ee(r,["tkhd"])[0];if(n){let a=n[0];const o=q(n,a===0?12:20),h=ee(r,["mdia","mdhd"])[0];if(h){a=h[0];const l=q(h,a===0?12:20),d=ee(r,["mdia","hdlr"])[0];if(d){const u=Se(d.subarray(8,12)),c={soun:Oe,vide:Ge}[u],f=So(ee(r,["mdia","minf","stbl","stsd"])[0]);c?(e[o]={timescale:l,type:c,stsd:f},e[c]=re({timescale:l,id:o},f)):e[o]={timescale:l,type:u,stsd:f}}}}}return ee(i,["moov","mvex","trex"]).forEach(s=>{const r=q(s,4),n=e[r];n&&(n.default={duration:q(s,12),flags:q(s,20)})}),e}function So(i){const e=i.subarray(8),t=e.subarray(86),s=Se(e.subarray(4,8));let r,n=s;const a=s==="enca"||s==="encv";if(a){const h=ee(e,[s])[0];ee(h.subarray(s==="enca"?28:78),["sinf"]).forEach(l=>{const d=ee(l,["schm"])[0];if(d){const u=Se(d.subarray(4,8));if(u==="cbcs"||u==="cenc"){const c=ee(l,["frma"])[0];c&&(n=Se(c))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const h=ee(t,["avcC"])[0];h&&h.length>3&&(n+="."+us(h[1])+us(h[2])+us(h[3]),r=ds(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const h=ee(e,[s])[0],l=ee(h.subarray(28),["esds"])[0];if(l&&l.length>7){let d=4;if(l[d++]!==3)break;d=Xs(l,d),d+=2;const u=l[d++];if(128&u&&(d+=2),64&u&&(d+=l[d++]),l[d++]!==4)break;d=Xs(l,d);const c=l[d++];if(c!==64||(n+="."+us(c),d+=12,l[d++]!==5))break;d=Xs(l,d);const f=l[d++];let g=(248&f)>>3;g===31&&(g+=1+((7&f)<<3)+((224&l[d])>>5)),n+="."+g}break}case"hvc1":case"hev1":{const h=ee(t,["hvcC"])[0];if(h&&h.length>12){const l=h[1],d=["","A","B","C"][l>>6],u=31&l,c=q(h,2),f=(32&l)>>5?"H":"L",g=h[12],p=h.subarray(6,12);n+="."+d+u,n+="."+function(y){let E=0;for(let T=0;T<32;T++)E|=(y>>T&1)<<31-T;return E>>>0}(c).toString(16).toUpperCase(),n+="."+f+g;let v="";for(let y=p.length;y--;){const E=p[y];(E||v)&&(v="."+E.toString(16).toUpperCase()+v)}n+=v}r=ds(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=ds(n,t)||n;break;case"vp09":{const h=ee(t,["vpcC"])[0];if(h&&h.length>6){const l=h[4],d=h[5],u=h[6]>>4&15;n+="."+Ye(l)+"."+Ye(d)+"."+Ye(u)}break}case"av01":{const h=ee(t,["av1C"])[0];if(h&&h.length>2){const l=h[1]>>>5,d=31&h[1],u=h[2]>>>7?"H":"M",c=(64&h[2])>>6,f=(32&h[2])>>5,g=l===2&&c?f?12:10:c?10:8,p=(16&h[2])>>4,v=(8&h[2])>>3,y=(4&h[2])>>2,E=3&h[2];n+="."+l+"."+Ye(d)+u+"."+Ye(g)+"."+p+"."+v+y+E+"."+Ye(1)+"."+Ye(1)+"."+Ye(1)+"."+0,r=ds("dav1",t)}break}}return{codec:n,encrypted:a,supplemental:r}}function ds(i,e){const t=ee(e,["dvvC"]),s=t.length?t[0]:ee(e,["dvcC"])[0];if(s){const r=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return i+"."+Ye(r)+"."+Ye(n)}}function Xs(i,e){const t=e+5;for(;128&i[e++]&&e<t;);return e}function us(i){return("0"+i.toString(16).toUpperCase()).slice(-2)}function Ye(i){return(i<10?"0":"")+i}function Xn(i,e){ee(i,["moov","trak"]).forEach(t=>{const s=ee(t,["mdia","minf","stbl","stsd"])[0];if(!s)return;const r=s.subarray(8);let n=ee(r,["enca"]);const a=n.length>0;a||(n=ee(r,["encv"])),n.forEach(o=>{ee(a?o.subarray(28):o.subarray(78),["sinf"]).forEach(h=>{const l=zn(h);l&&e(l,a)})})})}function zn(i){const e=ee(i,["schm"])[0];if(e){const t=Se(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=ee(i,["schi","tenc"])[0];if(s)return s}}}function Ne(i,e){const t=new Uint8Array(i.length+e.length);return t.set(i),t.set(e,i.length),t}function Sr(i,e){const t=[],s=e.samples,r=e.timescale,n=e.id;let a=!1;return ee(s,["moof"]).map(o=>{const h=o.byteOffset-8;ee(o,["traf"]).map(l=>{const d=ee(l,["tfdt"]).map(u=>{const c=u[0];let f=q(u,4);return c===1&&(f*=Math.pow(2,32),f+=q(u,8)),f/r})[0];return d!==void 0&&(i=d),ee(l,["tfhd"]).map(u=>{const c=q(u,4),f=16777215&q(u,0);let g=0;const p=!!(16&f);let v=0;const y=!!(32&f);let E=8;c===n&&(1&f&&(E+=8),2&f&&(E+=4),8&f&&(g=q(u,E),E+=4),p&&(v=q(u,E),E+=4),y&&(E+=4),e.type==="video"&&(a=Vs(e.codec)),ee(l,["trun"]).map(T=>{const A=T[0],L=16777215&q(T,0),b=!!(1&L);let S=0;const k=!!(4&L),D=!!(256&L);let P=0;const O=!!(512&L);let N=0;const B=!!(1024&L),F=!!(2048&L);let w=0;const _=q(T,4);let $=8;b&&(S=q(T,$),$+=4),k&&($+=4);let x=S+h;for(let C=0;C<_;C++){if(D?(P=q(T,$),$+=4):P=g,O?(N=q(T,$),$+=4):N=v,B&&($+=4),F&&(w=A===0?q(T,$):qn(T,$),$+=4),e.type===Ge){let M=0;for(;M<N;){const V=q(s,x);x+=4,Lo(a,s[x])&&Vi(s.subarray(x,x+V),a?2:1,i+w/r,t),x+=V,M+=V+4}}i+=P/r}}))})})}),t}function Vs(i){if(!i)return!1;const e=i.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Lo(i,e){if(i){const t=e>>1&63;return t===39||t===40}return(31&e)===6}function Vi(i,e,t,s){const r=Qn(i);let n=0;n+=e;let a=0,o=0,h=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;h=r[n++],a+=h}while(h===255);o=0;do{if(n>=r.length)break;h=r[n++],o+=h}while(h===255);const l=r.length-n;let d=n;if(o<l)n+=o;else if(o>l){ne.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(r[d++]===181){const u=jn(r,d);if(d+=2,u===49){const c=q(r,d);if(d+=4,c===1195456820){const f=r[d++];if(f===3){const g=r[d++],p=64&g,v=p?2+3*(31&g):0,y=new Uint8Array(v);if(p){y[0]=g;for(let E=1;E<v;E++)y[E]=r[d++]}s.push({type:f,payloadType:a,pts:t,bytes:y})}}}}}else if(a===5&&o>16){const u=[];for(let g=0;g<16;g++){const p=r[d++].toString(16);u.push(p.length==1?"0"+p:p),g!==3&&g!==5&&g!==7&&g!==9||u.push("-")}const c=o-16,f=new Uint8Array(c);for(let g=0;g<c;g++)f[g]=r[d++];s.push({payloadType:a,pts:t,uuid:u.join(""),userData:we(f),userDataBytes:f})}}}function Qn(i){const e=i.byteLength,t=[];let s=1;for(;s<e-2;)i[s]===0&&i[s+1]===0&&i[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return i;const r=e-t.length,n=new Uint8Array(r);let a=0;for(s=0;s<r;a++,s++)a===t[0]&&(a++,t.shift()),n[s]=i[a];return n}function Ao(i,e,t){if(i.byteLength!==16)throw new RangeError("Invalid system id");let s,r;s=new Uint8Array,r=new Uint8Array;const n=new Uint8Array(4);return t.byteLength>0&&new DataView(n.buffer).setUint32(0,t.byteLength,!1),function(a,...o){const h=o.length;let l=8,d=h;for(;d--;)l+=o[d].byteLength;const u=new Uint8Array(l);for(u[0]=l>>24&255,u[1]=l>>16&255,u[2]=l>>8&255,u[3]=255&l,u.set(a,4),d=0,l=8;d<h;d++)u.set(o[d],l),l+=o[d].byteLength;return u}([112,115,115,104],new Uint8Array([0,0,0,0]),i,r,s,n,t)}function Ro(i){const e=i.getUint32(0),t=i.byteOffset,s=i.byteLength;if(s<e)return{offset:t,size:s};if(i.getUint32(4)!==1886614376)return{offset:t,size:e};const r=i.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const n=i.buffer,a=Le(new Uint8Array(n,t+12,16));let o=null,h=null,l=0;if(r===0)l=28;else{const u=i.getUint32(28);if(!u||s<32+16*u)return{offset:t,size:e};o=[];for(let c=0;c<u;c++)o.push(new Uint8Array(n,t+32+16*c,16));l=32+16*u}if(!l)return{offset:t,size:e};const d=i.getUint32(l);return e-32<d?{offset:t,size:e}:(h=new Uint8Array(n,t+l+4,d),{version:r,systemId:a,kids:o,data:h,offset:t,size:e})}const Zn=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Ut={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Yi(i,e){const t=Ut[e];return!!t&&!!t[i.slice(0,4)]}function ts(i,e,t=!0){return!i.split(",").some(s=>!Wi(s,e,t))}function Wi(i,e,t=!0){var s;const r=ut(t);return(s=r?.isTypeSupported(ss(i,e)))!=null&&s}function ss(i,e){return`${e}/mp4;codecs=${i}`}function Lr(i){if(i){const e=i.substring(0,4);return Ut.video[e]}return 2}function xs(i){const e=Zn();return i.split(",").reduce((t,s)=>{const r=e&&Vs(s)?9:Ut.video[s];return r?(2*r+t)/(t?3:2):(Ut.audio[s]+t)/(t?2:1)},0)}const zs={},Io=/flac|opus|mp4a\.40\.34/i;function Os(i,e=!0){return i.replace(Io,t=>function(s,r=!0){if(zs[s])return zs[s];const n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let o=0;o<n.length;o++){var a;if(Wi(n[o],"audio",r))return zs[s]=n[o],n[o];if(n[o]==="mp3"&&(a=ut(r))!=null&&a.isTypeSupported("audio/mpeg"))return""}return s}(t.toLowerCase(),e))}function Rs(i,e){if(i&&(i.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(i)!==-1)&&(Ar(i,"audio")||Ar(i,"video")))return i;if(e){const t=e.split(",");if(t.length>1){if(i){for(let s=t.length;s--;)if(t[s].substring(0,4)===i.substring(0,4))return t[s]}return t[0]}}return e||i}function Ar(i,e){return Yi(i,e)&&Wi(i,e)}function bo(i){if(i.startsWith("av01.")){const e=i.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return i}function Rr(i){const e=ut(i)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ti(i){return i.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const ko={supported:!1,smooth:!1,powerEfficient:!1},Jn={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function ea(i,e){return{supported:!1,configurations:e,decodingInfoResults:[ko],error:i}}function Do(i,e,t,s,r,n){const a=i.videoCodec,o=i.audioCodec?i.audioGroups:null,h=n?.audioCodec,l=n?.channels,d=l?parseInt(l):h?1/0:2;let u=null;if(o!=null&&o.length)try{u=o.length===1&&o[0]?e.groups[o[0]].channels:o.reduce((c,f)=>{if(f){const g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(p=>{c[p]=(c[p]||0)+g.channels[p]})}return c},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(c=>Vs(c))||i.width>1920&&i.height>1088||i.height>1920&&i.width>1088||i.frameRate>Math.max(s,30)||i.videoRange!=="SDR"&&i.videoRange!==t||i.bitrate>Math.max(r,8e6))||!!u&&U(d)&&Object.keys(u).some(c=>parseInt(c)>d)}function ta(i,e,t,s={}){const r=i.videoCodec;if(!r&&!i.audioCodec||!t)return Promise.resolve(Jn);const n=[],a=function(d){var u;const c=(u=d.videoCodec)==null?void 0:u.split(","),f=Ir(d),g=d.width||640,p=d.height||480,v=d.frameRate||30,y=d.videoRange.toLowerCase();return c?c.map(E=>{const T={contentType:ss(bo(E),"video"),width:g,height:p,bitrate:f,framerate:v};return y!=="sdr"&&(T.transferFunction=y),T}):[]}(i),o=a.length,h=function(d,u,c){var f;const g=(f=d.audioCodec)==null?void 0:f.split(","),p=Ir(d);return g&&d.audioGroups?d.audioGroups.reduce((v,y)=>{var E;const T=y?(E=u.groups[y])==null?void 0:E.tracks:null;return T?T.reduce((A,L)=>{if(L.groupId===y){const b=parseFloat(L.channels||"");g.forEach(S=>{const k={contentType:ss(S,"audio"),bitrate:c?Po(S,p):p};b&&(k.channels=""+b),A.push(k)})}return A},v):v},[]):[]}(i,e,o>0),l=h.length;for(let d=o||1*l||1;d--;){const u={type:"media-source"};if(o&&(u.video=a[d%o]),l){u.audio=h[d%l];const c=u.audio.bitrate;u.video&&c&&(u.video.bitrate-=c)}n.push(u)}if(r){const d=navigator.userAgent;if(r.split(",").some(u=>Vs(u))&&Zn())return Promise.resolve(ea(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${d})`),n))}return Promise.all(n.map(d=>{const u=function(c){let f="";const{audio:g,video:p}=c;return p&&(f+=`${Ti(p.contentType)}_r${p.height}x${p.width}f${Math.ceil(p.framerate)}${p.transferFunction||"sd"}_${Math.ceil(p.bitrate/1e5)}`),g&&(f+=`${p?"_":""}${Ti(g.contentType)}_c${g.channels}`),f}(d);return s[u]||(s[u]=t.decodingInfo(d))})).then(d=>({supported:!d.some(u=>!u.supported),configurations:n,decodingInfoResults:d})).catch(d=>({supported:!1,configurations:n,decodingInfoResults:[],error:d}))}function Po(i,e){if(e<=1)return 1;let t=128e3;return i==="ec-3"?t=768e3:i==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Ir(i){return 1e3*Math.ceil(Math.max(.9*i.bitrate,i.averageBitrate)/1e3)||1}const Si=["NONE","TYPE-0","TYPE-1",null],Is=["SDR","PQ","HLG"];var sa="",Co="YES",_o="v2";function br(i){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=i;return e&&s<e/2?t?_o:Co:sa}class kr{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Yt{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Dr(this._audioGroups,e)}hasSubtitleGroup(e){return Dr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Dr(i,e){return!(!e||!i)&&i.indexOf(e)!==-1}function wo(i,e){let t=!1,s=[];if(i&&(t=i!=="SDR",s=[i]),e){s=e.allowedVideoRanges||Is.slice(0);const r=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:r&&function(){if(typeof matchMedia=="function"){const n=matchMedia("(dynamic-range: high)"),a=matchMedia("bad query");if(n.media!==a.media)return n.matches===!0}return!1}(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const oe=(i,e)=>JSON.stringify(i,(t=>{const s=new WeakSet;return(r,n)=>{if(t&&(n=t(r,n)),typeof n=="object"&&n!==null){if(s.has(n))return;s.add(n)}return n}})(e));function Ke(i,e){ne.log(`[abr] start candidates with "${i}" ignored because ${e}`)}function ia(i){return i.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const r=t.channels||"2";return s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Pr(i){if(!i)return i;const{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}=i;return{lang:e,assocLang:t,characteristics:s,channels:r,audioCodec:n}}function He(i,e,t){if("attrs"in i){const s=e.indexOf(i);if(s!==-1)return s}for(let s=0;s<e.length;s++)if(pt(i,e[s],t))return s;return-1}function pt(i,e,t){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=i,h=i.forced;return(s===void 0||e.groupId===s)&&(r===void 0||e.name===r)&&(n===void 0||function(l,d="--"){return l.length===d.length?l===d:l.startsWith(d)||d.startsWith(l)}(n,e.lang))&&(n===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(h===void 0||e.forced===h)&&(!("characteristics"in i)||function(l,d=""){const u=l.split(","),c=d.split(",");return u.length===c.length&&!u.some(f=>c.indexOf(f)===-1)}(i.characteristics||"",e.characteristics))&&(t===void 0||t(i,e))}function ct(i,e){const{audioCodec:t,channels:s}=i;return!(t!==void 0&&(e.audioCodec||"").substring(0,4)!==t.substring(0,4)||s!==void 0&&s!==(e.channels||"2"))}function Cr(i,e,t){for(let s=e;s>-1;s--)if(t(i[s]))return s;for(let s=e+1;s<i.length;s++)if(t(i[s]))return s;return-1}function Ms(i,e){var t;return!!i&&i!==((t=e.loadLevelObj)==null?void 0:t.uri)}const ra=function(i,e){let t=0,s=i.length-1,r=null,n=null;for(;t<=s;){r=(t+s)/2|0,n=i[r];const a=e(n);if(a>0)t=r+1;else{if(!(a<0))return n;s=r-1}}return null};function Et(i,e,t=0,s=0,r=.005){let n=null;if(i){n=e[1+i.sn-e[0].sn]||null;const o=i.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),n&&i.level!==n.level&&n.end<=i.end&&(n=e[2+i.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(n=e[0]);if(n&&((!i||i.level===n.level)&&_r(t,s,n)===0||function(o,h,l){if(h&&h.start===0&&h.level<o.level&&(h.endPTS||0)>0){const d=h.tagList.reduce((u,c)=>(c[0]==="INF"&&(u+=parseFloat(c[1])),u),l);return o.start<=d}return!1}(n,i,Math.min(r,s))))return n;const a=ra(e,_r.bind(null,t,s));return!a||a===i&&n?n:a}function _r(i=0,e=0,t){if(t.start<=i&&t.start+t.duration>i)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=i?1:t.start-s>i&&t.start?-1:0}function xo(i,e,t){const s=1e3*Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return(t.endProgramDateTime||0)-s>i}function na(i,e,t){if(i&&i.startCC<=e&&i.endCC>=e){let s=i.fragments;const{fragmentHint:r}=i;let n;return r&&(s=s.concat(r)),ra(s,a=>a.cc<e?1:a.cc>e?-1:(n=a,a.end<=t?1:a.start>t?-1:0)),n||null}return null}function Fs(i){switch(i.details){case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_TIMEOUT:case I.LEVEL_LOAD_TIMEOUT:case I.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function aa(i){return i.details.startsWith("key")}function oa(i){return aa(i)&&!!i.frag&&!i.frag.decryptdata}function wr(i,e){const t=Fs(e);return i.default[(t?"timeout":"error")+"Retry"]}function ji(i,e){const t=i.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*i.retryDelayMs,i.maxRetryDelayMs)}function xr(i){return re(re({},i),{errorRetry:null,timeoutRetry:null})}function Ns(i,e,t,s){if(!i)return!1;const r=s?.code,n=e<i.maxNumRetry&&(function(a){return Li(a)||!!a&&(a<400||a>499)}(r)||!!t);return i.shouldRetry?i.shouldRetry(i,e,t,s,n):n}function Li(i){return i===0&&navigator.onLine===!1}var la=0,We=2,Oo=3,Us=5,Wt=0,bs=1,Or=2,Mr=4;function Lt(i){const e={action:la,flags:Wt};return i&&(e.resolved=!0),e}var zt="NOT_LOADED",ha="APPENDING",_t="PARTIAL",wt="OK";class Mo{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let r=s.length;r--;){const n=s[r];if(!n)break;if(n.start<=e&&e<=n.end&&n.loaded)return n}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:r}=this,n=Object.keys(r);for(let a=n.length;a--;){const o=r[n[a]];if(o?.body.type===t&&(!s||o.buffered)){const h=o.body;if(h.start<=e&&e<=h.end)return h}}return null}detectEvictedFragments(e,t,s,r,n){this.timeRanges&&(this.timeRanges[e]=t);const a=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(o=>{const h=this.fragments[o];if(!h||a>=h.body.sn)return;if(!h.buffered&&(!h.loaded||n))return void(h.body.type===s&&this.removeFragment(h.body));const l=h.range[e];l&&(l.time.length!==0?l.time.some(d=>{const u=!this.isTimeBuffered(d.startPTS,d.endPTS,t);return u&&this.removeFragment(h.body),u}):this.removeFragment(h.body))})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,r=At(s),n=this.fragments[r];if(!n||n.buffered&&s.gap)return;const a=!s.relurl;Object.keys(t).forEach(o=>{const h=s.elementaryStreams[o];if(!h)return;const l=t[o],d=a||h.partial===!0;n.range[o]=this.getBufferedTimes(s,e.part,d,l)}),n.loaded=null,Object.keys(n.range).length?(this.bufferedEnd(n,s),cs(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Fr(s,r=>r.fragment.sn>=e))}fragBuffered(e,t){const s=At(e);let r=this.fragments[s];!r&&t&&(r=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e))}getBufferedTimes(e,t,s,r){const n={time:[],partial:s},a=e.start,o=e.end,h=e.minEndPTS||o,l=e.maxStartPTS||a;for(let d=0;d<r.length;d++){const u=r.start(d)-this.bufferPadding,c=r.end(d)+this.bufferPadding;if(l>=u&&h<=c){n.time.push({startPTS:Math.max(a,r.start(d)),endPTS:Math.min(o,r.end(d))});break}if(a<c&&o>u){const f=Math.max(a,r.start(d)),g=Math.min(o,r.end(d));g>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:g}))}else if(o<=u)break}return n}getPartialFragment(e){let t,s,r,n=null,a=0;const{bufferPadding:o,fragments:h}=this;return Object.keys(h).forEach(l=>{const d=h[l];d&&cs(d)&&(s=d.body.start-o,r=d.body.end+o,e>=s&&e<=r&&(t=Math.min(e-s,r-e),a<=t&&(n=d.body,a=t)))}),n}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||cs(t))}getState(e){const t=At(e),s=this.fragments[t];return s?s.buffered?cs(s)?_t:wt:ha:zt}isTimeBuffered(e,t,s){let r,n;for(let a=0;a<s.length;a++){if(r=s.start(a)-this.bufferPadding,n=s.end(a)+this.bufferPadding,e>=r&&t<=n)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,r=t.part?null:t,n=At(s);this.fragments[n]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:r,timeRanges:n,type:a}=t;if(s.sn==="initSegment")return;const o=s.type;if(r){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(r)}this.timeRanges=n;const h=n[a];this.detectEvictedFragments(a,h,o,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=At(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let r=s.length;r--;){const n=t[s[r]];if(n?.body.type===e)return!0}return!1}hasParts(e){var t;return!((t=this.activePartLists[e])==null||!t.length)}removeFragmentsInRange(e,t,s,r,n){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const h=o.body;h.type!==s||r&&!h.gap||h.start<t&&h.end>e&&(o.buffered||n)&&this.removeFragment(h)})}removeFragment(e){const t=At(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const r=e.sn;this.activePartLists[e.type]=Fr(s,n=>n.fragment.sn!==r)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}}function cs(i){var e,t,s;return i.buffered&&!!(i.body.gap||(e=i.range.video)!=null&&e.partial||(t=i.range.audio)!=null&&t.partial||(s=i.range.audiovideo)!=null&&s.partial)}function At(i){return`${i.type}_${i.level}_${i.sn}`}function Fr(i,e){return i.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var as=0,qi=1;class Fo{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case as:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case qi:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class No{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let r=0;r<4;r++)s[r]=t.getUint32(4*r);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,r=s[0],n=s[1],a=s[2],o=s[3],h=this.invSubMix,l=h[0],d=h[1],u=h[2],c=h[3],f=new Uint32Array(256);let g=0,p=0,v=0;for(v=0;v<256;v++)f[v]=v<128?v<<1:v<<1^283;for(v=0;v<256;v++){let y=p^p<<1^p<<2^p<<3^p<<4;y=y>>>8^255&y^99,e[g]=y,t[y]=g;const E=f[g],T=f[E],A=f[T];let L=257*f[y]^16843008*y;r[g]=L<<24|L>>>8,n[g]=L<<16|L>>>16,a[g]=L<<8|L>>>24,o[g]=L,L=16843009*A^65537*T^257*E^16843008*g,l[y]=L<<24|L>>>8,d[y]=L<<16|L>>>16,u[y]=L<<8|L>>>24,c[y]=L,g?(g=E^f[f[f[A^E]]],p^=f[f[p]]):g=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,r=0;for(;r<t.length&&s;)s=t[r]===this.key[r],r++;if(s)return;this.key=t;const n=this.keySize=t.length;if(n!==4&&n!==6&&n!==8)throw new Error("Invalid aes key size="+n);const a=this.ksRows=4*(n+6+1);let o,h;const l=this.keySchedule=new Uint32Array(a),d=this.invKeySchedule=new Uint32Array(a),u=this.sBox,c=this.rcon,f=this.invSubMix,g=f[0],p=f[1],v=f[2],y=f[3];let E,T;for(o=0;o<a;o++)o<n?E=l[o]=t[o]:(T=E,o%n===0?(T=T<<8|T>>>24,T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[255&T],T^=c[o/n|0]<<24):n>6&&o%n===4&&(T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[255&T]),l[o]=E=(l[o-n]^T)>>>0);for(h=0;h<a;h++)o=a-h,T=3&h?l[o]:l[o-4],d[h]=h<4||o<=4?T:g[u[T>>>24]]^p[u[T>>>16&255]]^v[u[T>>>8&255]]^y[u[255&T]],d[h]=d[h]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,s){const r=this.keySize+6,n=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,h=o[0],l=o[1],d=o[2],u=o[3],c=this.uint8ArrayToUint32Array_(s);let f=c[0],g=c[1],p=c[2],v=c[3];const y=new Int32Array(e),E=new Int32Array(y.length);let T,A,L,b,S,k,D,P,O,N,B,F,w,_;const $=this.networkToHostOrderSwap;for(;t<y.length;){for(O=$(y[t]),N=$(y[t+1]),B=$(y[t+2]),F=$(y[t+3]),S=O^n[0],k=F^n[1],D=B^n[2],P=N^n[3],w=4,_=1;_<r;_++)T=h[S>>>24]^l[k>>16&255]^d[D>>8&255]^u[255&P]^n[w],A=h[k>>>24]^l[D>>16&255]^d[P>>8&255]^u[255&S]^n[w+1],L=h[D>>>24]^l[P>>16&255]^d[S>>8&255]^u[255&k]^n[w+2],b=h[P>>>24]^l[S>>16&255]^d[k>>8&255]^u[255&D]^n[w+3],S=T,k=A,D=L,P=b,w+=4;T=a[S>>>24]<<24^a[k>>16&255]<<16^a[D>>8&255]<<8^a[255&P]^n[w],A=a[k>>>24]<<24^a[D>>16&255]<<16^a[P>>8&255]<<8^a[255&S]^n[w+1],L=a[D>>>24]<<24^a[P>>16&255]<<16^a[S>>8&255]<<8^a[255&k]^n[w+2],b=a[P>>>24]<<24^a[S>>16&255]<<16^a[k>>8&255]<<8^a[255&D]^n[w+3],E[t]=$(T^f),E[t+1]=$(b^g),E[t+2]=$(L^p),E[t+3]=$(A^v),f=O,g=N,p=B,v=F,t+=4}return E.buffer}}class Uo{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=function(t){switch(t){case as:return"AES-CBC";case qi:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class Xi{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const 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:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function(r){const n=r.byteLength,a=n&&new DataView(r.buffer).getUint8(n-1);return a?r.slice(0,n-a):r}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,r){return this.useSoftware?new Promise((n,a)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,r);const h=this.flush();h?n(h.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,r)}softwareDecrypt(e,t,s,r){const{currentIV:n,currentResult:a,remainderData:o}=this;if(r!==as||t.byteLength!==16)return ne.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Ne(o,e),this.remainderData=null);const h=this.getValidChunk(e);if(!h.length)return null;n&&(s=n);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new No),l.expandKey(t);const d=a;return this.currentResult=l.decrypt(h.buffer,0,s),this.currentIV=h.slice(-16).buffer,d||null}webCryptoDecrypt(e,t,s,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,r));this.key=t,this.fastAesKey=new Uo(this.subtle,t,r)}return this.fastAesKey.expandKey().then(n=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Fo(this.subtle,new Uint8Array(s),r).decrypt(e.buffer,n)):Promise.reject(new Error("web crypto not initialized"))).catch(n=>(ne.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(e,t,s,r)))}onWebCryptoError(e,t,s,r){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,r);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%16;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(ne.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Nr=Math.pow(2,17);class $o{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new tt({type:H.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,h)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(g=>g[0]==="GAP"))return void h($r(e));e.gap=!1}const l=this.loader=n?new n(r):new a(r),d=Ur(e);e.loader=l;const u=xr(r.fragLoadPolicy.default),c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Nr};e.stats=l.stats;const f={onSuccess:(g,p,v,y)=>{this.resetLoader(e,l);let E=g.data;v.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(E.slice(0,16)),E=E.slice(16)),o({frag:e,part:null,payload:E,networkDetails:y})},onError:(g,p,v,y)=>{this.resetLoader(e,l),h(new tt({type:H.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:re({url:s,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:v,stats:y}))},onAbort:(g,p,v)=>{this.resetLoader(e,l),h(new tt({type:H.NETWORK_ERROR,details:I.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:v,stats:g}))},onTimeout:(g,p,v)=>{this.resetLoader(e,l),h(new tt({type:H.NETWORK_ERROR,details:I.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:v,stats:g}))}};t&&(f.onProgress=(g,p,v,y)=>t({frag:e,part:null,payload:v,networkDetails:y})),l.load(d,c,f)})}loadPart(e,t,s){this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,h)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void h($r(e,t));const l=this.loader=n?new n(r):new a(r),d=Ur(e,t);e.loader=l;const u=xr(r.fragLoadPolicy.default),c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Nr};t.stats=l.stats,l.load(d,c,{onSuccess:(f,g,p,v)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const y={frag:e,part:t,payload:f.data,networkDetails:v};s(y),o(y)},onError:(f,g,p,v)=>{this.resetLoader(e,l),h(new tt({type:H.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:re({url:d.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:v}))},onAbort:(f,g,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),h(new tt({type:H.NETWORK_ERROR,details:I.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,l),h(new tt({type:H.NETWORK_ERROR,details:I.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${c.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,t){const s=e.stats,r=t.stats,n=r.total;if(s.loaded+=r.loaded,n){const h=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/n),h),d=(h-l)*Math.round(s.loaded/l);s.total=s.loaded+d}else s.total=Math.max(s.loaded,s.total);const a=s.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Ur(i,e=null){const t=e||i,s={frag:i,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},r=t.byteRangeStartOffset,n=t.byteRangeEndOffset;if(U(r)&&U(n)){var a;let h=r,l=n;if(i.sn==="initSegment"&&((o=(a=i.decryptdata)==null?void 0:a.method)==="AES-128"||o==="AES-256")){const d=n-r;d%16&&(l=n+(16-d%16)),r!==0&&(s.resetIV=!0,h=r-16)}s.rangeStart=h,s.rangeEnd=l}var o;return s}function $r(i,e){const t=new Error(`GAP ${i.gap?"tag":"attribute"} found`),s={type:H.MEDIA_ERROR,details:I.FRAG_GAP,fatal:!1,frag:i,error:t,networkDetails:null};return e&&(s.part=e),(e||i).stats.aborted=!0,new tt(s)}class tt extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class da extends Fe{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class zi{constructor(e,t,s,r=0,n=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=s,this.size=r,this.part=n,this.partial=a}}const Br={length:0,start:()=>0,end:()=>0};class z{static isBuffered(e,t){if(e){const s=z.getBuffered(e);for(let r=s.length;r--;)if(t>=s.start(r)&&t<=s.end(r))return!0}return!1}static bufferedRanges(e){if(e){const t=z.getBuffered(e);return z.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const r=z.bufferedRanges(e);if(r.length)return z.bufferedInfo(r,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((d,u)=>d.start-u.start||u.end-d.end);let r=-1,n=[];if(s)for(let d=0;d<e.length;d++){t>=e[d].start&&t<=e[d].end&&(r=d);const u=n.length;if(u){const c=n[u-1].end;e[d].start-c<s?e[d].end>c&&(n[u-1].end=e[d].end):n.push(e[d])}else n.push(e[d])}else n=e;let a,o=0,h=t,l=t;for(let d=0;d<n.length;d++){const u=n[d].start,c=n[d].end;if(r===-1&&t>=u&&t<=c&&(r=d),t+s>=u&&t<c)h=u,l=c,o=l-t;else if(t+s<u){a=u;break}}return{len:o,start:h||0,end:l||0,nextStart:a,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||Br}catch(t){return ne.log("failed to get media.buffered",t),Br}}}const ua=/\{\$([a-zA-Z0-9-_]+)\}/g;function Gr(i){return ua.test(i)}function Ai(i,e){if(i.variableList!==null||i.hasVariableRefs){const t=i.variableList;return e.replace(ua,s=>{const r=s.substring(2,s.length-1),n=t?.[r];return n===void 0?(i.playlistParsingError||(i.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),s):n})}return e}function Kr(i,e,t){let s,r,n=i.variableList;if(n||(i.variableList=n={}),"QUERYPARAM"in e){s=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(!a.has(s))throw new Error(`"${s}" does not match any query parameter in URI: "${t}"`);r=a.get(s)}catch(a){i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else s=e.NAME,r=e.VALUE;s in n?i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=r||""}function Bo(i,e,t){const s=e.IMPORT;if(t&&s in t){let r=i.variableList;r||(i.variableList=r={}),r[s]=t[s]}else i.playlistParsingError||(i.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const Go=/^(\d+)x(\d+)$/,Hr=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ce{constructor(e,t){typeof e=="string"&&(e=ce.parseAttrList(e,t)),ae(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const s=new Uint8Array(t.length/2);for(let r=0;r<t.length/2;r++)s[r]=parseInt(t.slice(2*r,2*r+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=!0,r),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Go.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const r={};for(Hr.lastIndex=0;(s=Hr.exec(e))!==null;){const n=s[1].trim();let a=s[2];const o=a.indexOf('"')===0&&a.lastIndexOf('"')===a.length-1;let h=!1;if(o)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":h=!0}if(t&&(o||h))a=Ai(t,a);else if(!h&&!o)switch(n){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":ne.warn(`${e}: attribute ${n} is missing quotes`)}r[n]=a}return r}}function Ko(i){return i!=="ID"&&i!=="CLASS"&&i!=="CUE"&&i!=="START-DATE"&&i!=="DURATION"&&i!=="END-DATE"&&i!=="END-ON-NEXT"}function Ho(i){return i==="SCTE35-OUT"||i==="SCTE35-IN"||i==="SCTE35-CMD"}class ca{constructor(e,t,s=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(r=t?.tagOrder)!=null?r:s,t){const n=t.attr;for(const a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){ne.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=ae(new ce({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const n=t?.endDate||new Date(this.attr["END-DATE"]);U(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(ne.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(U(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class==="com.apple.hls.interstitial"}get isValid(){return!!this.id&&!this._badValueForSameId&&U(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)}}class Vo{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return!!this.fragments.length&&U(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.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 e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function $s(i,e){return i.length===e.length&&!i.some((t,s)=>t!==e[s])}function Vr(i,e){return!i&&!e||!(!i||!e)&&$s(i,e)}function xt(i){return i==="AES-128"||i==="AES-256"||i==="AES-256-CTR"}function Qi(i){switch(i){case"AES-128":case"AES-256":return as;case"AES-256-CTR":return qi;default:throw new Error(`invalid full segment method ${i}`)}}function Zi(i){return Uint8Array.from(atob(i),e=>e.charCodeAt(0))}function Ri(i){return Uint8Array.from(unescape(encodeURIComponent(i)),e=>e.charCodeAt(0))}function fa(i){const e=function(t,s,r){const n=t[s];t[s]=t[r],t[r]=n};e(i,0,3),e(i,1,2),e(i,4,5),e(i,6,7)}function ga(i){const e=i.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),r=s[s.length-1].split(",");if(r.length===2){const n=r[0]==="base64",a=r[1];n?(s.splice(-1,1),t=Zi(a)):t=function(o){const h=Ri(o).subarray(0,16),l=new Uint8Array(16);return l.set(h,16-h.length),l}(a)}}return t}const Bs=typeof self<"u"?self:void 0;var fe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ji="org.w3.clearkey",Ys="com.apple.streamingkeydelivery",is="com.microsoft.playready",Qt="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function ks(i){switch(i){case Ys:return fe.FAIRPLAY;case is:return fe.PLAYREADY;case Qt:return fe.WIDEVINE;case Ji:return fe.CLEARKEY}}function Qs(i){switch(i){case fe.FAIRPLAY:return Ys;case fe.PLAYREADY:return is;case fe.WIDEVINE:return Qt;case fe.CLEARKEY:return Ji}}function jt(i){const{drmSystems:e,widevineLicenseUrl:t}=i,s=e?[fe.FAIRPLAY,fe.WIDEVINE,fe.PLAYREADY,fe.CLEARKEY].filter(r=>!!e[r]):[];return!s[fe.WIDEVINE]&&t&&s.push(fe.WIDEVINE),s}const ma=Bs!=null&&(Yr=Bs.navigator)!=null&&Yr.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Yr;function pa(i){const e=new Uint16Array(i.buffer,i.byteOffset,i.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),r=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(r){const n=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(n){const a=Zi(n).subarray(0,16);return fa(a),a}}return null}let Rt={};class dt{static clearKeyUriToKeyIdMap(){Rt={}}static setKeyIdForUri(e,t){Rt[e]=t}static addKeyIdForUri(e){const t=Object.keys(Rt).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),Rt[e]=s,s}constructor(e,t,s,r=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=r,this.iv=n,this.encrypted=!!e&&e!=="NONE",this.isCommonEncryption=this.encrypted&&!xt(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Hn(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&$s(e.keyFormatVersions,this.keyFormatVersions)&&Vr(e.iv,this.iv)&&Vr(e.keyId,this.keyId)}isSupported(){if(this.method){if(xt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Ys:case Qt:case is:case Ji:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(xt(this.method)){let n=this.iv;return n||(typeof e!="number"&&(ne.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),n=function(a){const o=new Uint8Array(16);for(let h=12;h<16;h++)o[h]=a>>8*(15-h)&255;return o}(e)),new dt(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){const n=Rt[this.uri];if(n&&!$s(this.keyId,n)&&dt.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=ga(this.uri);if(s)switch(this.keyFormat){case Qt:if(this.pssh=s,!this.keyId){const n=function(a){const o=[];if(a instanceof ArrayBuffer){const h=a.byteLength;let l=0;for(;l+32<h;){const d=Ro(new DataView(a,l));o.push(d),l+=d.size}}return o}(s.buffer);if(n.length){var r;const a=n[0];this.keyId=(r=a.kids)!=null&&r.length?a.kids[0]:null}}this.keyId||(this.keyId=Wr(t));break;case is:{const n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Ao(n,0,s),this.keyId=pa(s);break}default:{let n=s.subarray(0,16);if(n.length!==16){const a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=function(a){const o=a?.[Qt];return o?o.keyId:null}(t),n||(n=Wr(t),n||(n=Rt[this.uri])),n&&(this.keyId=n,dt.setKeyIdForUri(this.uri,n))}return this}}function Wr(i){const e=i?.[is];if(e){const t=ga(e.uri);if(t)return pa(t)}return null}const jr=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,qr=/#EXT-X-MEDIA:(.*)/g,Yo=/^#EXT(?:INF|-X-TARGETDURATION):/m,Zs=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Wo=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Xe{static findGroup(e,t){for(let s=0;s<e.length;s++){const r=e[s];if(r.id===t)return r}}static resolve(e,t){return Ki.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Yo.test(e)}static parseMasterPlaylist(e,t){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Gr(e)},r=[];if(jr.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=new Error("no EXTM3U delimiter"),s;let n;for(;(n=jr.exec(e))!=null;)if(n[1]){var a;const h=new ce(n[1],s),l=Ai(s,n[2]),d={attrs:h,bitrate:h.decimalInteger("BANDWIDTH")||h.decimalInteger("AVERAGE-BANDWIDTH"),name:h.NAME,url:Xe.resolve(l,t)},u=h.decimalResolution("RESOLUTION");u&&(d.width=u.width,d.height=u.height),Qr(h.CODECS,d);const c=h["SUPPLEMENTAL-CODECS"];c&&(d.supplemental={},Qr(c,d.supplemental)),(a=d.unknownCodecs)!=null&&a.length||r.push(d),s.levels.push(d)}else if(n[3]){const h=n[3],l=n[4];switch(h){case"SESSION-DATA":{const d=new ce(l,s),u=d["DATA-ID"];u&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[u]=d);break}case"SESSION-KEY":{const d=Xr(l,t,s);d.encrypted&&d.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(d)):ne.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${l}"`);break}case"DEFINE":Kr(s,new ce(l,s),t);break;case"CONTENT-STEERING":{const d=new ce(l,s);s.contentSteering={uri:Xe.resolve(d["SERVER-URI"],t),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=zr(l)}}const o=r.length>0&&r.length<s.levels.length;return s.levels=o?r:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,s){let r;const n={},a=s.levels,o={AUDIO:a.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:a.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let h=0;for(qr.lastIndex=0;(r=qr.exec(e))!==null;){const l=new ce(r[1],s),d=l.TYPE;if(d){const u=o[d],c=n[d]||[];n[d]=c;const f=l.LANGUAGE,g=l["ASSOC-LANGUAGE"],p=l.CHANNELS,v=l.CHARACTERISTICS,y=l["INSTREAM-ID"],E={attrs:l,bitrate:0,id:h++,groupId:l["GROUP-ID"]||"",name:l.NAME||f||"",type:d,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?Xe.resolve(l.URI,t):""};if(g&&(E.assocLang=g),p&&(E.channels=p),v&&(E.characteristics=v),y&&(E.instreamId=y),u!=null&&u.length){const T=Xe.findGroup(u,E.groupId)||u[0];Zr(E,T,"audioCodec"),Zr(E,T,"textCodec")}c.push(E)}}return n}static parseLevelPlaylist(e,t,s,r,n,a){var o;const h={url:t},l=new Vo(t),d=l.fragments,u=[];let c,f,g,p,v=null,y=0,E=0,T=0,A=0,L=0,b=null,S=new qs(r,h),k=-1,D=!1,P=null;if(Zs.lastIndex=0,l.m3u8=e,l.hasVariableRefs=Gr(e),((o=Zs.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(c=Zs.exec(e))!==null;){D&&(D=!1,S=new qs(r,h),S.playlistOffset=T,S.setStart(T),S.sn=y,S.cc=A,L&&(S.bitrate=L),S.level=s,v&&(S.initSegment=v,v.rawProgramDateTime&&(S.rawProgramDateTime=v.rawProgramDateTime,v.rawProgramDateTime=null),P&&(S.setByteRange(P),P=null)));const F=c[1];if(F){S.duration=parseFloat(F);const w=(" "+c[2]).slice(1);S.title=w||null,S.tagList.push(w?["INF",F,w]:["INF",F])}else if(c[3]){if(U(S.duration)){S.playlistOffset=T,S.setStart(T),g&&en(S,g,l),S.sn=y,S.level=s,S.cc=A,d.push(S);const w=(" "+c[3]).slice(1);S.relurl=Ai(l,w),Ii(S,b,u),b=S,T+=S.duration,y++,E=0,D=!0}}else{if(c=c[0].match(Wo),!c){ne.warn("No matches on slow regex match for level playlist!");continue}for(f=1;f<c.length&&c[f]===void 0;f++);const w=(" "+c[f]).slice(1),_=(" "+c[f+1]).slice(1),$=c[f+2]?(" "+c[f+2]).slice(1):null;switch(w){case"BYTERANGE":b?S.setByteRange(_,b):S.setByteRange(_);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=_,S.tagList.push(["PROGRAM-DATE-TIME",_]),k===-1&&(k=d.length);break;case"PLAYLIST-TYPE":l.type&&Ze(l,w,c),l.type=_.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?Ze(l,w,c):d.length>0&&tn(l,w,c),y=l.startSN=parseInt(_);break;case"SKIP":{l.skippedSegments&&Ze(l,w,c);const x=new ce(_,l),C=x.decimalInteger("SKIPPED-SEGMENTS");if(U(C)){l.skippedSegments+=C;for(let V=C;V--;)d.push(null);y+=C}const M=x.enumeratedString("RECENTLY-REMOVED-DATERANGES");M&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(M.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&Ze(l,w,c),l.targetduration=Math.max(parseInt(_),1);break;case"VERSION":l.version!==null&&Ze(l,w,c),l.version=parseInt(_);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||Ze(l,w,c),l.live=!1;break;case"#":(_||$)&&S.tagList.push($?[_,$]:[_]);break;case"DISCONTINUITY":A++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([w]);break;case"BITRATE":S.tagList.push([w,_]),L=1e3*parseInt(_),U(L)?S.bitrate=L:L=0;break;case"DATERANGE":{const x=new ce(_,l),C=new ca(x,l.dateRanges[x.ID],l.dateRangeTagCount);l.dateRangeTagCount++,C.isValid||l.skippedSegments?l.dateRanges[C.id]=C:ne.warn(`Ignoring invalid DATERANGE tag: "${_}"`),S.tagList.push(["EXT-X-DATERANGE",_]);break}case"DEFINE":{const x=new ce(_,l);"IMPORT"in x?Bo(l,x,a):Kr(l,x,t)}break;case"DISCONTINUITY-SEQUENCE":l.startCC!==0?Ze(l,w,c):d.length>0&&tn(l,w,c),l.startCC=A=parseInt(_);break;case"KEY":{const x=Xr(_,t,l);if(x.isSupported()){if(x.method==="NONE"){g=void 0;break}g||(g={});const C=g[x.keyFormat];C!=null&&C.matches(x)||(C&&(g=ae({},g)),g[x.keyFormat]=x)}else ne.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${_}"`);break}case"START":l.startTimeOffset=zr(_);break;case"MAP":{const x=new ce(_,l);if(S.duration){const C=new qs(r,h);Jr(C,x,s,g),v=C,S.initSegment=v,v.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=v.rawProgramDateTime)}else{const C=S.byteRangeEndOffset;if(C){const M=S.byteRangeStartOffset;P=`${C-M}@${M}`}else P=null;Jr(S,x,s,g),v=S,D=!0}v.cc=A;break}case"SERVER-CONTROL":p&&Ze(l,w,c),p=new ce(_),l.canBlockReload=p.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=p.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&p.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=p.optionalFloat("PART-HOLD-BACK",0),l.holdBack=p.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{l.partTarget&&Ze(l,w,c);const x=new ce(_);l.partTarget=x.decimalFloatingPoint("PART-TARGET");break}case"PART":{let x=l.partList;x||(x=l.partList=[]);const C=E>0?x[x.length-1]:void 0,M=E++,V=new ce(_,l),Y=new yo(V,S,h,M,C);x.push(Y),S.duration+=Y.duration;break}case"PRELOAD-HINT":{const x=new ce(_,l);l.preloadHint=x;break}case"RENDITION-REPORT":{const x=new ce(_,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(x);break}default:ne.warn(`line parsed but not handled: ${c}`)}}}b&&!b.relurl?(d.pop(),T-=b.duration,l.partList&&(l.fragmentHint=b)):l.partList&&(Ii(S,b,u),S.cc=A,l.fragmentHint=S,g&&en(S,g,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const O=d.length,N=d[0],B=d[O-1];if(T+=l.skippedSegments*l.targetduration,T>0&&O&&B){l.averagetargetduration=T/O;const F=B.sn;l.endSN=F!=="initSegment"?F:0,l.live||(B.endList=!0),k>0&&(function(w,_){let $=w[_];for(let x=_;x--;){const C=w[x];if(!C)return;C.programDateTime=$.programDateTime-1e3*C.duration,$=C}}(d,k),N&&u.unshift(N))}return l.fragmentHint&&(T+=l.fragmentHint.duration),l.totalduration=T,u.length&&l.dateRangeTagCount&&N&&va(u,l),l.endCC=A,l}}function va(i,e){let t=i.length;if(!t){if(!e.hasProgramDateTime)return;{const o=e.fragments[e.fragments.length-1];i.push(o),t++}}const s=i[t-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const h=e.dateRanges[n[o]],l=h.startDate.getTime();h.tagAnchor=s.ref;for(let d=t;d--;){var a;if(((a=i[d])==null?void 0:a.sn)<e.startSN)break;const u=jo(e,l,i,d,r);if(u!==-1){h.tagAnchor=e.fragments[u].ref;break}}}}function jo(i,e,t,s,r){const n=t[s];if(n){const o=n.programDateTime;if(e>=o||s===0){var a;if(e<=o+1e3*((((a=t[s+1])==null?void 0:a.start)||r)-n.start)){const h=t[s].sn-i.startSN;if(h<0)return-1;const l=i.fragments;if(l.length>t.length)for(let d=(t[s+1]||l[l.length-1]).sn-i.startSN;d>h;d--){const u=l[d].programDateTime;if(e>=u&&e<u+1e3*l[d].duration)return d}return h}}}return-1}function Xr(i,e,t){var s,r;const n=new ce(i,t),a=(s=n.METHOD)!=null?s:"",o=n.URI,h=n.hexadecimalInteger("IV"),l=n.KEYFORMATVERSIONS,d=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!h&&ne.error(`Invalid IV: ${n.IV}`);const u=o?Xe.resolve(o,e):"",c=(l||"1").split("/").map(Number).filter(Number.isFinite);return new dt(a,u,d,c,h,n.KEYID)}function zr(i){const e=new ce(i).decimalFloatingPoint("TIME-OFFSET");return U(e)?e:null}function Qr(i,e){let t=(i||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const r=t.filter(n=>Yi(n,s));r.length&&(e[`${s}Codec`]=r.map(n=>n.split("/")[0]).join(","),t=t.filter(n=>r.indexOf(n)===-1))}),e.unknownCodecs=t}function Zr(i,e,t){const s=e[t];s&&(i[t]=s)}function Ii(i,e,t){i.rawProgramDateTime?t.push(i):e!=null&&e.programDateTime&&(i.programDateTime=e.endProgramDateTime)}function Jr(i,e,t,s){i.relurl=e.URI,e.BYTERANGE&&i.setByteRange(e.BYTERANGE),i.level=t,i.sn="initSegment",s&&(i.levelkeys=s),i.initSegment=null}function en(i,e,t){i.levelkeys=e;const{encryptedFragments:s}=t;s.length&&s[s.length-1].levelkeys===e||!Object.keys(e).some(r=>e[r].isCommonEncryption)||s.push(i)}function Ze(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function tn(i,e,t){i.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Js(i,e){const t=e.startPTS;if(U(t)){let s,r=0;e.sn>i.sn?(r=t-i.start,s=i):(r=i.start-t,s=e),s.duration!==r&&s.setDuration(r)}else e.sn>i.sn?i.cc===e.cc&&i.minEndPTS?e.setStart(i.start+(i.minEndPTS-i.start)):e.setStart(i.start+i.duration):e.setStart(Math.max(i.start-e.duration,0))}function ya(i,e,t,s,r,n,a){s-t<=0&&(a.warn("Fragment should have a positive duration",e),s=t+e.duration,n=r+e.duration);let o=t,h=s;const l=e.startPTS,d=e.endPTS;if(U(l)){const v=Math.abs(l-t);i&&v>i.totalduration?a.warn(`media timestamps and playlist times differ by ${v}s for level ${e.level} ${i.url}`):U(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,o=Math.max(t,l),t=Math.min(t,l),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,h=Math.min(s,d),s=Math.max(s,d),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}const u=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=o,e.startDTS=r,e.endPTS=s,e.minEndPTS=h,e.endDTS=n;const c=e.sn;if(!i||c<i.startSN||c>i.endSN)return 0;let f;const g=c-i.startSN,p=i.fragments;for(p[g]=e,f=g;f>0;f--)Js(p[f],p[f-1]);for(f=g;f<p.length-1;f++)Js(p[f],p[f+1]);return i.fragmentHint&&Js(p[p.length-1],i.fragmentHint),i.PTSKnown=i.alignedSliding=!0,u}function qo(i,e,t){if(i===e)return;let s=null;const r=i.fragments;for(let d=r.length-1;d>=0;d--){const u=r[d].initSegment;if(u){s=u;break}}let n;i.fragmentHint&&delete i.fragmentHint.endPTS,function(d,u,c){const f=u.skippedSegments,g=Math.max(d.startSN,u.startSN)-u.startSN,p=(d.fragmentHint?1:0)+(f?u.endSN:Math.min(d.endSN,u.endSN))-u.startSN,v=u.startSN-d.startSN,y=u.fragmentHint?u.fragments.concat(u.fragmentHint):u.fragments,E=d.fragmentHint?d.fragments.concat(d.fragmentHint):d.fragments;for(let T=g;T<=p;T++){const A=E[v+T];let L=y[T];if(f&&!L&&A&&(L=u.fragments[T]=A),A&&L){c(A,L,T,y);const b=A.relurl,S=L.relurl;if(b&&Xo(b,S))return void(u.playlistParsingError=sn(`media sequence mismatch ${L.sn}:`,d,u,A,L));if(A.cc!==L.cc)return void(u.playlistParsingError=sn(`discontinuity sequence mismatch (${A.cc}!=${L.cc})`,d,u,A,L))}}}(i,e,(d,u,c,f)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==d.cc){const g=d.cc-u.cc;for(let p=c;p<f.length;p++)f[p].cc+=g;e.endCC=f[f.length-1].cc}U(d.startPTS)&&U(d.endPTS)&&(u.setStart(u.startPTS=d.startPTS),u.startDTS=d.startDTS,u.maxStartPTS=d.maxStartPTS,u.endPTS=d.endPTS,u.endDTS=d.endDTS,u.minEndPTS=d.minEndPTS,u.setDuration(d.endPTS-d.startPTS),u.duration&&(n=u),e.PTSKnown=e.alignedSliding=!0),d.hasStreams&&(u.elementaryStreams=d.elementaryStreams),u.loader=d.loader,d.hasStats&&(u.stats=d.stats),d.initSegment&&(u.initSegment=d.initSegment,s=d.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(d=>{var u;!d||d.initSegment&&d.initSegment.relurl!==((u=s)==null?void 0:u.relurl)||(d.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(d=>!d),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let d=e.skippedSegments;d--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=function(u,c,f){const{dateRanges:g,recentlyRemovedDateranges:p}=c,v=ae({},u);p&&p.forEach(E=>{delete v[E]});const y=Object.keys(v).length;return y?(Object.keys(g).forEach(E=>{const T=v[E],A=new ca(g[E].attr,T);A.isValid?(v[E]=A,T||(A.tagOrder+=y)):f.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${oe(g[E].attr)}"`)}),v):g}(i.dateRanges,e,t));const d=i.fragments.filter(u=>u.rawProgramDateTime);if(i.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Ii(o[u],o[u-1],d);va(d,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var h;const d=Sa(i,e.startSN-1);e.startCC=(h=d?.cc)!=null?h:a[0].cc}(function(d,u,c){if(d&&u){let f=0;for(let g=0,p=d.length;g<=p;g++){const v=d[g],y=u[g+f];v&&y&&v.index===y.index&&v.fragment.sn===y.fragment.sn?c(v,y):f--}}})(i.partList,e.partList,(d,u)=>{u.elementaryStreams=d.elementaryStreams,u.stats=d.stats}),n?ya(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,t):Ea(i,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=i.driftStartTime,e.driftStart=i.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const d=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=d),e.driftEndTime=l,e.driftEnd=d}else e.driftEndTime=i.driftEndTime,e.driftEnd=i.driftEnd,e.advancedDateTime=i.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=i.requestScheduled)}function sn(i,e,t,s,r){return new Error(`${i} ${r.url}
2
+ Playlist starting @${e.startSN}
3
+ ${e.m3u8}
4
+
5
+ Playlist starting @${t.startSN}
6
+ ${t.m3u8}`)}function Ea(i,e,t=!0){const s=e.startSN+e.skippedSegments-i.startSN,r=i.fragments,n=s>=0;let a=0;if(n&&s<r.length)a=r[s].start;else if(n&&e.startSN===i.endSN+1)a=i.fragmentEnd;else if(n&&t)a=i.fragmentStart+s*e.levelTargetDuration;else{if(e.skippedSegments||e.fragmentStart!==0)return;a=i.fragmentStart}bi(e,a)}function bi(i,e){if(e){const t=i.fragments;for(let s=i.skippedSegments;s<t.length;s++)t[s].addStart(e);i.fragmentHint&&i.fragmentHint.addStart(e)}}function Ta(i,e=1/0){let t=1e3*i.targetduration;if(i.updated){const s=i.fragments;if(s.length&&t*4>e){const n=1e3*s[s.length-1].duration;n<t&&(t=n)}}else t/=2;return Math.round(t)}function Sa(i,e,t){if(!i)return null;let s=i.fragments[e-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===e?s:e<i.startSN&&t&&t.sn===e?t:null)}function rn(i,e,t){return i?La(i.partList,e,t):null}function La(i,e,t){if(i)for(let s=i.length;s--;){const r=i[s];if(r.index===t&&r.fragment.sn===e)return r}return null}function Aa(i){i.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(r=>{r.level=t,r.initSegment&&(r.initSegment.level=t)})})}function Xo(i,e){return!(i===e||!e)&&nn(i)!==nn(e)}function nn(i){return i.replace(/\?[^?]*$/,"")}function Zt(i,e){for(let s=0,r=i.length;s<r;s++){var t;if(((t=i[s])==null?void 0:t.cc)===e)return i[s]}return null}function an(i,e){const t=i.start+e;i.startPTS=t,i.setStart(t),i.endPTS=t+i.duration}function Ra(i,e){const t=e.fragments;for(let s=0,r=t.length;s<r;s++)an(t[s],i);e.fragmentHint&&an(e.fragmentHint,i),e.alignedSliding=!0}function Ia(i,e){if(!function(n,a){return!!(n&&a.startCC<n.endCC&&a.endCC>n.startCC)}(e,i))return;const t=Math.min(e.endCC,i.endCC),s=Zt(e.fragments,t),r=Zt(i.fragments,t);!s||!r||(ne.log(`Aligning playlist at start of dicontinuity sequence ${t}`),Ra(s.start-r.start,i))}function Ds(i,e){if(!i.hasProgramDateTime||!e.hasProgramDateTime)return;const t=i.fragments,s=e.fragments;if(!t.length||!s.length)return;let r,n;const a=Math.min(e.endCC,i.endCC);e.startCC<a&&i.startCC<a&&(r=Zt(s,a),n=Zt(t,a)),r&&n||(r=s[Math.floor(s.length/2)],n=Zt(t,r.cc)||t[Math.floor(t.length/2)]);const o=r.programDateTime,h=n.programDateTime;!o||!h||Ra((h-o)/1e3-(n.start-r.start),i)}function Ie(i,e,t){De(i,e,t),i.addEventListener(e,t)}function De(i,e,t){i.removeEventListener(e,t)}const zo=function(i){let e="";const t=i.length;for(let s=0;s<t;s++)e+=`[${i.start(s).toFixed(3)}-${i.end(s).toFixed(3)}]`;return e},ye="STOPPED",J="IDLE",ki="KEY_LOADING",Ot="FRAG_LOADING",Mt="FRAG_LOADING_WAITING_RETRY",It="WAITING_TRACK",rt="PARSING",Gs="PARSED",$t="ENDED",it="ERROR",Ht="WAITING_INIT_PTS",vt="WAITING_LEVEL";class Di extends da{constructor(e,t,s,r,n){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ye,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:o,media:h,mediaBuffer:l,state:d}=this,u=h?h.currentTime:0,c=z.bufferInfo(l||h,u,a.maxBufferHole),f=!c.len;if(this.log(`Media seeking to ${U(u)?u.toFixed(3):u}, state: ${d}, ${f?"out of":"in"} buffer`),this.state===$t)this.resetLoadingState();else if(o){const g=a.maxFragLookUpTolerance,p=o.start-g,v=o.start+o.duration+g;if(f||v<c.start||p>c.end){const y=u>v;(u<p||y)&&(y&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(h&&(this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0),u>this.lastCurrentTime&&(this.lastCurrentTime=u),!this.loadingParts)){const g=Math.max(c.end,u),p=this.shouldLoadParts(this.getLevelDetails(),g);p&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${g.toFixed(2)}`),this.loadingParts=p)}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,f&&(this.startPosition=u)),f&&this.state===J&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=e,this.fragmentLoader=new $o(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Xi(e.config)}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===ye)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ye}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,r=this.config.timelineOffset||0;if(s<=r)return!1;const n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=z.bufferedInfo(n,e.start,0));const a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;const o=t.partList;if(o!=null&&o.length){const l=o[o.length-1];return z.isBuffered(this.media,l.start+l.duration/2)}const h=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(h)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;var t;return e?((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e:0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;Ie(s,"seeking",this.onMediaSeeking),Ie(s,"ended",this.onMediaEnded);const r=this.config;this.levels&&r.autoStartLoad&&this.state===ye&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),De(r,"seeking",this.onMediaSeeking),De(r,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=ye,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){this._doFragLoad(e,t,s,r=>{const n=r.frag;if(this.fragContextChanged(n))return this.warn(`${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(n);n.stats.chunkCount++,this._handleFragmentLoadProgress(r)}).then(r=>{if(!r)return;const n=this.state,a=r.frag;this.fragContextChanged(a)?(n===Ot||!this.fragCurrent&&n===rt)&&(this.fragmentTracker.removeFragment(a),this.state=J):("payload"in r&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r))}).catch(r=>{this.state!==ye&&this.state!==it&&(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===ha){const r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),a=Math.max(e.duration,n?n.len:this.config.maxBufferLength),o=this.backtrackFragment;((o?e.sn-o.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===_t&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const r={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const r=s?.frag;if(!r||this.fragContextChanged(r)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:r}=this,{frag:n,payload:a}=s,o=n.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&xt(o.method)){const h=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,Qi(o.method)).catch(l=>{throw r.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:n}),l}).then(l=>{const d=self.performance.now();return r.trigger(m.FRAG_DECRYPTED,{frag:n,payload:l,stats:{tstart:h,tdecrypt:d}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state!==ye&&this.state!==it&&(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==ye&&(this.state=J),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,r;const n=e.tracks;if(n&&!t.encrypted&&((s=n.audio)!=null&&s.encrypted||(r=n.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(m.ERROR,{type:H.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?zo(z.getBuffered(s)):"(detached)"})`),ve(e)){var r;if(e.type!==_e){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o]))return void(this.state=J)}const n=(r=this.levels)==null?void 0:r[e.level];n!=null&&n.fragmentError&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0)}this.state=J}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:r,partsLoaded:n}=e,a=!n||n.length===0||n.some(h=>!h),o=new zi(s.level,s.sn,s.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,r){var n;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(!e.encrypted||(n=e.decryptdata)!=null&&n.key)e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=ki,this.fragCurrent=e,o=this.keyLoader.load(e).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(m.KEY_LOADED,c),this.state===ki&&(this.state=J),c}),this.hls.trigger(m.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const h=this.fragPrevious;if(ve(e)&&(!h||e.sn!==h.sn)){const c=this.shouldLoadParts(t.details,e.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} loading sn ${h?.sn}->${e.sn}`),this.loadingParts=c)}if(s=Math.max(e.start,s||0),this.loadingParts&&ve(e)){const c=a.partList;if(c&&r){s>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const f=this.getNextPart(c,e,s);if(f>-1){const g=c[f];let p;return e=this.fragCurrent=g.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${g.index} (${f}/${c.length-1}) of ${this.fragInfo(e,!1,g)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=Ot,p=o?o.then(v=>!v||this.fragContextChanged(v.frag)?null:this.doFragPartsLoad(e,g,t,r)).catch(v=>this.handleFragLoadError(v)):this.doFragPartsLoad(e,g,t,r).catch(v=>this.handleFragLoadError(v)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:g,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}if(!e.url||this.loadedEndOfParts(c,s))return Promise.resolve(null)}}var l;if(ve(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=a.partList)==null?void 0:l.filter(c=>c.loaded).map(c=>`[${c.start}-${c.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),U(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Ot;const d=this.config.progressive&&e.type!==_e;let u;return u=d&&o?o.then(c=>!c||this.fragContextChanged(c.frag)?null:this.fragmentLoader.load(e,r)).catch(c=>this.handleFragLoadError(c)):Promise.all([this.fragmentLoader.load(e,d?r:void 0),o]).then(([c])=>(!d&&r&&r(c),c)).catch(c=>this.handleFragLoadError(c)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,s,r){return new Promise((n,a)=>{var o;const h=[],l=(o=s.details)==null?void 0:o.partList,d=u=>{this.fragmentLoader.loadPart(e,u,r).then(c=>{h[u.index]=c;const f=c.part;this.hls.trigger(m.FRAG_LOADED,c);const g=rn(s.details,e.sn,u.index+1)||La(l,e.sn,u.index+1);if(!g)return n({frag:e,part:f,partsLoaded:h});d(g)}).catch(a)};d(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===I.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===H.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==rt)return void(this.fragCurrent||this.state===ye||this.state===it||(this.state=J));const{frag:s,part:r,level:n}=t,a=self.performance.now();s.stats.parsing.end=a,r&&(r.stats.parsing.end=a);const o=this.getLevelDetails(),h=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);h!==this.loadingParts&&(this.log(`LL-Part loading ${h?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=h),this.updateLevelTiming(s,r,n,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const n=e.partList[0];if(n.fragment.type===_e)return!1;if(t>=n.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0)){var r;if((this.hls.hasEnoughToStart?((r=this.media)==null?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:r,sn:n,part:a}=e;if(t==null||!t[r])return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;const o=t[r],h=o.details,l=a>-1?rn(h,n,a):null,d=l?l.fragment:Sa(h,n,s);return d?(s&&s!==d&&(d.stats=s.stats),{frag:d,part:l,level:o}):null}bufferFragmentData(e,t,s,r,n){if(this.state!==rt)return;const{data1:a,data2:o}=e;let h=a;if(o&&(h=Ne(a,o)),!h.length)return;const l=this.initPTS[t.cc],d=l?-l.baseTime/l.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:r,offset:d,parent:t.type,data:h};if(this.hls.trigger(m.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(n)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!z.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const s=t.currentTime,r=z.bufferInfo(t,s,0),n=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),o=Math.max(Math.min(e.start-a,r.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const r=this.getLoadPosition();if(!U(r))return null;const n=this.lastCurrentTime>r||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,n)}getFwdBufferInfoAtPos(e,t,s,r){const n=z.bufferInfo(e,t,r);if(n.len===0&&n.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(n.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(n.nextStart,a.end)-t,r);return z.bufferInfo(e,t,o)}}return n}getMaxBufferLength(e){const{config:t}=this;let s;return s=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,r=Math.max(Math.min(e-t,s.maxBufferLength),t),n=Math.max(e-3*t,s.maxMaxBufferLength/2,r);return n>=r&&(s.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}s`),!0)}getAppendedFrag(e,t=Z){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,r=s.length;if(!r)return null;const{config:n}=this,a=s[0].start,o=n.lowLatencyMode&&!!t.partList;let h=null;if(t.live){const u=n.initialLiveManifestSize;if(r<u)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),h=this.getInitialLiveFragment(t);const c=this.hls.startPosition,f=this.hls.liveSyncPosition,g=h?(c!==-1&&c>=a?c:f)||h.start:e;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${c} liveSyncPosition: ${f} frag.start: ${(l=h)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}else e<=a&&(h=s[0]);if(!h){const u=this.loadingParts?t.partEnd:t.fragmentEnd;h=this.getFragmentAtPosition(e,u,t)}let d=this.filterReplacedPrimary(h,t);if(!d&&h){const u=h.sn-t.startSN;d=this.filterReplacedPrimary(s[u+1]||null,t)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===wt||s===_t&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,r,n){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,r,0);if(o!==null&&s.len+o.len>=n){const h=a.sn;return this.loopSn!==h&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${h}`),this.loopSn=h),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(on(this.config)){var e;if(!((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null)&&e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(on(this.config)&&e.type!==_e){const s=this.hls.interstitialsManager,r=s?.bufferingItem;if(r){const a=r.event;if(a){if(a.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&t?.live===!1||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}const n=s?.playerQueue;if(n)for(let a=n.length;a--;){const o=n[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e==null||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,s){let r=-1,n=!1,a=!0;for(let o=0,h=e.length;o<h;o++){const l=e[o];if(a=a&&!l.independent,r>-1&&s<l.start)break;const d=l.loaded;d?r=-1:(n||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),r=o),n=d}return r}loadedEndOfParts(e,t){let s;for(let r=e.length;r--;){if(s=e[r],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let r=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),r=function(n,a,o){if(a===null||!Array.isArray(n)||!n.length||!U(a)||a<(n[0].programDateTime||0)||a>=(n[n.length-1].endProgramDateTime||0))return null;for(let h=0;h<n.length;++h){const l=n[h];if(xo(a,o,l))return l}return null}(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const n=s.sn+1;if(n>=e.startSN&&n<=e.endSN){const a=t[n-e.startSN];s.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=na(e,s.cc,s.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const n=this.hls.liveSyncPosition;n!==null&&(r=this.getFragmentAtPosition(n,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,s){const{config:r}=this;let{fragPrevious:n}=this,{fragments:a,endSN:o}=s;const{fragmentHint:h}=s,{maxFragLookUpTolerance:l}=r,d=s.partList,u=!!(this.loadingParts&&d!=null&&d.length&&h);let c;if(u&&!this.bitrateTest&&d[d.length-1].fragment.sn===h.sn&&(a=a.concat(h),o=h.sn),e<t){var f;c=Et(n,a,e,e<this.lastCurrentTime||e>t-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l)}else c=a[a.length-1];if(c){const g=c.sn-s.startSN,p=this.fragmentTracker.getState(c);if((p===wt||p===_t&&c.gap)&&(n=c),n&&c.sn===n.sn&&(!u||d[0].fragment.sn>c.sn||!s.live)&&c.level===n.level){const v=a[g+1];c=c.sn<o&&this.fragmentTracker.getState(v)!==wt?v:null}}return c}alignPlaylists(e,t,s){const r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const n=e.fragmentStart,a=!t,o=e.alignedSliding&&U(n);if(a||!o&&!n){(function(l,d){l&&(Ia(d,l),d.alignedSliding||Ds(d,l),d.alignedSliding||d.skippedSegments||Ea(l,d,!1))})(s,e);const h=e.fragmentStart;return this.log(`Live playlist sliding: ${h.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),h}return n}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const r=this.timelineOffset;if(s===-1){const n=this.startTimeOffset!==null,a=n?this.startTimeOffset:e.startTimeOffset;a!==null&&U(a)?(s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+r}this.nextLoadPosition=s+r}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&ve(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===Mt)||(this.state=J)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const y=this.getCurrentContext(t.chunkMeta);y&&(t.frag=y.frag)}const r=t.frag;if(!r||r.type!==e||!this.levels)return;var n;if(this.fragContextChanged(r))return void this.warn(`Frag load error must match current frag to retry ${r.url} > ${(n=this.fragCurrent)==null?void 0:n.url}`);const a=t.details===I.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(r,!0);const o=t.errorAction;if(!o)return void(this.state=it);const{action:h,flags:l,retryCount:d=0,retryConfig:u}=o,c=!!u,f=c&&h===Us,g=c&&!o.resolved&&l===bs,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&g&&ve(r)&&!r.endList&&p&&!oa(t))this.resetFragmentErrors(e),this.treatAsGap(r),o.resolved=!0;else if((f||g)&&d<u.maxNumRetry){var v;const y=Li((v=t.response)==null?void 0:v.code),E=ji(u,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+E,this.state=Mt,o.resolved=!0,y)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(t.reason="offline");this.warn(`Fragment ${r.sn} of ${e} ${r.level} errored with ${t.details}, retrying loading ${d+1}/${u.maxNumRetry} in ${E}ms`)}else if(u){if(this.resetFragmentErrors(e),!(d<u.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${d})`);a||h===Oo||(o.resolved=!0)}else this.state=h===We?vt:it;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Li(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=J)}reduceLengthAndFlushBuffer(e){if(this.state===rt||this.state===Gs){const t=e.frag,s=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,s),n=r&&r.len>.5;n&&this.reduceMaxBufferLength(r.len,t?.duration||10);const a=!n;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===ke&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ye&&(this.state=J)}afterBufferFlushed(e,t,s){if(!e)return;const r=z.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,s),this.state===$t&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ye&&(this.state=J)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;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(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,r){const n=s.details;if(!n)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce((o,h)=>{const l=e.elementaryStreams[h];if(l){const d=l.endPTS-l.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${h} duration reliably (${d})`),o||!1;const u=r?0:ya(n,e,l.startPTS,l.endPTS,l.startDTS,l.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:n,level:s,drift:u,type:h,frag:e,start:l.startPTS,end:l.endPTS}),!0}return o},!1)){var a;const o=((a=this.transmuxer)==null?void 0:a.error)===null;if((s.fragmentError===0||o&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),o){const h=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(h.message),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,error:h,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Gs,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(m.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===Z?"level":"track"}fragInfo(e,t=!0,s){var r,n;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((r=t&&!s?e.startPTS:(s||e).start)!=null?r:NaN).toFixed(3)}-${((n=t&&!s?e.endPTS:(s||e).end)!=null?n:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function on(i){return!!i.interstitialsController&&i.enableInterstitialPlayback!==!1}class ba{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;return e.length?(s=e.length===1?e[0]:function(r,n){const a=new Uint8Array(n);let o=0;for(let h=0;h<r.length;h++){const l=r[h];a.set(l,o),o+=l.length}return a}(e,t),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var ln,hn={exports:{}},er=vo((ln||(ln=1,function(i){var e=Object.prototype.hasOwnProperty,t="~";function s(){}function r(h,l,d){this.fn=h,this.context=l,this.once=d||!1}function n(h,l,d,u,c){if(typeof d!="function")throw new TypeError("The listener must be a function");var f=new r(d,u||h,c),g=t?t+l:l;return h._events[g]?h._events[g].fn?h._events[g]=[h._events[g],f]:h._events[g].push(f):(h._events[g]=f,h._eventsCount++),h}function a(h,l){--h._eventsCount===0?h._events=new s:delete h._events[l]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1)),o.prototype.eventNames=function(){var h,l,d=[];if(this._eventsCount===0)return d;for(l in h=this._events)e.call(h,l)&&d.push(t?l.slice(1):l);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(h)):d},o.prototype.listeners=function(h){var l=t?t+h:h,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,c=d.length,f=new Array(c);u<c;u++)f[u]=d[u].fn;return f},o.prototype.listenerCount=function(h){var l=t?t+h:h,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(h,l,d,u,c,f){var g=t?t+h:h;if(!this._events[g])return!1;var p,v,y=this._events[g],E=arguments.length;if(y.fn){switch(y.once&&this.removeListener(h,y.fn,void 0,!0),E){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,l),!0;case 3:return y.fn.call(y.context,l,d),!0;case 4:return y.fn.call(y.context,l,d,u),!0;case 5:return y.fn.call(y.context,l,d,u,c),!0;case 6:return y.fn.call(y.context,l,d,u,c,f),!0}for(v=1,p=new Array(E-1);v<E;v++)p[v-1]=arguments[v];y.fn.apply(y.context,p)}else{var T,A=y.length;for(v=0;v<A;v++)switch(y[v].once&&this.removeListener(h,y[v].fn,void 0,!0),E){case 1:y[v].fn.call(y[v].context);break;case 2:y[v].fn.call(y[v].context,l);break;case 3:y[v].fn.call(y[v].context,l,d);break;case 4:y[v].fn.call(y[v].context,l,d,u);break;default:if(!p)for(T=1,p=new Array(E-1);T<E;T++)p[T-1]=arguments[T];y[v].fn.apply(y[v].context,p)}}return!0},o.prototype.on=function(h,l,d){return n(this,h,l,d,!1)},o.prototype.once=function(h,l,d){return n(this,h,l,d,!0)},o.prototype.removeListener=function(h,l,d,u){var c=t?t+h:h;if(!this._events[c])return this;if(!l)return a(this,c),this;var f=this._events[c];if(f.fn)f.fn!==l||u&&!f.once||d&&f.context!==d||a(this,c);else{for(var g=0,p=[],v=f.length;g<v;g++)(f[g].fn!==l||u&&!f[g].once||d&&f[g].context!==d)&&p.push(f[g]);p.length?this._events[c]=p.length===1?p[0]:p:a(this,c)}return this},o.prototype.removeAllListeners=function(h){var l;return h?(l=t?t+h:h,this._events[l]&&a(this,l)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,i.exports=o}(hn)),hn.exports));const qt="1.6.15",bt={};function ka(i,e){return e+10<=i.length&&i[e]===51&&i[e+1]===68&&i[e+2]===73&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function tr(i,e){return e+10<=i.length&&i[e]===73&&i[e+1]===68&&i[e+2]===51&&i[e+3]<255&&i[e+4]<255&&i[e+6]<128&&i[e+7]<128&&i[e+8]<128&&i[e+9]<128}function Ws(i,e){let t=0;return t=(127&i[e])<<21,t|=(127&i[e+1])<<14,t|=(127&i[e+2])<<7,t|=127&i[e+3],t}function rs(i,e){const t=e;let s=0;for(;tr(i,e);)s+=10,s+=Ws(i,e+6),ka(i,e+10)&&(s+=10),e+=s;if(s>0)return i.subarray(t,t+s)}function Da(i,e){return i[e]===255&&(246&i[e+1])==240}function Pa(i,e){return 1&i[e+1]?7:9}function sr(i,e){return(3&i[e+3])<<11|i[e+4]<<3|(224&i[e+5])>>>5}function Ks(i,e){return e+1<i.length&&Da(i,e)}function Qo(i,e){if(Ks(i,e)){const t=Pa(i,e);if(e+t>=i.length)return!1;const s=sr(i,e);if(s<=t)return!1;const r=e+s;return r===i.length||Ks(i,r)}return!1}function Ca(i,e,t,s,r){if(!i.samplerate){const n=function(a,o,h,l){const d=o[h+2],u=d>>2&15;if(u>12){const E=new Error(`invalid ADTS sampling index:${u}`);return void a.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!0,error:E,reason:E.message})}const c=1+(d>>6&3),f=o[h+3]>>6&3|(1&d)<<2,g="mp4a.40."+c,p=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][u];let v=u;c!==5&&c!==29||(v-=3);const y=[c<<3|(14&v)>>1,(1&v)<<7|f<<3];return ne.log(`manifest codec:${l}, parsed codec:${g}, channels:${f}, rate:${p} (ADTS object type:${c} sampling index:${u})`),{config:y,samplerate:p,channelCount:f,codec:g,parsedCodec:g,manifestCodec:l}}(e,t,s,r);if(!n)return;ae(i,n)}}function _a(i){return 9216e4/i}function wa(i,e,t,s,r){const n=s+r*_a(i.samplerate),a=function(l,d){const u=Pa(l,d);if(d+u<=l.length){const c=sr(l,d)-u;if(c>0)return{headerLength:u,frameLength:c}}}(e,t);let o;if(a){const{frameLength:l,headerLength:d}=a,u=d+l,c=Math.max(0,t+u-e.length);c?(o=new Uint8Array(u-d),o.set(e.subarray(t+d,e.length),0)):o=e.subarray(t+d,t+u);const f={unit:o,pts:n};return c||i.samples.push(f),{sample:f,length:u,missing:c}}const h=e.length-t;return o=new Uint8Array(h),o.set(e.subarray(t,e.length),0),{sample:{unit:o,pts:n},length:h,missing:-1}}function Zo(i,e){return tr(i,e)&&Ws(i,e+6)+10<=i.length-e}function ei(i,e=0,t=1/0){return function(s,r,n,a){const o=(h=s,h instanceof ArrayBuffer?h:h.buffer);var h;let l=1;"BYTES_PER_ELEMENT"in a&&(l=a.BYTES_PER_ELEMENT);const d=(p=s,p&&p.buffer instanceof ArrayBuffer&&p.byteLength!==void 0&&p.byteOffset!==void 0?s.byteOffset:0),u=(d+s.byteLength)/l,c=(d+r)/l,f=Math.floor(Math.max(0,Math.min(c,u))),g=Math.floor(Math.min(f+Math.max(n,0),u));var p;return new a(o,f,g-f)}(i,e,t,Uint8Array)}function Jo(i){const e={key:i.type,description:"",data:"",mimeType:null,pictureType:null};if(i.size<2)return;if(i.data[0]!==3)return void console.log("Ignore frame with unrecognized character encoding");const t=i.data.subarray(1).indexOf(0);if(t===-1)return;const s=we(ei(i.data,1,t)),r=i.data[2+t],n=i.data.subarray(3+t).indexOf(0);if(n===-1)return;const a=we(ei(i.data,3+t,n));let o;var h;return o=s==="-->"?we(ei(i.data,4+t+n)):(h=i.data.subarray(4+t+n))instanceof ArrayBuffer?h:h.byteOffset==0&&h.byteLength==h.buffer.byteLength?h.buffer:new Uint8Array(h).buffer,e.mimeType=s,e.pictureType=r,e.description=a,e.data=o,e}function el(i){return i.type==="PRIV"?function(e){if(e.size<2)return;const t=we(e.data,!0),s=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:s.buffer}}(i):i.type[0]==="W"?function(e){if(e.type==="WXXX"){if(e.size<2)return;let s=1;const r=we(e.data.subarray(s),!0);s+=r.length+1;const n=we(e.data.subarray(s));return{key:e.type,info:r,data:n}}const t=we(e.data);return{key:e.type,info:"",data:t}}(i):i.type==="APIC"?Jo(i):function(e){if(e.size<2)return;if(e.type==="TXXX"){let s=1;const r=we(e.data.subarray(s),!0);s+=r.length+1;const n=we(e.data.subarray(s));return{key:e.type,info:r,data:n}}const t=we(e.data.subarray(1));return{key:e.type,info:"",data:t}}(i)}function tl(i){const e=String.fromCharCode(i[0],i[1],i[2],i[3]),t=Ws(i,4);return{type:e,size:t,data:i.subarray(10,10+t)}}function xa(i){let e=0;const t=[];for(;tr(i,e);){const s=Ws(i,e+6);i[e+5]>>6&1&&(e+=10),e+=10;const r=e+s;for(;e+10<r;){const n=tl(i.subarray(e)),a=el(n);a&&t.push(a),e+=n.size+10}ka(i,e)&&(e+=10)}return t}function Oa(i){return i&&i.key==="PRIV"&&i.info==="com.apple.streaming.transportStreamTimestamp"}function sl(i){if(i.data.byteLength===8){const e=new Uint8Array(i.data),t=1&e[3];let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function ir(i){const e=xa(i);for(let t=0;t<e.length;t++){const s=e[t];if(Oa(s))return sl(s)}}let xe=function(i){return i.audioId3="org.id3",i.dateRange="com.apple.quicktime.HLS",i.emsg="https://aomedia.org/emsg/ID3",i.misbklv="urn:misb:KLV:bin:1910.1",i}({});function je(i="",e=9e4){return{type:i,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Pi{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=Ne(this.cachedData,e),this.cachedData=null);let s,r=rs(e,0),n=r?r.length:0;const a=this._audioTrack,o=this._id3Track,h=r?ir(r):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&U(h))&&(this.basePTS=il(h,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),r&&r.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:xe.audioId3,duration:Number.POSITIVE_INFINITY});n<l;){if(this.canParse(e,n)){const d=this.appendFrame(a,e,n);d?(this.frameIndex++,this.lastPTS=d.sample.pts,n+=d.length,s=n):n=l}else Zo(e,n)?(r=rs(e,n),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:xe.audioId3,duration:Number.POSITIVE_INFINITY}),n+=r.length,s=n):n++;if(n===l&&s!==l){const d=e.slice(s);this.cachedData?this.cachedData=Ne(this.cachedData,d):this.cachedData=d}}return{audioTrack:a,videoTrack:je(),id3Track:o,textTrack:je()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:je(),id3Track:this._id3Track,textTrack:je()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const il=(i,e,t)=>U(i)?90*i:9e4*e+(t?9e4*t.baseTime/t.timescale:0);let fs=null;const rl=[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],nl=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],al=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ol=[0,1,1,4];function Ma(i,e,t,s,r){if(t+24>e.length)return;const n=Fa(e,t);if(n&&t+n.frameLength<=e.length){const a=s+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(t,t+n.frameLength),pts:a,dts:a};return i.config=[],i.channelCount=n.channelCount,i.samplerate=n.sampleRate,i.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Fa(i,e){const t=i[e+1]>>3&3,s=i[e+1]>>1&3,r=i[e+2]>>4&15,n=i[e+2]>>2&3;if(t!==1&&r!==0&&r!==15&&n!==3){const a=i[e+2]>>1&1,o=i[e+3]>>6,h=1e3*rl[14*(t===3?3-s:s===3?3:4)+r-1],l=nl[3*(t===3?0:t===2?1:2)+n],d=o===3?1:2,u=al[t][s],c=ol[s],f=8*u*c,g=Math.floor(u*h/l+a)*c;if(fs===null){const p=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);fs=p?parseInt(p[1]):0}return fs&&fs<=87&&s===2&&h>=224e3&&o===0&&(i[e+3]=128|i[e+3]),{sampleRate:l,channelCount:d,frameLength:g,samplesPerFrame:f}}}function rr(i,e){return!(i[e]!==255||224&~i[e+1]||!(6&i[e+1]))}function Na(i,e){return e+1<i.length&&rr(i,e)}function dn(i,e){if(e+1<i.length&&rr(i,e)){const s=Fa(i,e);let r=4;s!=null&&s.frameLength&&(r=s.frameLength);const n=e+r;return n===i.length||Na(i,n)}return!1}const Ua=(i,e)=>{let t=0,s=5;e+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=i[e];const o=Math.min(s,8),h=8-o;n[0]=4278190080>>>24+h<<h,r[0]=(a[0]&n[0])>>h,t=t?t<<o|r[0]:r[0],e+=1,s-=o}return t};class ll extends Pi{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,r){super.resetInitSegment(e,t,s,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const r=$a(e,t,s,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;const t=rs(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&ir(t)!==void 0&&Ua(e,s)<16}}function $a(i,e,t,s,r){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const n=e[t+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[t+4],h=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(t+h>e.length)return-1;const l=e[t+6]>>5;let d=0;l===2?d+=2:(1&l&&l!==1&&(d+=2),4&l&&(d+=2));const u=(e[t+6]<<8|e[t+7])>>12-d&1,c=[2,1,2,3,3,4,4,5][l]+u,f=e[t+5]>>3,g=7&e[t+5],p=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|l<<3|u<<2|o>>4,o<<4&224]),v=s+r*(1536/a*9e4),y=e.subarray(t,t+h);return i.config=p,i.channelCount=c,i.samplerate=a,i.samples.push({unit:y,pts:v}),h}const hl=/\/emsg[-/]ID3/i;function un(i,e){return U(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale}class dl{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Xi(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,as)}decryptAacSample(e,t,s){const r=e[t].unit;if(r.length<=16)return;const n=r.subarray(16,r.length-r.length%16),a=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(a).then(o=>{const h=new Uint8Array(o);r.set(h,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length)return void s();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,s=new Int8Array(t);let r=0;for(let n=32;n<e.length-16;n+=160,r+=16)s.set(e.subarray(n,n+16),r);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let r=0;for(let n=32;n<e.length-16;n+=160,r+=16)e.set(s.subarray(r,r+16),n);return e}decryptAvcSample(e,t,s,r,n){const a=Qn(n.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(h=>{n.data=this.getAvcDecryptedUnit(a,h),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,r)}).catch(r)}decryptAvcSamples(e,t,s,r){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length)return void r();const n=e[t].units;for(;!(s>=n.length);s++){const a=n[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5||(this.decryptAvcSample(e,t,s,r,a),this.decrypter.isSync())))return}}}}class Ba{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s,r=this.VideoSample;if(r&&r.units.length!==0||(r=e[e.length-1]),(t=r)!=null&&t.units){const n=r.units;s=n[n.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,r=s.length;if(!r)return void t.dropped++;{const n=s[r-1];e.pts=n.pts,e.dts=n.dts}}t.samples.push(e)}}parseNALu(e,t,s){const r=t.byteLength;let n=e.naluState||0;const a=n,o=[];let h,l,d,u=0,c=-1,f=0;for(n===-1&&(c=0,f=this.getNALuType(t,0),n=0,u=1);u<r;)if(h=t[u++],n)if(n!==1)if(h)if(h===1){if(l=u-n-1,c>=0){const g={data:t.subarray(c,l),type:f};o.push(g)}else{const g=this.getLastNalUnit(e.samples);g&&(a&&u<=4-a&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-a)),l>0&&(g.data=Ne(g.data,t.subarray(0,l)),g.state=0))}u<r?(d=this.getNALuType(t,u),c=u,f=d,n=0):n=-1}else n=0;else n=3;else n=h?0:2;else n=h?0:1;if(c>=0&&n>=0){const g={data:t.subarray(c,r),type:f,state:n};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(e.samples);g&&(g.data=Ne(g.data,t))}return e.naluState=n,o}}class Jt{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,r=new Uint8Array(4),n=Math.min(4,t);if(n===0)throw new Error("no bytes available");r.set(e.subarray(s,s+n)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&ne.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class ul extends Ba{parsePES(e,t,s,r){const n=this.parseNALu(e,s.data,r);let a,o=this.VideoSample,h=!1;s.data=null,o&&n.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(l=>{var d,u;switch(l.type){case 1:{let p=!1;a=!0;const v=l.data;if(h&&v.length>4){const y=this.readSliceType(v);y!==2&&y!==4&&y!==7&&y!==9||(p=!0)}var c;p&&(c=o)!=null&&c.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),o.frame=!0,o.key=p;break}case 5:a=!0,(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),o.key=!0,o.frame=!0;break;case 6:a=!0,Vi(l.data,1,s.pts,t.samples);break;case 7:{var f,g;a=!0,h=!0;const p=l.data,v=this.readSPS(p);if(!e.sps||e.width!==v.width||e.height!==v.height||((f=e.pixelRatio)==null?void 0:f[0])!==v.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==v.pixelRatio[1]){e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.sps=[p];const y=p.subarray(1,4);let E="avc1.";for(let T=0;T<3;T++){let A=y[T].toString(16);A.length<2&&(A="0"+A),E+=A}e.codec=E}break}case 8:a=!0,e.pps=[l.data];break;case 9:a=!0,e.audFound=!0,(u=o)!=null&&u.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:a=!0;break;default:a=!1}o&&a&&o.units.push(l)}),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){const t=new Jt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s,r=8,n=8;for(let a=0;a<e;a++)n!==0&&(s=t.readEG(),n=(r+s+256)%256),r=n===0?r:n}readSPS(e){const t=new Jt(e);let s,r,n,a=0,o=0,h=0,l=0;const d=t.readUByte.bind(t),u=t.readBits.bind(t),c=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),p=t.skipEG.bind(t),v=t.skipUEG.bind(t),y=this.skipScalingList.bind(this);d();const E=d();if(u(5),g(3),d(),v(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){const k=c();if(k===3&&g(1),v(),v(),g(1),f())for(r=k!==3?8:12,n=0;n<r;n++)f()&&y(n<6?16:64,t)}v();const T=c();if(T===0)c();else if(T===1)for(g(1),p(),p(),s=c(),n=0;n<s;n++)p();v(),g(1);const A=c(),L=c(),b=u(1);b===0&&g(1),g(1),f()&&(a=c(),o=c(),h=c(),l=c());let S=[1,1];if(f()&&f())switch(d()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[d()<<8|d(),d()<<8|d()]}return{width:Math.ceil(16*(A+1)-2*a-2*o),height:(2-b)*(L+1)*16-(b?2:4)*(h+l),pixelRatio:S}}}class cl extends Ba{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,r){const n=this.parseNALu(e,s.data,r);let a,o=this.VideoSample,h=!1;s.data=null,o&&n.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.forEach(l=>{var d,u;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),o.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:var c;a=!0,h&&(c=o)!=null&&c.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),o.key=!0,o.frame=!0;break;case 19:case 20:a=!0,(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),o.key=!0,o.frame=!0;break;case 39:a=!0,Vi(l.data,2,s.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ae(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(a=!0,h=!0,e.vps===void 0||e.vps[0]===this.initVPS||e.sps===void 0||this.matchSPS(e.sps[0],l.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(l.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const g in f.params)e.params[g]=f.params[g]}this.pushParameterSet(e.sps,l.data,e.vps),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),o.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(l.data);for(const g in f)e.params[g]=f[g]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(u=o)!=null&&u.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:a=!1}o&&a&&o.units.push(l)}),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[s]=e[r],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Jt(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){const t=new Jt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const r=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),h=t.readUByte(),l=t.readUByte(),d=t.readUByte(),u=t.readUByte(),c=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),v=t.readUByte(),y=t.readUByte(),E=[],T=[];for(let K=0;K<s;K++)E.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let K=s;K<8;K++)t.readBits(2);for(let K=0;K<s;K++)E[K]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[K]&&t.readUByte();t.readUEG();const A=t.readUEG();A==3&&t.skipBits(1);const L=t.readUEG(),b=t.readUEG(),S=t.readBoolean();let k=0,D=0,P=0,O=0;S&&(k+=t.readUEG(),D+=t.readUEG(),P+=t.readUEG(),O+=t.readUEG());const N=t.readUEG(),B=t.readUEG(),F=t.readUEG();for(let K=t.readBoolean()?0:s;K<=s;K++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let K=0;K<4;K++)for(let Q=0;Q<(K===3?2:6);Q++)if(t.readBoolean()){const he=Math.min(64,1<<4+(K<<1));K>1&&t.readEG();for(let de=0;de<he;de++)t.readEG()}else t.readUEG();t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const w=t.readUEG();let _=0;for(let K=0;K<w;K++){let Q=!1;if(K!==0&&(Q=t.readBoolean()),Q){K===w&&t.readUEG(),t.readBoolean(),t.readUEG();let he=0;for(let de=0;de<=_;de++){const ie=t.readBoolean();let ge=!1;ie||(ge=t.readBoolean()),(ie||ge)&&he++}_=he}else{const he=t.readUEG(),de=t.readUEG();_=he+de;for(let ie=0;ie<he;ie++)t.readUEG(),t.readBoolean();for(let ie=0;ie<de;ie++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const K=t.readUEG();for(let Q=0;Q<K;Q++){for(let he=0;he<F+4;he++)t.readBits(1);t.readBits(1)}}let $=0,x=1,C=1,M=!0,V=1,Y=0;t.readBoolean(),t.readBoolean();let W=!1;if(t.readBoolean()){if(t.readBoolean()){const K=t.readUByte();K>0&&K<16?(x=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][K-1],C=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][K-1]):K===255&&(x=t.readBits(16),C=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),W=t.readBoolean(),W&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(V=t.readBits(32),Y=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const K=t.readBoolean(),Q=t.readBoolean();let he=!1;(K||Q)&&(he=t.readBoolean(),he&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),he&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let de=0;de<=s;de++){M=t.readBoolean();let ie=!1;M||t.readBoolean()?t.readEG():ie=t.readBoolean();const ge=ie?1:t.readUEG()+1;if(K)for(let se=0;se<ge;se++)t.readUEG(),t.readUEG(),he&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Q)for(let se=0;se<ge;se++)t.readUEG(),t.readUEG(),he&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),$=t.readUEG())}let G=L,X=b;if(S){let K=1,Q=1;A===1?K=Q=2:A==2&&(K=2),G=L-K*D-K*k,X=b-Q*O-Q*P}const j=r?["A","B","C"][r]:"",le=o<<24|h<<16|l<<8|d;let te=0;for(let K=0;K<32;K++)te=(te|(le>>K&1)<<31-K)>>>0;let Ee=te.toString(16);return a===1&&Ee==="2"&&(Ee="6"),{codecString:`hvc1.${j}${a}.${Ee}.${n?"H":"L"}${y}.B0`,params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,h,l,d],general_constraint_indicator_flags:[u,c,f,g,p,v],general_level_idc:y,bit_depth:N+8,bit_depth_luma_minus8:N,bit_depth_chroma_minus8:B,min_spatial_segmentation_idc:$,chroma_format_idc:A,frame_rate:{fixed:M,fps:Y/V}},width:G,height:X,pixelRatio:[x,C]}}readPPS(e){const t=new Jt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const s=t.readBoolean(),r=t.readBoolean();let n=1;return r&&s?n=0:r?n=3:s&&(n=2),{parallelismType:n}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const Ae=188;class ht{constructor(e,t,s,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=r,this.videoParser=null}static probe(e,t){const s=ht.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(940,t-Ae)+1,r=0;for(;r<s;){let n=!1,a=-1,o=0;for(let h=r;h<t;h+=Ae){if(e[h]!==71||t-h!==Ae&&e[h+Ae]!==71){if(o)return-1;break}if(o++,a===-1&&(a=h,a!==0&&(s=Math.min(a+18612,e.length-Ae)+1)),n||(n=Ci(e,h)===0),n&&o>1&&(a===0&&o>2||h+Ae>s))return a}r++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Wn[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ht.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=ht.createTrack("audio",r),this._id3Track=ht.createTrack("id3"),this._txtTrack=ht.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,r=!1){let n;s||(this.sampleAes=null);const a=this._videoTrack,o=this._audioTrack,h=this._id3Track,l=this._txtTrack;let d=a.pid,u=a.pesData,c=o.pid,f=h.pid,g=o.pesData,p=h.pesData,v=null,y=this.pmtParsed,E=this._pmtId,T=e.length;if(this.remainderData&&(T=(e=Ne(this.remainderData,e)).length,this.remainderData=null),T<Ae&&!r)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:h,textTrack:l};const A=Math.max(0,ht.syncOffset(e));T-=(T-A)%Ae,T<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let L=0;for(let S=A;S<T;S+=Ae)if(e[S]===71){const k=!!(64&e[S+1]),D=Ci(e,S);let P;if((48&e[S+3])>>4>1){if(P=S+5+e[S+4],P===S+Ae)continue}else P=S+4;switch(D){case d:k&&(u&&(n=kt(u,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,l,n,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(P,S+Ae)),u.size+=S+Ae-P);break;case c:if(k){if(g&&(n=kt(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n)}g={data:[],size:0}}g&&(g.data.push(e.subarray(P,S+Ae)),g.size+=S+Ae-P);break;case f:k&&(p&&(n=kt(p,this.logger))&&this.parseID3PES(h,n),p={data:[],size:0}),p&&(p.data.push(e.subarray(P,S+Ae)),p.size+=S+Ae-P);break;case 0:k&&(P+=e[P]+1),E=this._pmtId=fl(e,P);break;case E:{k&&(P+=e[P]+1);const O=gl(e,P,this.typeSupported,s,this.observer,this.logger);d=O.videoPid,d>0&&(a.pid=d,a.segmentCodec=O.segmentVideoCodec),c=O.audioPid,c>0&&(o.pid=c,o.segmentCodec=O.segmentAudioCodec),f=O.id3Pid,f>0&&(h.pid=f),v===null||y||(this.logger.warn(`MPEG-TS PMT found at ${S} after unknown PID '${v}'. Backtracking to sync byte @${A} to parse all TS packets.`),v=null,S=A-188),y=this.pmtParsed=!0;break}case 17:case 8191:break;default:v=D}}else L++;L>0&&_i(this.observer,new Error(`Found ${L} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=u,o.pesData=g,h.pesData=p;const b={audioTrack:o,videoTrack:a,id3Track:h,textTrack:l};return r&&this.extractRemainingSamples(b),b}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:r,textTrack:n}=e,a=s.pesData,o=t.pesData,h=r.pesData;let l;if(a&&(l=kt(a,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,n,l,!0),s.pesData=null)):s.pesData=a,o&&(l=kt(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l)}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;h&&(l=kt(h,this.logger))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=h}demuxSampleAes(e,t,s){const r=this.demux(e,s,!0,!this.config.progressive),n=this.sampleAes=new dl(this.observer,this.config,t);return this.decrypt(r,n)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new ul:e==="hevc"&&(this.videoParser=new cl))}decrypt(e,t){return new Promise(s=>{const{audioTrack:r,videoTrack:n}=e;r.samples&&r.segmentCodec==="aac"?t.decryptAacSamples(r.samples,0,()=>{n.samples?t.decryptAvcSamples(n.samples,0,0,()=>{s(e)}):s(e)}):n.samples&&t.decryptAvcSamples(n.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const r=this.aacOverFlow;let n,a,o,h=t.data;if(r){this.aacOverFlow=null;const u=r.missing,c=r.sample.unit.byteLength;if(u===-1)h=Ne(r.sample.unit,h);else{const f=c-u;r.sample.unit.set(h.subarray(0,u),f),e.samples.push(r.sample),s=r.missing}}for(n=s,a=h.length;n<a-1&&!Ks(h,n);n++);if(n!==s){let u;const c=n<a-1;if(u=c?`AAC PES did not start with ADTS header,offset:${n}`:"No ADTS header found in AAC PES",_i(this.observer,new Error(u),c,this.logger),!c)return}if(Ca(e,this.observer,h,n,this.audioCodec),t.pts!==void 0)o=t.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const u=_a(e.samplerate);o=r.sample.pts+u}}let l,d=0;for(;n<a;){if(l=wa(e,h,n,o,d),n+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;n<a-1&&!Ks(h,n);n++);}}parseMPEGPES(e,t){const s=t.data,r=s.length;let n=0,a=0;const o=t.pts;if(o!==void 0)for(;a<r;)if(Na(s,a)){const h=Ma(e,s,a,o,n);if(!h)break;a+=h.length,n++}else a++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const s=t.data,r=t.pts;if(r===void 0)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const n=s.length;let a,o=0,h=0;for(;h<n&&(a=$a(e,s,h,r,o++))>0;)h+=a}}parseID3PES(e,t){if(t.pts===void 0)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=ae({},t,{type:this._videoTrack?xe.emsg:xe.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Ci(i,e){return((31&i[e+1])<<8)+i[e+2]}function fl(i,e){return(31&i[e+10])<<8|i[e+11]}function gl(i,e,t,s,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=e+3+((15&i[e+1])<<8|i[e+2])-4;for(e+=12+((15&i[e+10])<<8|i[e+11]);e<o;){const h=Ci(i,e),l=(15&i[e+3])<<8|i[e+4];switch(i[e]){case 207:if(!s){ti("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=h);break;case 21:a.id3Pid===-1&&(a.id3Pid=h);break;case 219:if(!s){ti("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=h);break;case 3:case 4:t.mpeg||t.mp3?a.audioPid===-1&&(a.audioPid=h,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!s){ti("AC-3",n);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=h,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&l>0){let d=e+5,u=l;for(;u>2;){i[d]===106&&(t.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=h,a.segmentAudioCodec="ac3"));const c=i[d+1]+2;d+=c,u-=c}}break;case 194:case 135:return _i(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=h,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}e+=l+5}return a}function _i(i,e,t,s){s.warn(`parsing error: ${e.message}`),i.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function ti(i,e){e.log(`${i} with AES-128-CBC encryption found in unencrypted stream`)}function kt(i,e){let t,s,r,n,a,o=0;const h=i.data;if(!i||i.size===0)return null;for(;h[0].length<19&&h.length>1;)h[0]=Ne(h[0],h[1]),h.splice(1,1);if(t=h[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(s=(t[4]<<8)+t[5],s&&s>i.size-6)return null;const l=t[7];192&l&&(n=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&l?(a=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=t[8];let d=r+9;if(i.size<=d)return null;i.size-=d;const u=new Uint8Array(i.size);for(let c=0,f=h.length;c<f;c++){t=h[c];let g=t.byteLength;if(d){if(d>g){d-=g;continue}t=t.subarray(d),g-=d,d=0}u.set(t,o),o+=g}return s&&(s-=r+3),{data:u,pts:n,dts:a,len:s}}return null}class ml{static getSilentFrame(e,t){if(e==="mp4a.40.2"){if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===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(t===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])}else{if(t===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(t===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(t===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])}}}const at=Math.pow(2,32)-1;class R{static init(){let e;for(e in R.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},R.types)R.types.hasOwnProperty(e)&&(R.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=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]);R.HDLR_TYPES={video:t,audio:s};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);R.STTS=R.STSC=R.STCO=n,R.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),R.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),R.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),R.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),h=new Uint8Array([0,0,0,1]);R.FTYP=R.box(R.types.ftyp,a,h,a,o),R.DINF=R.box(R.types.dinf,R.box(R.types.dref,r))}static box(e,...t){let s=8,r=t.length;const n=r;for(;r--;)s+=t[r].byteLength;const a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=255&s,a.set(e,4),r=0,s=8;r<n;r++)a.set(t[r],s),s+=t[r].byteLength;return a}static hdlr(e){return R.box(R.types.hdlr,R.HDLR_TYPES[e])}static mdat(e){return R.box(R.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(at+1)),r=Math.floor(t%(at+1));return R.box(R.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return R.box(R.types.mdia,R.mdhd(e.timescale||0,e.duration||0),R.hdlr(e.type),R.minf(e))}static mfhd(e){return R.box(R.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return e.type==="audio"?R.box(R.types.minf,R.box(R.types.smhd,R.SMHD),R.DINF,R.stbl(e)):R.box(R.types.minf,R.box(R.types.vmhd,R.VMHD),R.DINF,R.stbl(e))}static moof(e,t,s){return R.box(R.types.moof,R.mfhd(e),R.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=R.trak(e[t]);return R.box.apply(null,[R.types.moov,R.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(R.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=R.trex(e[t]);return R.box.apply(null,[R.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(at+1)),r=Math.floor(t%(at+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,s>>24,s>>16&255,s>>8&255,255&s,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return R.box(R.types.mvhd,n)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let r,n;for(r=0;r<t.length;r++)n=t[r].flags,s[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return R.box(R.types.sdtp,s)}static stbl(e){return R.box(R.types.stbl,R.stsd(e),R.box(R.types.stts,R.STTS),R.box(R.types.stsc,R.STSC),R.box(R.types.stsz,R.STSZ),R.box(R.types.stco,R.STCO))}static avc1(e){let t,s,r,n=[],a=[];for(t=0;t<e.sps.length;t++)s=e.sps[t],r=s.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(s));for(t=0;t<e.pps.length;t++)s=e.pps[t],r=s.byteLength,a.push(r>>>8&255),a.push(255&r),a=a.concat(Array.prototype.slice.call(s));const o=R.box(R.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(a))),h=e.width,l=e.height,d=e.pixelRatio[0],u=e.pixelRatio[1];return R.box(R.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,255&h,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,u>>24,u>>16&255,u>>8&255,255&u])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return R.box(R.types.mp4a,R.audioStsd(e),R.box(R.types.esds,R.esds(e)))}static mp3(e){return R.box(R.types[".mp3"],R.audioStsd(e))}static ac3(e){return R.box(R.types["ac-3"],R.audioStsd(e),R.box(R.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return R.box(R.types.stsd,R.STSD,R.mp4a(e));if(t==="ac3"&&e.config)return R.box(R.types.stsd,R.STSD,R.ac3(e));if(t==="mp3"&&e.codec==="mp3")return R.box(R.types.stsd,R.STSD,R.mp3(e))}else{if(!e.pps||!e.sps)throw new Error("video track missing pps or sps");if(t==="avc")return R.box(R.types.stsd,R.STSD,R.avc1(e));if(t==="hevc"&&e.vps)return R.box(R.types.stsd,R.STSD,R.hvc1(e))}throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),r=e.width||0,n=e.height||0,a=Math.floor(s/(at+1)),o=Math.floor(s%(at+1));return R.box(R.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,n>>8&255,255&n,0,0]))}static traf(e,t){const s=R.sdtp(e),r=e.id,n=Math.floor(t/(at+1)),a=Math.floor(t%(at+1));return R.box(R.types.traf,R.box(R.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),R.box(R.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a])),R.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,R.box(R.types.trak,R.tkhd(e),R.mdia(e))}static trex(e){const t=e.id;return R.box(R.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],r=s.length,n=12+16*r,a=new Uint8Array(n);let o,h,l,d,u,c;for(t+=8+n,a.set([e.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),o=0;o<r;o++)h=s[o],l=h.duration,d=h.size,u=h.flags,c=h.cts,a.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,61440&u.degradPrio,15&u.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*o);return R.box(R.types.trun,a)}static initSegment(e){R.types||R.init();const t=R.moov(e);return Ne(R.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let n=r.length;for(let f=0;f<s.length;f+=1){n+=3;for(let g=0;g<s[f].length;g+=1)n+=2+s[f][g].length}const a=new Uint8Array(n);a.set(r,0),n=r.length;const o=s.length-1;for(let f=0;f<s.length;f+=1){a.set(new Uint8Array([32+f|(f===o?128:0),0,s[f].length]),n),n+=3;for(let g=0;g<s[f].length;g+=1)a.set(new Uint8Array([s[f][g].length>>8,255&s[f][g].length]),n),n+=2,a.set(s[f][g],n),n+=s[f][g].length}const h=R.box(R.types.hvcC,a),l=e.width,d=e.height,u=e.pixelRatio[0],c=e.pixelRatio[1];return R.box(R.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,d>>8&255,255&d,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),h,R.box(R.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),R.box(R.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,c>>24,c>>16&255,c>>8&255,255&c])))}}R.types=void 0,R.HDLR_TYPES=void 0,R.STTS=void 0,R.STSC=void 0,R.STCO=void 0,R.STSZ=void 0,R.VMHD=void 0,R.SMHD=void 0,R.STSD=void 0,R.FTYP=void 0,R.DINF=void 0;function nr(i,e,t=1,s=!1){const r=i*e*t;return s?Math.round(r):r}function Vt(i,e=!1){return nr(i,1e3,1/9e4,e)}function cn(i){const{baseTime:e,timescale:t,trackId:s}=i;return`${e/t} (${e}/${t}) trackId: ${s}`}let st,Dt=null,si=null;function fn(i,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:i?2:1,isNonSync:i?0:1}}}class Ps extends Fe{constructor(e,t,s,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,Dt===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Dt=n?parseInt(n[1]):0}if(si===null){const n=navigator.userAgent.match(/Safari\/(\d+)/i);si=n?parseInt(n[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t&&cn(t)} > ${e&&cn(e)}`),this._initPTS=this._initDTS=e}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(e){let t=!1;const s=e[0].pts,r=e.reduce((n,a)=>{let o=a.pts,h=o-n;return h<-4294967296&&(t=!0,o=Ce(o,s),h=o-n),h>0?n:o},s);return t&&this.debug("PTS rollover detected"),r}remux(e,t,s,r,n,a,o,h){let l,d,u,c,f,g,p=n,v=n;const y=e.pid>-1,E=t.pid>-1,T=t.samples.length,A=e.samples.length>0,L=o&&T>0||T>1;if((!y||A)&&(!E||L)||this.ISGenerated||o){if(this.ISGenerated){var b,S,k,D;const B=this.videoTrackConfig;(B&&(t.width!==B.width||t.height!==B.height||((b=t.pixelRatio)==null?void 0:b[0])!==((S=B.pixelRatio)==null?void 0:S[0])||((k=t.pixelRatio)==null?void 0:k[1])!==((D=B.pixelRatio)==null?void 0:D[1]))||!B&&L||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,n,a));const P=this.isVideoContiguous;let O,N=-1;if(L&&(N=function(B){for(let F=0;F<B.length;F++)if(B[F].key)return F;return-1}(t.samples),!P&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,N>0){this.warn(`Dropped ${N} out of ${T} video samples due to a missing keyframe`);const B=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(N),t.dropped+=N,v+=(t.samples[0].pts-B)/t.inputTimeScale,O=v}else N===-1&&(this.warn(`No keyframe found out of ${T} video samples`),g=!1);if(this.ISGenerated){if(A&&L){const B=this.getVideoStartPts(t.samples),F=(Ce(e.samples[0].pts,B)-B)/t.inputTimeScale;p+=Math.max(0,F),v+=Math.max(0,-F)}if(A){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,n,a)),d=this.remuxAudio(e,p,this.isAudioContiguous,a,E||L||h===ke?v:void 0),L){const B=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,n,a)),l=this.remuxVideo(t,v,P,B)}}else L&&(l=this.remuxVideo(t,v,P,0));l&&(l.firstKeyFrame=N,l.independent=N!==-1,l.firstKeyFramePTS=O)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=Ga(s,n,this._initPTS,this._initDTS)),r.samples.length&&(c=Ka(r,n,this._initPTS))),{audio:d,video:l,initSegment:u,independent:g,text:c,id3:f}}computeInitPts(e,t,s,r){const n=Math.round(s*t);let a=Ce(e,n);if(a<n+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-a)/t} ${r}`);a<n+t;)a+=8589934592;return a-n}generateIS(e,t,s,r){const n=e.samples,a=t.samples,o=this.typeSupported,h={},l=this._initPTS;let d,u,c,f=!l||r,g="audio/mp4",p=-1;if(f&&(d=u=1/0),e.config&&n.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(g="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}h.audio={id:"audio",container:g,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):R.initSegment([e]),metadata:{channelCount:e.channelCount}},f&&(p=e.id,c=e.inputTimeScale,l&&c===l.timescale?f=!1:d=u=this.computeInitPts(n[0].pts,c,s,"audio"))}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,h.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:R.initSegment([t]),metadata:{width:t.width,height:t.height}},f)if(p=t.id,c=t.inputTimeScale,l&&c===l.timescale)f=!1;else{const v=this.getVideoStartPts(a),y=Ce(a[0].dts,v),E=this.computeInitPts(y,c,s,"video"),T=this.computeInitPts(v,c,s,"video");u=Math.min(u,E),d=Math.min(d,T)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(h).length)return this.ISGenerated=!0,f?(l&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${s} ${d/c} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/c} (${d}/${c}) trackId: ${p}`),this._initPTS={baseTime:d,timescale:c,trackId:p},this._initDTS={baseTime:u,timescale:c,trackId:p}):d=c=void 0,{tracks:h,initPTS:d,timescale:c,trackId:p}}remuxVideo(e,t,s,r){const n=e.inputTimeScale,a=e.samples,o=[],h=a.length,l=this._initPTS,d=l.baseTime*n/l.timescale;let u,c,f=this.nextVideoTs,g=8,p=this.videoSampleDuration,v=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,E=!1;if(!s||f===null){const C=d+t*n,M=a[0].pts-Ce(a[0].dts,a[0].pts);Dt&&f!==null&&Math.abs(C-M-(f+d))<15e3?s=!0:f=C-M-d}const T=f+d;for(let C=0;C<h;C++){const M=a[C];M.pts=Ce(M.pts,T),M.dts=Ce(M.dts,T),M.dts<a[C>0?C-1:C].dts&&(E=!0)}E&&a.sort(function(C,M){const V=C.dts-M.dts,Y=C.pts-M.pts;return V||Y}),u=a[0].dts,c=a[a.length-1].dts;const A=c-u,L=A?Math.round(A/(h-1)):p||e.inputTimeScale/30;if(s){const C=u-T,M=C>L,V=C<-1;if((M||V)&&(M?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Vt(C,!0)} ms (${C}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Vt(-C,!0)} ms (${C}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!V||T>=a[0].pts||Dt)){u=T;const Y=a[0].pts-C;if(M)a[0].dts=u,a[0].pts=Y;else{let W=!0;for(let G=0;G<a.length&&!(a[G].dts>Y&&W);G++){const X=a[G].pts;if(a[G].dts-=C,a[G].pts-=C,G<a.length-1){const j=a[G+1].pts;W=j<=a[G].pts==j<=X}}}this.log(`Video: Initial PTS/DTS adjusted: ${Vt(Y,!0)}/${Vt(u,!0)}, delta: ${Vt(C,!0)} ms`)}}u=Math.max(0,u);let b=0,S=0,k=u;for(let C=0;C<h;C++){const M=a[C],V=M.units,Y=V.length;let W=0;for(let G=0;G<Y;G++)W+=V[G].data.length;S+=W,b+=Y,M.length=W,M.dts<k?(M.dts=k,k+=L/4|0||1):k=M.dts,v=Math.min(M.pts,v),y=Math.max(M.pts,y)}c=a[h-1].dts;const D=S+4*b+8;let P;try{P=new Uint8Array(D)}catch(C){return void this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:I.REMUX_ALLOC_ERROR,fatal:!1,error:C,bytes:D,reason:`fail allocating video mdat ${D}`})}const O=new DataView(P.buffer);O.setUint32(0,D),P.set(R.types.mdat,4);let N=!1,B=Number.POSITIVE_INFINITY,F=Number.POSITIVE_INFINITY,w=Number.NEGATIVE_INFINITY,_=Number.NEGATIVE_INFINITY;for(let C=0;C<h;C++){const M=a[C],V=M.units;let Y,W=0;for(let X=0,j=V.length;X<j;X++){const le=V[X],te=le.data,Ee=le.data.byteLength;O.setUint32(g,Ee),g+=4,P.set(te,g),g+=Ee,W+=4+Ee}if(C<h-1)p=a[C+1].dts-M.dts,Y=a[C+1].pts-M.pts;else{const X=this.config,j=C>0?M.dts-a[C-1].dts:L;if(Y=C>0?M.pts-a[C-1].pts:L,X.stretchShortVideoTrack&&this.nextAudioTs!==null){const le=Math.floor(X.maxBufferHole*n),te=(r?v+r*n:this.nextAudioTs+d)-M.pts;te>le?(p=te-j,p<0?p=j:N=!0,this.log(`It is approximately ${te/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=j}else p=j}const G=Math.round(M.pts-M.dts);B=Math.min(B,p),w=Math.max(w,p),F=Math.min(F,Y),_=Math.max(_,Y),o.push(fn(M.key,p,W,G))}if(o.length){if(Dt){if(Dt<70){const C=o[0].flags;C.dependsOn=2,C.isNonSync=0}}else if(si&&_-F<w-B&&L/w<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let C=u;for(let M=0,V=o.length;M<V;M++){const Y=C+o[M].duration,W=C+o[M].cts;if(M<V-1){const G=Y+o[M+1].cts;o[M].duration=G-W}else o[M].duration=M?o[M-1].duration:L;o[M].cts=0,C=Y}}}p=N||!p?L:p;const $=c+p;this.nextVideoTs=f=$-d,this.videoSampleDuration=p,this.isVideoContiguous=!0;const x={data1:R.moof(e.sequenceNumber++,u,ae(e,{samples:o})),data2:P,startPTS:(v-d)/n,endPTS:(y+p-d)/n,startDTS:(u-d)/n,endDTS:f/n,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,x}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,s,r,n){const a=e.inputTimeScale,o=a/(e.samplerate?e.samplerate:a),h=this.getSamplesPerFrame(e),l=h*o,d=this._initPTS,u=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,c=[],f=n!==void 0;let g=e.samples,p=u?0:8,v=this.nextAudioTs||-1;const y=d.baseTime*a/d.timescale,E=y+t*a;if(this.isAudioContiguous=s=s||g.length&&v>0&&(r&&Math.abs(E-(v+y))<9e3||Math.abs(Ce(g[0].pts,E)-(v+y))<20*l),g.forEach(function(F){F.pts=Ce(F.pts,E)}),!s||v<0){const F=g.length;if(g=g.filter(w=>w.pts>=0),F!==g.length&&this.warn(`Removed ${g.length-F} of ${F} samples (initPTS ${y} / ${a})`),!g.length)return;v=n===0?0:r&&!f?Math.max(0,E-y):g[0].pts-y}if(e.segmentCodec==="aac"){const F=this.config.maxAudioFramesDrift;for(let w=0,_=v+y;w<g.length;w++){const $=g[w],x=$.pts,C=x-_,M=Math.abs(1e3*C/a);if(C<=-F*l&&f)w===0&&(this.warn(`Audio frame @ ${(x/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*C/a)} ms.`),this.nextAudioTs=v=x-y,_=x);else if(C>=F*l&&M<1e4&&f){let V=Math.round(C/l);for(_=x-V*l;_<0&&V&&l;)V--,_+=l;w===0&&(this.nextAudioTs=v=_-y),this.warn(`Injecting ${V} audio frames @ ${((_-y)/a).toFixed(3)}s due to ${Math.round(1e3*C/a)} ms gap.`);for(let Y=0;Y<V;Y++){let W=ml.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);W||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),W=$.unit.subarray()),g.splice(w,0,{unit:W,pts:_}),_+=l,w++}}$.pts=_,_+=l}}let T,A=null,L=null,b=0,S=g.length;for(;S--;)b+=g[S].unit.byteLength;for(let F=0,w=g.length;F<w;F++){const _=g[F],$=_.unit;let x=_.pts;if(L!==null)c[F-1].duration=Math.round((x-L)/o);else{if(s&&e.segmentCodec==="aac"&&(x=v+y),A=x,!(b>0))return;b+=p;try{T=new Uint8Array(b)}catch(M){return void this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:I.REMUX_ALLOC_ERROR,fatal:!1,error:M,bytes:b,reason:`fail allocating audio mdat ${b}`})}u||(new DataView(T.buffer).setUint32(0,b),T.set(R.types.mdat,4))}T.set($,p);const C=$.byteLength;p+=C,c.push(fn(!0,h,C,0)),L=x}const k=c.length;if(!k)return;const D=c[c.length-1];v=L-y,this.nextAudioTs=v+o*D.duration;const P=u?new Uint8Array(0):R.moof(e.sequenceNumber++,A/o,ae({},e,{samples:c}));e.samples=[];const O=(A-y)/a,N=this.nextAudioTs/a,B={data1:P,data2:T,startPTS:O,endPTS:N,startDTS:O,endDTS:N,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,B}}function Ce(i,e){let t;if(e===null)return i;for(t=e<i?-8589934592:8589934592;Math.abs(i-e)>4294967296;)i+=t;return i}function Ga(i,e,t,s){const r=i.samples.length;if(!r)return;const n=i.inputTimeScale;for(let o=0;o<r;o++){const h=i.samples[o];h.pts=Ce(h.pts-t.baseTime*n/t.timescale,e*n)/n,h.dts=Ce(h.dts-s.baseTime*n/s.timescale,e*n)/n}const a=i.samples;return i.samples=[],{samples:a}}function Ka(i,e,t){const s=i.samples.length;if(!s)return;const r=i.inputTimeScale;for(let a=0;a<s;a++){const o=i.samples[a];o.pts=Ce(o.pts-t.baseTime*r/t.timescale,e*r)/r}i.samples.sort((a,o)=>a.pts-o.pts);const n=i.samples;return i.samples=[],{samples:n}}function gs(i,e,t=!1){return i?.start!==void 0?(i.start+(t?i.duration:0))/i.timescale:e}function gn(i,e,t){const s=i.codec;return s&&s.length>4?s:e===Oe?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Os(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}try{st=self.performance.now.bind(self.performance)}catch{st=Date.now}const Cs=[{demux:class{constructor(i,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(i,e,t,s){const r=this.videoTrack=je("video",1),n=this.audioTrack=je("audio",1),a=this.txtTrack=je("text",1);if(this.id3Track=je("id3",1),this.timeOffset=0,i==null||!i.byteLength)return;const o=Tr(i);if(o.video){const{id:h,timescale:l,codec:d,supplemental:u}=o.video;r.id=h,r.timescale=a.timescale=l,r.codec=d,r.supplemental=u}if(o.audio){const{id:h,timescale:l,codec:d}=o.audio;n.id=h,n.timescale=l,n.codec=d}a.id=Wn.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(i){return function(e){const t=e.byteLength;for(let s=0;s<t;){const r=q(e,s);if(r>8&&e[s+4]===109&&e[s+5]===111&&e[s+6]===111&&e[s+7]===102)return!0;s=r>1?s+r:t}return!1}(i)}demux(i,e){this.timeOffset=e;let t=i;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(t=Ne(this.remainderData,i));const a=function(o){const h={valid:null,remainder:null},l=ee(o,["moof"]);if(l.length<2)return h.remainder=o,h;const d=l[l.length-1];return h.valid=o.slice(0,d.byteOffset-8),h.remainder=o.slice(d.byteOffset-8),h}(t);this.remainderData=a.remainder,s.samples=a.valid||new Uint8Array}else s.samples=t;const n=this.extractID3Track(s,e);return r.samples=Sr(e,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const i=this.timeOffset,e=this.videoTrack,t=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(e,this.timeOffset);return t.samples=Sr(i,e),{videoTrack:e,audioTrack:je(),id3Track:s,textTrack:je()}}extractID3Track(i,e){const t=this.id3Track;if(i.samples.length){const s=ee(i.samples,["emsg"]);s&&s.forEach(r=>{const n=function(a){const o=a[0];let h="",l="",d=0,u=0,c=0,f=0,g=0,p=0;if(o===0){for(;Se(a.subarray(p,p+1))!=="\0";)h+=Se(a.subarray(p,p+1)),p+=1;for(h+=Se(a.subarray(p,p+1)),p+=1;Se(a.subarray(p,p+1))!=="\0";)l+=Se(a.subarray(p,p+1)),p+=1;l+=Se(a.subarray(p,p+1)),p+=1,d=q(a,12),u=q(a,16),f=q(a,20),g=q(a,24),p=28}else if(o===1){p+=4,d=q(a,p),p+=4;const v=q(a,p);p+=4;const y=q(a,p);for(p+=4,c=4294967296*v+y,co(c)||(c=Number.MAX_SAFE_INTEGER,ne.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),f=q(a,p),p+=4,g=q(a,p),p+=4;Se(a.subarray(p,p+1))!=="\0";)h+=Se(a.subarray(p,p+1)),p+=1;for(h+=Se(a.subarray(p,p+1)),p+=1;Se(a.subarray(p,p+1))!=="\0";)l+=Se(a.subarray(p,p+1)),p+=1;l+=Se(a.subarray(p,p+1)),p+=1}return{schemeIdUri:h,value:l,timeScale:d,presentationTime:c,presentationTimeDelta:u,eventDuration:f,id:g,payload:a.subarray(p,a.byteLength)}}(r);if(hl.test(n.schemeIdUri)){const a=un(n,e);let o=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;o<=.001&&(o=Number.POSITIVE_INFINITY);const h=n.payload;t.samples.push({data:h,len:h.byteLength,dts:a,pts:a,type:xe.emsg,duration:o})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=un(n,e);t.samples.push({data:n.payload,len:n.payload.byteLength,dts:a,pts:a,type:xe.misbklv,duration:Number.POSITIVE_INFINITY})}})}return t}demuxSampleAes(i,e,t){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends Fe{constructor(i,e,t,s){super("passthrough-remuxer",s),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(i){this.lastEndTime=null;const e=this.initPTS;e&&i&&e.baseTime===i.baseTime&&e.timescale===i.timescale||(this.initPTS=i)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(i,e,t,s){this.audioCodec=e,this.videoCodec=t,this.generateInitSegment(i,s),this.emitInitSegment=!0}generateInitSegment(i,e){let{audioCodec:t,videoCodec:s}=this;if(i==null||!i.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,video:n}=this.initData=Tr(i);if(e)(function(o,h){if(!o||!h)return;const l=h.keyId;l&&h.isCommonEncryption&&Xn(o,(d,u)=>{const c=d.subarray(8,24);c.some(f=>f!==0)||(ne.log(`[eme] Patching keyId in 'enc${u?"a":"v"}>sinf>>tenc' box: ${Le(c)} -> ${Le(l)}`),d.set(l,8))})})(i,e);else{const o=r||n;o!=null&&o.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${o.codec}")!`)}r&&(t=gn(r,Oe,this)),n&&(s=gn(n,Ge,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:t+","+s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:i,id:"main"}:r?a.audio={container:"audio/mp4",codec:t,encrypted:r.encrypted,initSegment:i,id:"audio"}:n?a.video={container:"video/mp4",codec:s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:i,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(i,e,t,s,r,n){var a,o;let{initPTS:h,lastEndTime:l}=this;const d={audio:void 0,video:void 0,text:s,id3:t,initSegment:void 0};U(l)||(l=this.lastEndTime=r||0);const u=e.samples;if(!u.length)return d;const c={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((a=f)!=null&&a.length||(this.generateInitSegment(u),f=this.initData),(o=f)==null||!o.length)return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(_,$,x){const C={},M=ee(_,["moof","traf"]);for(let V=0;V<M.length;V++){const Y=M[V],W=ee(Y,["tfhd"])[0],G=q(W,4),X=$[G];if(!X)continue;C[G]||(C[G]={start:NaN,duration:0,sampleCount:0,timescale:X.timescale,type:X.type});const j=C[G],le=ee(Y,["tfdt"])[0];if(le){const ge=le[0];let se=q(le,4);ge===1&&(se===yr?x.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(se*=yr+1,se+=q(le,8))),U(se)&&(!U(j.start)||se<j.start)&&(j.start=se)}const te=X.default,Ee=q(W,0)|te?.flags;let K=te?.duration||0;8&Ee&&(K=q(W,2&Ee?12:8));const Q=ee(Y,["trun"]);let he=j.start||0,de=0,ie=K;for(let ge=0;ge<Q.length;ge++){const se=Q[ge],Me=q(se,4),os=j.sampleCount;j.sampleCount+=Me;const Bt=1&se[3],Tt=4&se[3],ls=1&se[2],Gt=2&se[2],hs=4&se[2],Kt=8&se[2];let Re=8,ue=Me;for(Bt&&(Re+=4),Tt&&Me&&(1&se[Re+1]||j.keyFrameIndex!==void 0||(j.keyFrameIndex=os),Re+=4,ls?(ie=q(se,Re),Re+=4):ie=K,Gt&&(Re+=4),Kt&&(Re+=4),he+=ie,de+=ie,ue--);ue--;)ls?(ie=q(se,Re),Re+=4):ie=K,Gt&&(Re+=4),hs&&(1&se[Re+1]||j.keyFrameIndex===void 0&&(j.keyFrameIndex=j.sampleCount-(ue+1),j.keyFrameStart=he),Re+=4),Kt&&(Re+=4),he+=ie,de+=ie;!de&&K&&(de+=K*Me)}j.duration+=de}if(!Object.keys(C).some(V=>C[V].duration)){let V=1/0,Y=0;const W=ee(_,["sidx"]);for(let G=0;G<W.length;G++){const X=To(W[G]);if(X!=null&&X.references){V=Math.min(V,X.earliestPresentationTime/X.timescale);const j=X.references.reduce((le,te)=>le+te.info.duration||0,0);Y=Math.max(Y,j+X.earliestPresentationTime/X.timescale)}}Y&&U(Y)&&Object.keys(C).forEach(G=>{C[G].duration||(C[G].duration=Y*C[G].timescale-C[G].start)})}return C}(u,f,this),p=f.audio?g[f.audio.id]:null,v=f.video?g[f.video.id]:null,y=gs(v,1/0),E=gs(p,1/0),T=gs(v,0,!0),A=gs(p,0,!0);let L=r,b=0;const S=p&&(!v||!h&&E<y||h&&h.trackId===f.audio.id),k=S?p:v;if(k){const _=k.timescale,$=k.start-r*_,x=S?f.audio.id:f.video.id;L=k.start/_,b=S?A-E:T-y,!n&&h||!function(C,M,V,Y){if(C===null)return!0;const W=Math.max(Y,1),G=M-C.baseTime/C.timescale;return Math.abs(G-V)>W}(h,L,r,b)&&_===h.timescale||(h&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${$/_} != initPTS: ${h.baseTime/h.timescale} (${h.baseTime}/${h.timescale}) trackId: ${h.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${L-r} (${$}/${_}) trackId: ${x}`),h=null,c.initPTS=$,c.timescale=_,c.trackId=x)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);h?(c.initPTS=h.baseTime,c.timescale=h.timescale,c.trackId=h.trackId):(c.timescale&&c.trackId!==void 0&&c.initPTS!==void 0||(this.warn("Could not set initPTS"),c.initPTS=L,c.timescale=1,c.trackId=-1),this.initPTS=h={baseTime:c.initPTS,timescale:c.timescale,trackId:c.trackId});const D=L-h.baseTime/h.timescale,P=D+b;b>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const O=!!f.audio,N=!!f.video;let B="";O&&(B+="audio"),N&&(B+="video");const F={data1:u,startPTS:D,startDTS:D,endPTS:P,endDTS:P,type:B,hasAudio:O,hasVideo:N,nb:1,dropped:0,encrypted:!!f.audio&&f.audio.encrypted||!!f.video&&f.video.encrypted};d.audio=O&&!N?F:void 0,d.video=N?F:void 0;const w=v?.sampleCount;if(w){const _=v.keyFrameIndex,$=_!==-1;F.nb=w,F.dropped=_===0||this.isVideoContiguous?0:$?_:w,F.independent=$,F.firstKeyFrame=_,$&&v.keyFrameStart&&(F.firstKeyFramePTS=(v.keyFrameStart-h.baseTime)/h.timescale),this.isVideoContiguous||(d.independent=$),this.isVideoContiguous||(this.isVideoContiguous=$),F.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${_}/${w} dropped: ${F.dropped} start: ${F.firstKeyFramePTS||"NA"}`)}return d.initSegment=c,d.id3=Ga(t,r,h,h),s.samples.length&&(d.text=Ka(s,r,h)),d}}},{demux:ht,remux:Ps},{demux:class extends Pi{constructor(i,e){super(),this.observer=void 0,this.config=void 0,this.observer=i,this.config=e}resetInitSegment(i,e,t,s){super.resetInitSegment(i,e,t,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(i,e){if(!i)return!1;const t=rs(i,0);let s=t?.length||0;if(dn(i,s))return!1;for(let r=i.length;s<r;s++)if(Qo(i,s))return e.log("ADTS sync word found !"),!0;return!1}canParse(i,e){return function(t,s){return function(r,n){return n+5<r.length}(t,s)&&Da(t,s)&&sr(t,s)<=t.length-s}(i,e)}appendFrame(i,e,t){Ca(i,this.observer,e,t,i.manifestCodec);const s=wa(i,e,t,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}},remux:Ps},{demux:class extends Pi{resetInitSegment(i,e,t,s){super.resetInitSegment(i,e,t,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(i){if(!i)return!1;const e=rs(i,0);let t=e?.length||0;if(e&&i[t]===11&&i[t+1]===119&&ir(e)!==void 0&&Ua(i,t)<=16)return!1;for(let s=i.length;t<s;t++)if(dn(i,t))return ne.log("MPEG Audio sync word found !"),!0;return!1}canParse(i,e){return function(t,s){return rr(t,s)&&4<=t.length-s}(i,e)}appendFrame(i,e,t){if(this.basePTS!==null)return Ma(i,e,t,this.basePTS,this.frameIndex)}},remux:Ps}];Cs.splice(2,0,{demux:ll,remux:Ps});class mn{constructor(e,t,s,r,n,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=e,this.typeSupported=t,this.config=s,this.id=n,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,r){const n=s.transmuxing;n.executeStart=st();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:h}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:d,trackSwitch:u,accurateTimeOffset:c,timeOffset:f,initSegmentChange:g}=r||o,{audioCodec:p,videoCodec:v,defaultInitPts:y,duration:E,initSegmentData:T}=h,A=function(k,D){let P=null;return k.byteLength>0&&D?.key!=null&&D.iv!==null&&D.method!=null&&(P=D),P}(a,t);if(A&&xt(A.method)){const k=this.getDecrypter(),D=Qi(A.method);if(!k.isSync())return this.asyncResult=!0,this.decryptionPromise=k.webCryptoDecrypt(a,A.key.buffer,A.iv.buffer,D).then(P=>{const O=this.push(P,null,s);return this.decryptionPromise=null,O}),this.decryptionPromise;{let P=k.softwareDecrypt(a,A.key.buffer,A.iv.buffer,D);if(s.part>-1){const O=k.flush();P=O&&O.buffer}if(!P)return n.executeEnd=st(),ii(s);a=new Uint8Array(P)}}const L=this.needsProbing(d,u);if(L){const k=this.configureTransmuxer(a);if(k)return this.logger.warn(`[transmuxer] ${k.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,error:k,reason:k.message}),n.executeEnd=st(),ii(s)}(d||u||g||L)&&this.resetInitSegment(T,p,v,E,t),(d||g||L)&&this.resetInitialTimestamp(y),l||this.resetContiguity();const b=this.transmux(a,A,f,c,s);this.asyncResult=ns(b);const S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,n.executeEnd=st(),b}flush(e){const t=e.transmuxing;t.executeStart=st();const{decrypter:s,currentTransmuxState:r,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(e));const a=[],{timeOffset:o}=r;if(s){const u=s.flush();u&&a.push(this.push(u.buffer,null,e))}const{demuxer:h,remuxer:l}=this;if(!h||!l){t.executeEnd=st();const u=[ii(e)];return this.asyncResult?Promise.resolve(u):u}const d=h.flush(o);return ns(d)?(this.asyncResult=!0,d.then(u=>(this.flushRemux(a,u,e),a))):(this.flushRemux(a,d,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=t,{accurateTimeOffset:h,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===Z?"level":"track"} ${s.level}`);const d=this.remuxer.remux(r,n,a,o,l,h,!0,this.id);e.push({remuxResult:d,chunkMeta:s}),s.transmuxing.executeEnd=st()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;t&&s&&(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,r,n){const{demuxer:a,remuxer:o}=this;a&&o&&(a.resetInitSegment(e,t,s,r),o.resetInitSegment(e,t,s,n))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,r,n){let a;return a=t&&t.method==="SAMPLE-AES"?this.transmuxSampleAes(e,t,s,r,n):this.transmuxUnencrypted(e,s,r,n),a}transmuxUnencrypted(e,t,s,r){const{audioTrack:n,videoTrack:a,id3Track:o,textTrack:h}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(n,a,o,h,t,s,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,s,r,n){return this.demuxer.demuxSampleAes(e,t,s).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,r,!1,this.id),chunkMeta:n}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:r}=this;let n;for(let u=0,c=Cs.length;u<c;u++){var a;if((a=Cs[u].demux)!=null&&a.probe(e,this.logger)){n=Cs[u];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,h=this.remuxer,l=n.remux,d=n.demux;h&&h instanceof l||(this.remuxer=new l(s,t,r,this.logger)),o&&o instanceof d||(this.demuxer=new d(s,t,r,this.logger),this.probe=d.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Xi(this.config)),e}}const ii=i=>({remuxResult:{},chunkMeta:i});function ns(i){return"then"in i&&i.then instanceof Function}class pl{constructor(e,t,s,r,n){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=r,this.defaultInitPts=n||null}}class vl{constructor(e,t,s,r,n,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=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=r,this.timeOffset=n,this.initSegmentChange=a}}let pn=0;class Ha{constructor(e,t,s,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=pn++,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=h=>{const l=h.data,d=this.hls;if(d&&l!=null&&l.event&&l.instanceNo===this.instanceNo)switch(l.event){case"init":{var u;const c=(u=this.workerContext)==null?void 0:u.objectURL;c&&self.URL.revokeObjectURL(c);break}case"transmuxComplete":this.handleTransmuxComplete(l.data);break;case"flush":this.onFlush(l.data);break;case"workerLog":d.logger[l.data.logType]&&d.logger[l.data.logType](l.data.message);break;default:l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,d.trigger(l.event,l.data)}},this.onWorkerError=h=>{if(!this.hls)return;const l=new Error(`${h.message} (${h.filename}:${h.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:H.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const n=e.config;this.hls=e,this.id=t,this.useWorker=!!n.enableWorker,this.onTransmuxComplete=s,this.onFlush=r;const a=(h,l)=>{(l=l||{}).frag=this.frag||void 0,h===m.ERROR&&(l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(h,l)};this.observer=new er,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);const o=Rr(n.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const h=this.hls.logger;if(n.workerPath||typeof __HLS_WORKER_BUNDLE__=="function"){try{n.workerPath?(h.log(`loading Web Worker ${n.workerPath} for "${t}"`),this.workerContext=function(d){const u=bt[d];if(u)return u.clientCount++,u;const c=new self.URL(d,self.location.href).href,f={worker:new self.Worker(c),scriptURL:c,clientCount:1};return bt[d]=f,f}(n.workerPath)):(h.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){const d=bt[qt];if(d)return d.clientCount++,d;const u=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),c=self.URL.createObjectURL(u),f={worker:new self.Worker(c),objectURL:c,clientCount:1};return bt[qt]=f,f}());const{worker:l}=this.workerContext;l.addEventListener("message",this.onWorkerMessage),l.addEventListener("error",this.onWorkerError),l.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:oe(n)})}catch(l){h.warn(`Error setting up "${t}" Web Worker, fallback to inline`,l),this.terminateWorker(),this.error=null,this.transmuxer=new mn(this.observer,o,n,"",t,e.logger)}return}}this.transmuxer=new mn(this.observer,o,n,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=pn++;const t=this.hls.config,s=Rr(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:oe(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(t){const s=bt[t||qt];if(s&&s.clientCount--===1){const{worker:r,objectURL:n}=s;delete bt[t||qt],n&&self.URL.revokeObjectURL(n),r.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,r,n,a,o,h,l,d){var u,c;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,p=a?a.start:n.start,v=n.decryptdata,y=this.frag,E=!(y&&n.cc===y.cc),T=!(y&&l.level===y.level),A=y?l.sn-y.sn:-1,L=this.part?l.part-this.part.index:-1,b=A===0&&l.id>1&&l.id===y?.stats.chunkCount,S=!T&&(A===1||A===0&&(L===1||b&&L<=0)),k=self.performance.now();(T||A||n.stats.parsing.start===0)&&(n.stats.parsing.start=k),!a||!L&&S||(a.stats.parsing.start=k);const D=!(y&&((u=n.initSegment)==null?void 0:u.url)===((c=y.initSegment)==null?void 0:c.url)),P=new vl(E,S,h,T,p,D);if(!S||E||D){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===Z?"level":"track"}: ${l.level} id: ${l.id}
7
+ discontinuity: ${E}
8
+ trackSwitch: ${T}
9
+ contiguous: ${S}
10
+ accurateTimeOffset: ${h}
11
+ timeOffset: ${p}
12
+ initSegmentChange: ${D}`);const O=new pl(s,r,t,o,d);this.configureTransmuxer(O)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:v,chunkMeta:l,state:P},e instanceof ArrayBuffer?[e]:[]);else if(g){const O=g.push(e,v,l,P);ns(O)?O.then(N=>{this.handleTransmuxComplete(N)}).catch(N=>{this.transmuxerError(N,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(O)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const r=s.flush(e);ns(r)?r.then(n=>{this.handleFlushResult(n,e)}).catch(n=>{this.transmuxerError(n,e,"transmuxer-interface flush error")}):this.handleFlushResult(r,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class wi extends Fe{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const r=t?.renditionReports;if(r){let n=-1;for(let a=0;a<r.length;a++){const o=r[a];let h;try{h=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),h=o.URI||""}if(h===e){n=a;break}h===e.substring(0,h.length)&&(n=a)}if(n!==-1){const a=r[n],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let h=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const d=Math.min(t.age-t.partTarget,t.targetduration);h>=0&&d>t.partTarget&&(h+=1)}const l=s&&br(s);return new kr(o,h>=0?h:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:r,stats:n}=t,a=self.performance.now(),o=n.loading.first?Math.max(0,a-n.loading.first):0;r.advancedDateTime=Date.now()-o;const h=this.hls.config.timelineOffset;if(h!==r.appliedTimelineOffset){const d=Math.max(h||0,0);r.appliedTimelineOffset=d,r.fragments.forEach(u=>{u.setStart(u.playlistOffset+d)})}if(r.live||s!=null&&s.live){const d="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(s),s&&r.fragments.length>0){qo(s,r,this);const y=r.playlistParsingError;if(y){this.warn(y);const E=this.hls;if(!E.config.ignorePlaylistParsingErrors){var l;const{networkDetails:T}=t;return void E.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:I.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:y,reason:y.message,level:t.level||void 0,parent:(l=r.fragments[0])==null?void 0:l.type,networkDetails:T,stats:n})}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=n.loading.start);const u=this.hls.mainForwardBufferInfo,c=u?u.end-u.len:0,f=Ta(r,1e3*(r.edge-c));if(r.requestScheduled+f<a?r.requestScheduled=a:r.requestScheduled+=f,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;let g,p,v;if(r.canBlockReload&&r.endSN&&r.advanced){const y=this.hls.config.lowLatencyMode,E=r.lastPartSn,T=r.endSN,A=r.lastPartIndex,L=E===T;A!==-1?L?(p=T+1,v=y?0:A):(p=E,v=y?A+1:r.maxPartIndex):p=T+1;const b=r.age,S=b+r.ageHeader;let k=Math.min(S-r.partTarget,1.5*r.targetduration);if(k>0){if(S>3*r.targetduration)this.log(`Playlist last advanced ${b.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&S-r.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${k} with playlist age: ${r.age}`),k=0;else{const D=Math.floor(k/r.targetduration);p+=D,v!==void 0&&(v+=Math.round(k%r.targetduration/r.partTarget)),this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${b.toFixed(2)}s goal: ${k} skip sn ${D} to part ${v}`)}r.tuneInGoal=k}if(g=this.getDeliveryDirectives(r,t.deliveryDirectives,p,v),y||!L)return r.requestScheduled=a,void this.loadingPlaylist(d,g)}else(r.canBlockReload||r.canSkipUntil)&&(g=this.getDeliveryDirectives(r,t.deliveryDirectives,p,v));g&&p!==void 0&&r.canBlockReload&&(r.requestScheduled=n.loading.first+Math.max(f-2*o,f/2)),this.scheduleLoading(d,g,r)}else this.clearTimer()}scheduleLoading(e,t,s){const r=s||e.details;if(!r)return void this.loadingPlaylist(e,t);const n=self.performance.now(),a=r.requestScheduled;if(n>=a)return void this.loadingPlaylist(e,t);const o=a-n;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,r){let n=br(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,r=t.part,n=sa),new kr(s,r,n)}checkRetry(e){const t=e.details,s=Fs(e),r=e.errorAction,{action:n,retryCount:a=0,retryConfig:o}=r||{},h=!!r&&!!o&&(n===Us||!r.resolved&&n===We);if(h){var l;if(a>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const d=ji(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),d),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${d}ms`)}e.levelRetry=!0,r.resolved=!0}return h}}function vn(i,e){if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(!Xt(i[t].attrs,e[t].attrs))return!1;return!0}function Xt(i,e,t){const s=i["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>i[r]!==e[r])}function xi(i,e){return e.label.toLowerCase()===i.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(i.lang||"").toLowerCase())}class yl{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const r=this.queues[t];r.push(e),r.length!==1||s||this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;s!=="async-blocker"&&s!=="async-blocker-prepend"||(e[0].execute(),e.splice(0,1))})}unblockAudio(e){this.queues!==null&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const r=t[0];try{r.execute()}catch(n){var s;if(r.onError(n),this.queues===null||this.tracks===null)return;const a=(s=this.tracks[e])==null?void 0:s.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
13
+ ${this.list("video")}
14
+ ${this.list("audio")}
15
+ ${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],r=s?.buffer;return r?`SourceBuffer${r.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const yn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Va="HlsJsTrackRemovedError";class El extends Error{constructor(e){super(e),this.name=Va}}function En(i){const e=i.querySelectorAll("source");[].slice.call(e).forEach(t=>{i.removeChild(t)})}function ri(i){return i==="audio"?1:0}class ar{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&U(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((r,n)=>this.isLevelAllowed(r)&&n<=e);return this.clientRect=null,ar.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,t.width||t.height||(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,s){if(e==null||!e.length)return-1;const r=(o,h)=>!h||o.width!==h.width||o.height!==h.height;let n=e.length-1;const a=Math.max(t,s);for(let o=0;o<e.length;o+=1){const h=e[o];if((h.width>=a||h.height>=a)&&r(h,e[o+1])){n=o;break}}return n}}const be={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Tl={HLS:"h"};class Qe{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof Qe?s:new Qe(s))),this.value=e,this.params=t}}function Sl(i,e,t,s){return new Error(`failed to ${i} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":typeof r=="object"?JSON.stringify(r):String(r)}" as ${t}`,{cause:s});var r}function ze(i,e,t){return Sl("serialize",i,e,t)}class Ya{constructor(e){this.description=e}}const Tn="Bare Item";function Ll(i){if(ArrayBuffer.isView(i)===!1)throw ze(i,"Byte Sequence");return`:${e=i,btoa(String.fromCharCode(...e))}:`;var e}function Sn(i){if(function(e){return e<-999999999999999||999999999999999<e}(i))throw ze(i,"Integer");return i.toString()}function Wa(i,e){if(i<0)return-Wa(-i,e);const t=Math.pow(10,e);if(Math.abs(i*t%1-.5)<Number.EPSILON){const s=Math.floor(i*t);return(s%2==0?s:s+1)/t}return Math.round(i*t)/t}function Al(i){const e=Wa(i,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ze(i,"Decimal");const t=e.toString();return t.includes(".")?t:`${t}.0`}const Rl=/[\x00-\x1f\x7f]+/;function Ln(i){const e=(t=i).description||t.toString().slice(7,-1);var t;if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw ze(e,"Token");return e}function Oi(i){switch(typeof i){case"number":if(!U(i))throw ze(i,Tn);return Number.isInteger(i)?Sn(i):Al(i);case"string":return function(e){if(Rl.test(e))throw ze(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(i);case"symbol":return Ln(i);case"boolean":return function(e){if(typeof e!="boolean")throw ze(e,"Boolean");return e?"?1":"?0"}(i);case"object":if(i instanceof Date)return function(e){return`@${Sn(e.getTime()/1e3)}`}(i);if(i instanceof Uint8Array)return Ll(i);if(i instanceof Ya)return Ln(i);default:throw ze(i,Tn)}}function Mi(i){if(/^[a-z*][a-z0-9\-_.*]*$/.test(i)===!1)throw ze(i,"Key");return i}function Fi(i){return i==null?"":Object.entries(i).map(([e,t])=>t===!0?`;${Mi(e)}`:`;${Mi(e)}=${Oi(t)}`).join("")}function An(i){return i instanceof Qe?`${Oi(i.value)}${Fi(i.params)}`:Oi(i)}function Il(i,e={whitespace:!0}){if(typeof i!="object"||i==null)throw ze(i,"Dict");const t=i instanceof Map?i.entries():Object.entries(i),s=e?.whitespace?" ":"";return Array.from(t).map(([r,n])=>{!(n instanceof Qe)&&(n=new Qe(n));let a=Mi(r);var o;return n.value===!0?a+=Fi(n.params):(a+="=",Array.isArray(n.value)?a+=`(${(o=n).value.map(An).join(" ")})${Fi(o.params)}`:a+=An(n)),a}).join(`,${s}`)}function ja(i,e){return Il(i,e)}const Ve="CMCD-Object",pe="CMCD-Request",ft="CMCD-Session",ot="CMCD-Status",bl={br:Ve,ab:Ve,d:Ve,ot:Ve,tb:Ve,tpb:Ve,lb:Ve,tab:Ve,lab:Ve,url:Ve,pb:pe,bl:pe,tbl:pe,dl:pe,ltc:pe,mtp:pe,nor:pe,nrr:pe,rc:pe,sn:pe,sta:pe,su:pe,ttfb:pe,ttfbb:pe,ttlb:pe,cmsdd:pe,cmsds:pe,smrt:pe,df:pe,cs:pe,ts:pe,cid:ft,pr:ft,sf:ft,sid:ft,st:ft,v:ft,msd:ft,bs:ot,bsd:ot,cdn:ot,rtp:ot,bg:ot,pt:ot,ec:ot,e:ot},kl=pe;function Dl(i,e){const t={};if(!i)return t;const s=Object.keys(i),r=e?(n=e,Object.keys(n).reduce((a,o)=>{var h;return(h=n[o])===null||h===void 0||h.forEach(l=>a[l]=o),a},{})):{};var n;return s.reduce((a,o)=>{var h;const l=bl[o]||r[o]||kl;return((h=a[l])!==null&&h!==void 0?h:a[l]={})[o]=i[o],a},t)}const qa="event",_s=i=>Math.round(i),Ni=(i,e)=>Array.isArray(i)?i.map(t=>Ni(t,e)):i instanceof Qe&&typeof i.value=="string"?new Qe(Ni(i.value,e),i.params):(e.baseUrl&&(i=function(t,s){const r=new URL(t),n=new URL(s);if(r.origin!==n.origin)return t;const a=r.pathname.split("/").slice(1),o=n.pathname.split("/").slice(1,-1);for(;a[0]===o[0];)a.shift(),o.shift();for(;o.length;)o.shift(),a.unshift("..");return a.join("/")+r.search+r.hash}(i,e.baseUrl)),e.version===1?encodeURIComponent(i):i),ms=i=>100*_s(i/100),Pl={br:_s,d:_s,bl:ms,dl:ms,mtp:ms,nor:(i,e)=>{let t=i;return e.version>=2&&(i instanceof Qe&&typeof i.value=="string"?t=new Qe([i]):typeof i=="string"&&(t=[i])),Ni(t,e)},rtp:ms,tb:_s},Xa="request",za="response",ni=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Cl=["e"],_l=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function ws(i){return _l.test(i)}const Rn=["d","dl","nor","ot","rtp","su"],wl=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],xl=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Ol(i){return xl.includes(i)||ws(i)}const Ml={[za]:function(i){return ni.includes(i)||Rn.includes(i)||wl.includes(i)||ws(i)},[qa]:function(i){return ni.includes(i)||Cl.includes(i)||ws(i)},[Xa]:function(i){return ni.includes(i)||Rn.includes(i)||ws(i)}};function Qa(i,e={}){const t={};if(i==null||typeof i!="object")return t;const s=e.version||i.v||1,r=e.reportingMode||Xa,n=s===1?Ol:Ml[r];let a=Object.keys(i).filter(n);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const h=r===za||r===qa;h&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const l=ae({},Pl,e.formatters),d={version:s,reportingMode:r,baseUrl:e.baseUrl};return a.sort().forEach(u=>{let c=i[u];const f=l[u];if(typeof f=="function"&&(c=f(c,d)),u==="v"){if(s===1)return;c=s}u=="pr"&&c===1||(h&&u==="ts"&&!U(c)&&(c=Date.now()),function(g){return typeof g=="number"?U(g):g!=null&&g!==""&&g!==!1}(c)&&(function(g){return["ot","sf","st","e","sta"].includes(g)}(u)&&typeof c=="string"&&(c=new Ya(c)),t[u]=c))}),t}function Fl(i,e,t){return ae(i,function(s,r={}){const n={};if(!s)return n;const a=Dl(Qa(s,r),r?.customHeaderMap);return Object.entries(a).reduce((o,[h,l])=>{const d=ja(l,{whitespace:!1});return d&&(o[h]=d),o},n)}(e,t))}function Nl(i,e={}){if(!i)return"";const t=function(s,r={}){return s?ja(Qa(s,r),{whitespace:!1}):""}(i,e);return encodeURIComponent(t)}const In=/CMCD=[^&#]+/;function Ul(i,e,t){const s=function(n,a={}){return n?`CMCD=${Nl(n,a)}`:""}(e,t);if(!s)return i;if(In.test(i))return i.replace(In,s);const r=i.includes("?")?"&":"?";return`${i}${r}${s}`}function bn(i,e,t,s){i&&Object.keys(e).forEach(r=>{const n=i.filter(a=>a.groupId===r).map(a=>{const o=ae({},a);return o.details=void 0,o.attrs=new ce(o.attrs),o.url=o.attrs.URI=Za(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[r],o.attrs["PATHWAY-ID"]=s,o});i.push(...n)})}function Za(i,e,t,s){const{HOST:r,PARAMS:n,[t]:a}=s;let o;e&&(o=a?.[e],o&&(i=o));const h=new self.URL(i);return r&&!o&&(h.host=r),n&&Object.keys(n).sort().forEach(l=>{l&&h.searchParams.set(l,n[l])}),h.href}class Ft extends Fe{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Ft.CDMCleanupPromise?[Ft.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:r}=t,n=`"${t.type}" event: init data type: "${s}"`;if(this.debug(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=jt(this.config));const o=a.map(Qs).filter(h=>!!h);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=ks(a);if(s!=="sinf"||o!==fe.FAIRPLAY)return void this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);let h;try{const f=Se(new Uint8Array(r)),g=zn(Zi(JSON.parse(f).sinf));if(!g)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");h=new Uint8Array(g.subarray(8,24))}catch(f){return void this.warn(`${n} Failed to parse sinf: ${f}`)}const l=Le(h),{keyIdToKeySessionPromise:d,mediaKeySessions:u}=this;let c=d[l];for(let f=0;f<u.length;f++){const g=u[f],p=g.decryptdata;if(!p.keyId)continue;const v=Le(p.keyId);if($s(h,p.keyId)||p.uri.replace(/-/g,"").indexOf(l)!==-1){if(c=d[v],!c)continue;if(p.pssh)break;delete d[v],p.pssh=new Uint8Array(r),p.keyId=h,c=d[l]=c.then(()=>this.generateRequestWithPreferredKeySession(g,s,r,"encrypted-event-key-match")),c.catch(y=>this.handleError(y));break}}c||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(m.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(m.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,r=t?.[e];return r?r.licenseUrl:e===fe.WIDEVINE&&s?s:void 0}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t?.[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(a,o,h)=>!!a&&h.indexOf(a)===o,r=t.map(a=>a.audioCodec).filter(s),n=t.map(a=>a.videoCodec).filter(s);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const h=l=>{const d=l.shift();this.getMediaKeysPromise(d,r,n).then(u=>a({keySystem:d,mediaKeys:u})).catch(u=>{l.length?h(l):o(u instanceof Pe?u:new Pe({type:H.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};h(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${s}`;return ma===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return s(e,t)}getMediaKeysPromise(e,t,s){var r;const n=function(h,l,d,u){let c;switch(h){case fe.FAIRPLAY:c=["cenc","sinf"];break;case fe.WIDEVINE:case fe.PLAYREADY:c=["cenc"];break;case fe.CLEARKEY:c=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${h}`)}return function(f,g,p,v){return[{initDataTypes:f,persistentState:v.persistentState||"optional",distinctiveIdentifier:v.distinctiveIdentifier||"optional",sessionTypes:v.sessionTypes||[v.sessionType||"temporary"],audioCapabilities:g.map(y=>({contentType:`audio/mp4; codecs=${y}`,robustness:v.audioRobustness||"",encryptionScheme:v.audioEncryptionScheme||null})),videoCapabilities:p.map(y=>({contentType:`video/mp4; codecs=${y}`,robustness:v.videoRobustness||"",encryptionScheme:v.videoEncryptionScheme||null}))}]}(c,l,d,u)}(e,t,s,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(r=a)==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${oe(n)}`),o=this.requestMediaKeySystemAccess(e,n);const h=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const d=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=h.mediaKeys=l.createMediaKeys().then(c=>(this.log(`Media-keys created for "${e}"`),h.hasMediaKeys=!0,d.then(f=>f?this.setMediaKeysServerCertificate(c,e,f):c)));return u.catch(c=>{this.error(`Failed to create media-keys for "${e}"}: ${c}`)}),u})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Le(e.keyId||[])} keyUri: ${e.uri}`);const r=s.createSession(),n={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(n),n}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),r=ps(t),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(s,n,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Le(e.decryptdata.keyId||[])}
16
+ } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Qs(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:r})=>{const n=Qs(r);n?t(n):s(new Error(`Unable to find format for key-system "${r}"`))}).catch(s)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=jt(this.config),s=e.map(ks).filter(r=>!!r&&t.indexOf(r)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const r=$l(e,t[s]);if(r)return r}}loadKey(e){const t=e.keyInfo.decryptdata,s=ps(t),r=this.bannedKeyIds[s];if(r||this.getKeyStatus(t)==="internal-error"){const o=kn(r||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const n=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${n}`);const a=this.keyIdToKeySessionPromise[s];if(!a){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:h,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${n}`),this.attemptSetMediaKeys(h,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:h,mediaKeys:l,decryptdata:t}))))).then(h=>{const l=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(h,"cenc",l,"playlist-key")});return o.catch(h=>this.handleError(h,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return a.catch(o=>{if(o instanceof Pe){const h=re({},o.data);this.getKeyStatus(t)==="internal-error"&&(h.decryptdata=t);const l=new Pe(h,o.message);this.handleError(l,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Pe){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Le(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:H.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=ps(e),s=this.keyIdToKeySessionPromise[t];if(!s){const r=ks(e.keyFormat),n=r?[r]:jt(this.config);return this.attemptKeySystemAccess(n)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=jt(this.config)),e.length===0)throw new Pe({type:H.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${oe({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const r=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(n).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>s.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(e,t,s,r){var n;const a=(n=this.config.drmSystems)==null||(n=n[e.keySystem])==null?void 0:n.generateRequest;if(a)try{const g=a.call(this.hls,t,s,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,s=g.initData?g.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(s===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);const o=ps(e.decryptdata),h=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${h} (init data type: ${t} length: ${s.byteLength})`);const l=new er,d=e._onmessage=g=>{const p=e.mediaKeysSession;if(!p)return void l.emit("error",new Error("invalid state"));const{messageType:v,message:y}=g;this.log(`"${v}" message event for session "${p.sessionId}" message size: ${y.byteLength}`),v==="license-request"||v==="license-renewal"?this.renewLicense(e,y).catch(E=>{l.eventNames().length?l.emit("error",E):this.handleError(E)}):v==="license-release"?e.keySystem===fe.FAIRPLAY&&this.updateKeySession(e,Ri("acknowledged")).then(()=>this.removeSession(e)).catch(E=>this.handleError(E)):this.warn(`unhandled media key message type "${v}"`)},u=(g,p)=>{let v;p.keyStatus=g,g.startsWith("usable")?l.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?v=kn(g,p.decryptdata):g==="expired"?v=new Error(`key expired (keyId: ${o})`):g==="released"?v=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),v&&(l.eventNames().length?l.emit("error",v):this.handleError(v))},c=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession)return void l.emit("error",new Error("invalid state"));const p=this.getKeyStatuses(e);if(!Object.keys(p).some(E=>p[E]!=="status-pending"))return;if(p[o]==="expired")return this.log(`Expired key ${oe(p)} in key-session "${e.mediaKeysSession.sessionId}"`),void this.renewKeySession(e);let v=p[o];if(v)u(v,e);else{var y;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(y=e.keyStatusTimeouts)[o]||(y[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const T=this.getKeyStatus(e.decryptdata);if(T&&T!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${T} from other session.`),u(T,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),v="internal-error",u(v,e)},1e3)),this.log(`No status for keyId ${o} (${oe(p)}).`)}};Ie(e.mediaKeysSession,"message",d),Ie(e.mediaKeysSession,"keystatuseschange",c);const f=new Promise((g,p)=>{l.on("error",p),l.on("resolved",g)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${h}`)}).catch(g=>{throw new Pe({type:H.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw g}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,r)=>{if(typeof r=="string"&&typeof s=="object"){const o=r;r=s,s=o}const n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===fe.PLAYREADY&&n.length===16){const o=Le(n);t[o]=s,fa(n)}const a=Le(n);s==="internal-error"&&(this.bannedKeyIds[a]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=s}),t}fetchServerCertificate(e){const t=this.config,s=new t.loader(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,a)=>{const o={responseType:"arraybuffer",url:r},h=t.certLoadPolicy.default,l={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,c,f,g)=>{n(u.data)},onError:(u,c,f,g)=>{a(new Pe({type:H.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:re({url:o.url,data:void 0},u)},`"${e}" certificate request failed (${r}). Status: ${u.code} (${u.text})`))},onTimeout:(u,c,f)=>{a(new Pe({type:H.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:o.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(u,c,f)=>{a(new Error("aborted"))}};s.load(o,l,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((r,n)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),r(e)}).catch(a=>{n(new Pe({type:H.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(r=>{throw new Pe({type:H.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const r=new DOMParser().parseFromString(s,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let d;for(let u=0,c=n.length;u<c;u++){var a,o;d=n[u];const f=(a=d.querySelector("name"))==null?void 0:a.textContent,g=(o=d.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const h=r.querySelector("Challenge"),l=h?.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Ri(atob(l))}setupLicenseXHR(e,t,s,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return n.call(this.hls,e,t,s,r)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),n.call(this.hls,e,t,s,r)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{const a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let h=o.response;this.log(`License received ${h instanceof ArrayBuffer?h.byteLength:h}`);const l=this.config.licenseResponseCallback;if(l)try{h=l.call(this.hls,o,a,e)}catch(d){this.error(d)}r(h)}else{const h=s.errorRetry,l=h?h.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)n(new Pe({type:H.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const d=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t).then(r,n)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:h,licenseChallenge:l})=>{e.keySystem==fe.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(h,l)),h.send(l)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,Ie(s,"encrypted",this.onMediaEncrypted),Ie(s,"waitingforkey",this.onWaitingForKey);const r=this.mediaResolved;r?r():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(De(e,"encrypted",this.onMediaEncrypted),De(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,dt.clearKeyUriToKeyIdMap();const n=r.length;Ft.CDMCleanupPromise=Promise.all(r.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){const s=t.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Le(r?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);const{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(l=>self.clearTimeout(a[l]));const{drmSystemOptions:o}=this.config;return(function(l){var d;return!(!l||l.sessionType!=="persistent-license"&&((d=l.sessionTypes)==null||!d.some(u=>u==="persistent-license")))}(o)?new Promise((l,d)=>{self.setTimeout(()=>d(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(d)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}function ps(i){if(!i)throw new Error("Could not read keyId of undefined decryptdata");if(i.keyId===null)throw new Error("keyId is null");return Le(i.keyId)}function $l(i,e){return i.keyId&&e.mediaKeysSession.keyStatuses.has(i.keyId)?e.mediaKeysSession.keyStatuses.get(i.keyId):i.matches(e.decryptdata)?e.keyStatus:void 0}Ft.CDMCleanupPromise=void 0;class Pe extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function kn(i,e){const t=i==="output-restricted",s=t?I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:I.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Pe({type:H.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${i}"`)}function Ja(i,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=i,e.dispatchEvent(t)}function eo(i,e){const t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues&&!i.cues.getCueById(e.id))try{if(i.addCue(e),!i.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){ne.debug(`[texttrack-utils]: ${s}`);try{const r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,i.addCue(r)}catch(r){ne.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}t==="disabled"&&(i.mode=t)}function Pt(i,e){const t=i.mode;if(t==="disabled"&&(i.mode="hidden"),i.cues)for(let s=i.cues.length;s--;)e&&i.cues[s].removeEventListener("enter",e),i.removeCue(i.cues[s]);t==="disabled"&&(i.mode=t)}function Ui(i,e,t,s){const r=i.mode;if(r==="disabled"&&(i.mode="hidden"),i.cues&&i.cues.length>0){const n=function(a,o,h){const l=[],d=function(u,c){if(c<=u[0].startTime)return 0;const f=u.length-1;if(c>u[f].endTime)return-1;let g,p=0,v=f;for(;p<=v;)if(g=Math.floor((v+p)/2),c<u[g].startTime)v=g-1;else{if(!(c>u[g].startTime&&p<f))return g;p=g+1}return u[p].startTime-c<c-u[v].startTime?p:v}(a,o);if(d>-1)for(let u=d,c=a.length;u<c;u++){const f=a[u];if(f.startTime>=o&&f.endTime<=h)l.push(f);else if(f.startTime>h)return l}return l}(i.cues,e,t);for(let a=0;a<n.length;a++)s&&!s(n[a])||i.removeCue(n[a])}r==="disabled"&&(i.mode=r)}function vs(i){const e=[];for(let t=0;t<i.length;t++){const s=i[t];s.kind!=="subtitles"&&s.kind!=="captions"||!s.label||e.push(i[t])}return e}function es(i){let e=5381,t=i.length;for(;t;)e=33*e^i.charCodeAt(--t);return(e>>>0).toString()}const Nt=.025;let Hs=function(i){return i[i.Point=0]="Point",i[i.Range=1]="Range",i}({});function Bl(i,e,t){return`${i.identifier}-${t+1}-${es(e)}`}class Gl{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return ai(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-ai(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=U(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return ai(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Nt))}set appendInPlace(e){this.appendInPlaceStarted?this.resetOnResume=!e:this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return t=this._duration!==null?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Hs.Range:Hs.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`["${(e=this).identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`;var e}}function ai(i,e){return i-e.start<e.duration/2&&!(Math.abs(i-(e.start+e.duration))<Nt)?e.start:e.start+e.duration}function to(i,e,t){const s=new self.URL(i,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function oi(i,e){for(;(t=i.assetList[++e])!=null&&t.error;)var t;return e}function Ct(i){const e=i.timelineStart,t=i.duration||0;return`["${i.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class Kl{constructor(e,t,s,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(m.PLAYOUT_LIMIT_REACHED,{})};const n=this.hls=new e(t);this.interstitial=s,this.assetItem=r;const a=()=>{this.hasDetails=!0};n.once(m.LEVEL_LOADED,a),n.once(m.AUDIO_TRACK_LOADED,a),n.once(m.SUBTITLE_TRACK_LOADED,a),n.on(m.MEDIA_ATTACHING,(o,{media:h})=>{this.removeMediaListeners(),this.mediaAttached=h,this.interstitial.playoutLimit&&(h.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(m.BUFFER_APPENDED,()=>{const l=this.bufferedEnd;this.reachedPlayout(l)&&(this._bufferedEosTime=l,n.trigger(m.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=to(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,n=z.bufferInfo(e,r,0);return this.getAssetTime(n.end)>=s-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=z.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;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=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var e;this.mediaAttached&&(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,s){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,s){var r;(r=this.hls)==null||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Ct(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class Hl extends Fe{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const r=this.items;if(r)for(r[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(n=r[s])!=null&&n.event;){var n;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let r=0;r<s.length;r++){let n=s[r];if(t&&t!=="primary"&&(n=n[t]),e===n.start||e>n.start&&e<n.end)return r}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let r=e;r<=t&&s[r];r++){const n=s[r].event;if(n!=null&&n.restrictions.jump&&!n.appendInPlace)return r}return-1}findEventIndex(e){const t=this.items;if(t)for(let r=t.length;r--;){var s;if(((s=t[r].event)==null?void 0:s.identifier)===e)return r}return-1}findAssetIndex(e,t){const s=e.assetList,r=s.length;if(r>1)for(let n=0;n<r;n++){const a=s[n];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||n===r-1))return n}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,r=s[s.length-1];if(r)return r.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:r}=s,n=this.events,a=this.parseDateRanges(r,{url:s.url},t),o=Object.keys(r),h=n?n.filter(l=>!o.includes(l.identifier)):[];a.length&&a.sort((l,d)=>{const u=l.cue.pre,c=l.cue.post,f=d.cue.pre,g=d.cue.post;if(u&&!f)return-1;if(f&&!u||c&&!g)return 1;if(g&&!c)return-1;if(!(u||f||c||g)){const p=l.startTime,v=d.startTime;if(p!==v)return p-v}return l.dateRange.tagOrder-d.dateRange.tagOrder}),this.events=a,h.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,h)}updateSchedule(e,t=[],s=!1){const r=this.events||[];if(r.length||t.length||this.length<2){const n=this.items,a=this.parseSchedule(r,e);(s||t.length||n?.length!==a.length||a.some((o,h)=>Math.abs(o.playout.start-n[h].playout.start)>.005||Math.abs(o.playout.end-n[h].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,n))}}parseDateRanges(e,t,s){const r=[],n=Object.keys(e);for(let a=0;a<n.length;a++){const o=n[a],h=e[o];if(h.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(h):(l=new Gl(h,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),r.push(l)}}return r}parseSchedule(e,t){const s=[],r=t.main.details,n=r.live?1/0:r.edge;let a=0;if((e=e.filter(h=>!(h.error||h.cue.once&&h.hasPlayed))).length){this.resolveOffsets(e,t);let h=0,l=0;if(e.forEach((d,u)=>{const c=d.cue.pre,f=d.cue.post,g=e[u-1]||null,p=d.appendInPlace,v=f?n:d.startOffset,y=d.duration,E=d.timelineOccupancy===Hs.Range?y:0,T=d.resumptionOffset,A=g?.startTime===v,L=v+d.cumulativeDuration;let b=p?L+y:v+T;if(c||!f&&v<=0){const k=l;l+=E,d.timelineStart=L;const D=a;a+=y,s.push({event:d,start:L,end:b,playout:{start:D,end:a},integrated:{start:k,end:l}})}else{if(!(v<=n))return;{if(!A){const P=v-h;if(P>.033){const O=h,N=l;l+=P;const B=a;a+=P;const F={previousEvent:e[u-1]||null,nextEvent:d,start:O,end:O+P,playout:{start:B,end:a},integrated:{start:N,end:l}};s.push(F)}else P>0&&g&&(g.cumulativeDuration+=P,s[s.length-1].end=v)}f&&(b=L),d.timelineStart=L;const k=l;l+=E;const D=a;a+=y,s.push({event:d,start:L,end:b,playout:{start:D,end:a},integrated:{start:k,end:l}})}}const S=d.resumeTime;h=f||S>n?n:S}),h<n){var o;const d=h,u=l,c=n-h;l+=c;const f=a;a+=c,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:h,end:d+c,playout:{start:f,end:a},integrated:{start:u,end:l}})}this.setDurations(n,a,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:n,playout:{start:0,end:n},integrated:{start:0,end:n}}),this.setDurations(n,n,n);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,r=s.live?1/0:s.edge;let n=0,a=-1;e.forEach((o,h)=>{const l=o.cue.pre,d=o.cue.post,u=l?0:d?r:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=n:(n=0,a=u),!d&&o.snapOptions.in&&(o.resumeAnchor=Et(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&h+1<e.length&&e[h+1].startTime-e[h].resumeTime<.033&&(e[h+1].appendInPlace=!1,e[h+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const c=U(o.resumeOffset)?o.resumeOffset:o.duration;n+=c})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(s-r)>Nt?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(n=>{const a=t[n].details,o=a.edge;if(s>=o)return this.log(`"${e.identifier}" resumption ${s} past ${n} playlist end ${o}`),!1;const h=Et(null,a.fragments,s);if(!h)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${n} playlist (${a.fragStart}-${a.fragmentEnd})`),!0;const l=n==="audio"?.175:0;return!(Math.abs(h.start-s)<Nt+l||Math.abs(h.end-s)<Nt+l)&&(this.log(`"${e.identifier}" resumption ${s} not aligned with ${n} fragment bounds (${h.start}-${h.end} sn: ${h.sn} cc: ${h.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,r=!1,n=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],h=t+s;o.startOffset=s,o.timelineStart=h,r||(r=o.duration===null),n||(n=!!o.error),s+=o.error?0:o.duration||0}e.duration=r&&!n?Math.max(s,e.duration):s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function $e(i){return`[${i.event?'"'+i.event.identifier+'"':"primary"}: ${i.start.toFixed(2)}-${i.end.toFixed(2)}]`}class Vl{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let r;try{r=to(s,this.hls.sessionId,e.baseUrl)}catch(u){const c=this.assignAssetListError(e,I.ASSET_LIST_LOAD_ERROR,u,s);return void this.hls.trigger(m.ERROR,c)}t&&r.protocol!=="data:"&&r.searchParams.set("_HLS_start_offset",""+t);const n=this.hls.config,a=new n.loader(n),o={responseType:"json",url:r.href},h=n.interstitialAssetListLoadPolicy.default,l={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,c,f,g)=>{const p=u.data,v=p?.ASSETS;if(!Array.isArray(v)){const y=this.assignAssetListError(e,I.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),f.url,c,g);return void this.hls.trigger(m.ERROR,y)}e.assetListResponse=p,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:p,networkDetails:g})},onError:(u,c,f,g)=>{const p=this.assignAssetListError(e,I.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${u.code} ${u.text} (${c.url})`),c.url,g,f);this.hls.trigger(m.ERROR,p)},onTimeout:(u,c,f)=>{const g=this.assignAssetListError(e,I.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${c.url})`),c.url,u,f);this.hls.trigger(m.ERROR,g)}};return a.load(o,l,d),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,s,r,n,a){return e.error=s,{type:H.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:s,networkDetails:a,stats:n}}}function Dn(i){var e;i==null||(e=i.play())==null||e.catch(()=>{})}function ys(i,e){return`[${i}] Advancing timeline position to ${e}`}class Yl{constructor(e){this.buffered=void 0;const t=(s,r,n)=>{if((r>>>=0)>n-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${r}) is greater than the maximum bound (${n})`);return e[r][s]};this.buffered={get length(){return e.length},end:s=>t("end",s,e.length),start:s=>t("start",s,e.length)}}}const Wl={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},so=i=>String.fromCharCode(Wl[i]||i),gt=15,Je=100,jl={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},ql={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Xl={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},zl={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Ql=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Zl{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;ne.log(`${this.time} [${e}] ${s}`)}}}const mt=function(i){const e=[];for(let t=0;t<i.length;t++)e.push(i[t].toString(16));return e};class io{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const r=t[s];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Jl{constructor(){this.uchar=" ",this.penState=new io}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class eh{constructor(e){this.chars=[],this.pos=0,this.currPenState=new io,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Je;t++)this.chars.push(new Jl);this.logger=e}equals(e){for(let t=0;t<Je;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Je;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Je;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Je&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Je)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=so(e);this.pos>=Je?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<Je;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<Je;s++){const r=this.chars[s].uchar;r!==" "&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class li{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<gt;t++)this.rows.push(new eh(e));this.logger=e}reset(){for(let e=0;e<gt;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let s=0;s<gt;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<gt;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<gt;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+oe(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<gt;o++)this.rows[o].clear();const n=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[n].cueStartTime,h=this.logger.time;if(o!==null&&h!==null&&o<h)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(a.rows[n+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const n=e.indent,a=Math.max(n-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}const r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+oe(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",r=-1;for(let n=0;n<gt;n++){const a=this.rows[n].getTextString();a&&(r=n+1,e?t.push("Row "+r+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(s=e?"["+t.join(" | ")+"]":t.join(`
17
+ `)),s}getTextAndFormat(){return this.rows}}class Pn{constructor(e,t,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=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new li(s),this.nonDisplayedMemory=new li(s),this.lastOutputScreen=new li(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),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=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+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(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=r[s]}this.logger.log(2,"MIDROW: "+oe(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime!==null||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Cn{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const r=this.logger=new Zl;this.channels=[null,new Pn(e,t,r),new Pn(e+1,s,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const r=127&t[s],n=127&t[s+1];let a=!1,o=null;if(r===0&&n===0)continue;this.logger.log(3,()=>"["+mt([t[s],t[s+1]])+"] -> ("+mt([r,n])+")");const h=this.cmdHistory;if(r>=16&&r<=31){if(th(r,n,h)){Es(null,null,h),this.logger.log(3,()=>"Repeated command ("+mt([r,n])+") is dropped");continue}Es(r,n,this.cmdHistory),a=this.parseCmd(r,n),a||(a=this.parseMidrow(r,n)),a||(a=this.parsePAC(r,n)),a||(a=this.parseBackgroundAttributes(r,n))}else Es(null,null,h);if(!a&&(o=this.parseChars(r,n),o)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}a||o||this.logger.log(2,()=>"Couldn't parse cleaned data "+mt([r,n])+" orig: "+mt([t[s],t[s+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47)&&!((e===23||e===31)&&t>=33&&t<=35))return!1;const s=e===20||e===21||e===23?1:2,r=this.channels[s];return e===20||e===21||e===28||e===29?t===32?r.ccRCL():t===33?r.ccBS():t===34?r.ccAOF():t===35?r.ccAON():t===36?r.ccDER():t===37?r.ccRU(2):t===38?r.ccRU(3):t===39?r.ccRU(4):t===40?r.ccFON():t===41?r.ccRDC():t===42?r.ccTR():t===43?r.ccRTD():t===44?r.ccEDM():t===45?r.ccCR():t===46?r.ccENM():t===47&&r.ccEOC():r.ccTO(t-32),this.currentChannel=s,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(s=e===17?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[s];return!!r&&(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+mt([e,t])+")"),!0)}return!1}parsePAC(e,t){let s;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((e===16||e===24)&&t>=64&&t<=95))return!1;const r=e<=23?1:2;s=t>=64&&t<=95?r===1?jl[e]:Xl[e]:r===1?ql[e]:zl[e];const n=this.channels[r];return!!n&&(n.setPAC(this.interpretPAC(s,t)),this.currentChannel=r,!0)}interpretPAC(e,t){let s;const r={color:null,italics:!1,indent:null,underline:!1,row:e};return s=t>95?t-96:t-64,r.underline=!(1&~s),s<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((s-16)/2),r}parseChars(e,t){let s,r=null,n=null;if(e>=25?(s=2,n=e-8):(s=1,n=e),n>=17&&n<=19){let a;a=n===17?t+80:n===18?t+112:t+144,this.logger.log(2,()=>"Special char '"+so(a)+"' in channel "+s),r=[a]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+mt(r).join(",")),r}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47)&&!((e===23||e===31)&&t>=45&&t<=47))return!1;let s;const r={};e===16||e===24?(s=Math.floor((t-32)/2),r.background=Ql[s],t%2==1&&(r.background=r.background+"_semi")):t===45?r.background="transparent":(r.foreground="black",t===47&&(r.underline=!0));const n=e<=23?1:2;return this.channels[n].setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Es(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function Es(i,e,t){t.a=i,t.b=e}function th(i,e,t){return t.a===i&&t.b===e}var or=function(){if(Bs!=null&&Bs.VTTCue)return self.VTTCue;const i=["","lr","rl"],e=["start","middle","end","left","right"];function t(a,o){if(typeof o!="string"||!Array.isArray(a))return!1;const h=o.toLowerCase();return!!~a.indexOf(h)&&h}function s(a){return t(e,a)}function r(a,...o){let h=1;for(;h<arguments.length;h++){const l=arguments[h];for(const d in l)a[d]=l[d]}return a}function n(a,o,h){const l=this,d={enumerable:!0};l.hasBeenReset=!1;let u="",c=!1,f=a,g=o,p=h,v=null,y="",E=!0,T="auto",A="start",L=50,b="middle",S=50,k="middle";Object.defineProperty(l,"id",r({},d,{get:function(){return u},set:function(D){u=""+D}})),Object.defineProperty(l,"pauseOnExit",r({},d,{get:function(){return c},set:function(D){c=!!D}})),Object.defineProperty(l,"startTime",r({},d,{get:function(){return f},set:function(D){if(typeof D!="number")throw new TypeError("Start time must be set to a number.");f=D,this.hasBeenReset=!0}})),Object.defineProperty(l,"endTime",r({},d,{get:function(){return g},set:function(D){if(typeof D!="number")throw new TypeError("End time must be set to a number.");g=D,this.hasBeenReset=!0}})),Object.defineProperty(l,"text",r({},d,{get:function(){return p},set:function(D){p=""+D,this.hasBeenReset=!0}})),Object.defineProperty(l,"region",r({},d,{get:function(){return v},set:function(D){v=D,this.hasBeenReset=!0}})),Object.defineProperty(l,"vertical",r({},d,{get:function(){return y},set:function(D){const P=function(O){return t(i,O)}(D);if(P===!1)throw new SyntaxError("An invalid or illegal string was specified.");y=P,this.hasBeenReset=!0}})),Object.defineProperty(l,"snapToLines",r({},d,{get:function(){return E},set:function(D){E=!!D,this.hasBeenReset=!0}})),Object.defineProperty(l,"line",r({},d,{get:function(){return T},set:function(D){if(typeof D!="number"&&D!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");T=D,this.hasBeenReset=!0}})),Object.defineProperty(l,"lineAlign",r({},d,{get:function(){return A},set:function(D){const P=s(D);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");A=P,this.hasBeenReset=!0}})),Object.defineProperty(l,"position",r({},d,{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(l,"positionAlign",r({},d,{get:function(){return b},set:function(D){const P=s(D);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");b=P,this.hasBeenReset=!0}})),Object.defineProperty(l,"size",r({},d,{get:function(){return S},set:function(D){if(D<0||D>100)throw new Error("Size must be between 0 and 100.");S=D,this.hasBeenReset=!0}})),Object.defineProperty(l,"align",r({},d,{get:function(){return k},set:function(D){const P=s(D);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");k=P,this.hasBeenReset=!0}})),l.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class sh{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function ro(i){function e(s,r,n,a){return 3600*(0|s)+60*(0|r)+(0|n)+parseFloat(a||0)}const t=i.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class ih{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||t===""||(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let r=0;r<s.length;++r)if(t===s[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function no(i,e,t,s){const r=s?i.split(s):[i];for(const n in r){if(typeof r[n]!="string")continue;const a=r[n].split(t);a.length===2&&e(a[0],a[1])}}const $i=new or(0,0,""),Ts=$i.align==="middle"?"middle":"center";function rh(i,e,t){const s=i;function r(){const a=ro(i);if(a===null)throw new Error("Malformed timestamp: "+s);return i=i.replace(/^[^\sa-zA-Z-]+/,""),a}function n(){i=i.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),i.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);i=i.slice(3),n(),e.endTime=r(),n(),function(a,o){const h=new ih;no(a,function(u,c){let f;switch(u){case"region":for(let g=t.length-1;g>=0;g--)if(t[g].id===c){h.set(u,t[g].region);break}break;case"vertical":h.alt(u,c,["rl","lr"]);break;case"line":f=c.split(","),h.integer(u,f[0]),h.percent(u,f[0])&&h.set("snapToLines",!1),h.alt(u,f[0],["auto"]),f.length===2&&h.alt("lineAlign",f[1],["start",Ts,"end"]);break;case"position":f=c.split(","),h.percent(u,f[0]),f.length===2&&h.alt("positionAlign",f[1],["start",Ts,"end","line-left","line-right","auto"]);break;case"size":h.percent(u,c);break;case"align":h.alt(u,c,["start",Ts,"end","left","right"])}},/:/,/\s/),o.region=h.get("region",null),o.vertical=h.get("vertical","");let l=h.get("line","auto");l==="auto"&&$i.line===-1&&(l=-1),o.line=l,o.lineAlign=h.get("lineAlign","start"),o.snapToLines=h.get("snapToLines",!0),o.size=h.get("size",100),o.align=h.get("align",Ts);let d=h.get("position","auto");d==="auto"&&$i.position===50&&(d=o.align==="start"||o.align==="left"?0:o.align==="end"||o.align==="right"?100:50),o.position=d}(i,e)}function ao(i){return i.replace(/<br(?: \/)?>/gi,`
18
+ `)}class nh{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new sh,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function s(){let n=t.buffer,a=0;for(n=ao(n);a<n.length&&n[a]!=="\r"&&n[a]!==`
19
+ `;)++a;const o=n.slice(0,a);return n[a]==="\r"&&++a,n[a]===`
20
+ `&&++a,t.buffer=n.slice(a),o}function r(n){no(n,function(a,o){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let n="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;n=s();const o=n.match(/^()?WEBVTT([ \t].*)?$/);if(o==null||!o[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:n=s(),t.state){case"HEADER":/:/.test(n)?r(n):n||(t.state="ID");continue;case"NOTE":n||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(n)){t.state="NOTE";break}if(!n)continue;if(t.cue=new or(0,0,""),t.state="CUE",n.indexOf("-->")===-1){t.cue.id=n;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{rh(n,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=n.indexOf("-->")!==-1;if(!n||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
21
+ `),t.cue.text+=n}continue;case"BADCUE":n||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
22
+
23
+ `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const ah=/\r\n|\n\r|\n|\r/g,hi=function(i,e,t=0){return i.slice(t,t+e.length)===e};function lr(i,e,t){return es(i.toString())+es(e.toString())+es(t)}function oh(i,e,t,s,r,n,a){const o=new nh,h=we(new Uint8Array(i)).trim().replace(ah,`
24
+ `).split(`
25
+ `),l=[],d=e?function(v,y=1){return nr(v,9e4,1/y)}(e.baseTime,e.timescale):0;let u,c="00:00.000",f=0,g=0,p=!0;o.oncue=function(v){const y=t[s];let E=t.ccOffset;const T=(f-d)/9e4;if(y!=null&&y.new&&(g!==void 0?E=t.ccOffset=y.start:function(S,k,D){let P=S[k],O=S[P.prevCC];if(!O||!O.new&&P.new)return S.ccOffset=S.presentationOffset=P.start,void(P.new=!1);for(;(N=O)!=null&&N.new;){var N;S.ccOffset+=P.start-O.start,P.new=!1,P=O,O=S[P.prevCC]}S.presentationOffset=D}(t,s,T)),T){if(!e)return void(u=new Error("Missing initPTS for VTT MPEGTS"));E=T-t.presentationOffset}const A=v.endTime-v.startTime,L=Ce(9e4*(v.startTime+E-g),9e4*r)/9e4;v.startTime=Math.max(L,0),v.endTime=Math.max(L+A,0);const b=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(b)),v.id||(v.id=lr(v.startTime,v.endTime,b)),v.endTime>0&&l.push(v)},o.onparsingerror=function(v){u=v},o.onflush=function(){u?a(u):n(l)},h.forEach(v=>{if(p){if(hi(v,"X-TIMESTAMP-MAP=")){p=!1,v.slice(16).split(",").forEach(y=>{hi(y,"LOCAL:")?c=y.slice(6):hi(y,"MPEGTS:")&&(f=parseInt(y.slice(7)))});try{g=function(y){let E=parseInt(y.slice(-3));const T=parseInt(y.slice(-6,-4)),A=parseInt(y.slice(-9,-7)),L=y.length>9?parseInt(y.substring(0,y.indexOf(":"))):0;if(!(U(E)&&U(T)&&U(A)&&U(L)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${y}`);return E+=1e3*T,E+=6e4*A,E+=36e5*L,E}(c)/1e3}catch(y){u=y}return}v===""&&(p=!1)}o.parse(v+`
26
+ `)}),o.flush()}const di="stpp.ttml.im1t",_n=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,wn=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,lh={left:"start",center:"center",right:"end",start:"start",end:"end"};function xn(i,e,t,s){const r=ee(new Uint8Array(i),["mdat"]);if(r.length===0)return void s(new Error("Could not parse IMSC1 mdat"));const n=r.map(o=>we(o)),a=function(o,h,l=1,d=!1){return nr(o,h,1/l,d)}(e.baseTime,1,e.timescale);try{n.forEach(o=>t(function(h,l){const d=new DOMParser().parseFromString(h,"text/xml"),u=d.getElementsByTagName("tt")[0];if(!u)throw new Error("Invalid ttml");const c={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},f=Object.keys(c).reduce((E,T)=>(E[T]=u.getAttribute(`ttp:${T}`)||c[T],E),{}),g=u.getAttribute("xml:space")!=="preserve",p=On(ui(u,"styling","style")),v=On(ui(u,"layout","region")),y=ui(u,"body","[begin]");return[].map.call(y,E=>{const T=oo(E,g);if(!T||!E.hasAttribute("begin"))return null;const A=fi(E.getAttribute("begin"),f),L=fi(E.getAttribute("dur"),f);let b=fi(E.getAttribute("end"),f);if(A===null)throw Mn(E);if(b===null){if(L===null)throw Mn(E);b=A+L}const S=new or(A-l,b-l,T);S.id=lr(S.startTime,S.endTime,S.text);const k=function(P,O,N){const B="http://www.w3.org/ns/ttml#styling";let F=null;const w=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],_=P!=null&&P.hasAttribute("style")?P.getAttribute("style"):null;return _&&N.hasOwnProperty(_)&&(F=N[_]),w.reduce(($,x)=>{const C=ci(O,B,x)||ci(P,B,x)||ci(F,B,x);return C&&($[x]=C),$},{})}(v[E.getAttribute("region")],p[E.getAttribute("style")],p),{textAlign:D}=k;if(D){const P=lh[D];P&&(S.lineAlign=P),S.align=D}return ae(S,k),S}).filter(E=>E!==null)}(o,a)))}catch(o){s(o)}}function ui(i,e,t){const s=i.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function On(i){return i.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function oo(i,e){return[].slice.call(i.childNodes).reduce((t,s,r)=>{var n;return s.nodeName==="br"&&r?t+`
27
+ `:(n=s.childNodes)!=null&&n.length?oo(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function ci(i,e,t){return i&&i.hasAttributeNS(e,t)?i.getAttributeNS(e,t):null}function Mn(i){return new Error(`Could not parse ttml timestamp ${i}`)}function fi(i,e){if(!i)return null;let t=ro(i);return t===null&&(_n.test(i)?t=function(s,r){const n=_n.exec(s),a=(0|n[4])+(0|n[5])/r.subFrameRate;return 3600*(0|n[1])+60*(0|n[2])+(0|n[3])+a/r.frameRate}(i,e):wn.test(i)&&(t=function(s,r){const n=wn.exec(s),a=Number(n[1]);switch(n[2]){case"h":return 3600*a;case"m":return 60*a;case"ms":return 1e3*a;case"f":return a/r.frameRate;case"t":return a/r.tickRate}return a}(i,e))),t}class Ss{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function lo(i){return i.characteristics&&/transcribes-spoken-dialog/gi.test(i.characteristics)&&/describes-music-and-sound/gi.test(i.characteristics)?"captions":"subtitles"}function Fn(i,e){return!!i&&i.kind===lo(e)&&xi(e,i)}function hh(i,e,t,s){return Math.min(e,s)-Math.max(i,t)}const dh=/\s/,uh={newCue(i,e,t,s){const r=[];let n,a,o,h,l;const d=self.VTTCue||self.TextTrackCue;for(let c=0;c<s.rows.length;c++)if(n=s.rows[c],o=!0,h=0,l="",!n.isEmpty()){var u;for(let p=0;p<n.chars.length;p++)dh.test(n.chars[p].uchar)&&o?h++:(l+=n.chars[p].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),h>=16?h--:h++;const f=ao(l.trim()),g=lr(e,t,f);i!=null&&(u=i.cues)!=null&&u.getCueById(g)||(a=new d(e,t,f),a.id=g,a.line=c+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*h/32)),r.push(a))}return i&&r.length&&(r.sort((c,f)=>c.line==="auto"||f.line==="auto"?0:c.line>8&&f.line>8?f.line-c.line:c.line-f.line),r.forEach(c=>eo(i,c))),r}},ch=/(\d+)-(\d+)\/(\d+)/;class Nn{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||fh,this.controller=new self.AbortController,this.stats=new Hi}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const n=function(d,u){const c={method:"GET",mode:"cors",credentials:"same-origin",signal:u,headers:new self.Headers(ae({},d.headers))};return d.rangeEnd&&c.headers.set("Range","bytes="+d.rangeStart+"-"+String(d.rangeEnd-1)),c}(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:h,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=h&&U(h)?h:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},t.timeout),(ns(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var u;this.response=this.loader=d;const c=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},l-(c-r.loading.start)),!d.ok){const{status:g,statusText:p}=d;throw new gh(p||"fetch, bad network response",g,d)}r.loading.first=c,r.total=function(g){const p=g.get("Content-Range");if(p){const y=function(E){const T=ch.exec(E);if(T)return parseInt(T[2])-parseInt(T[1])+1}(p);if(U(y))return y}const v=g.get("Content-Length");if(v)return parseInt(v)}(d.headers)||r.total;const f=(u=this.callbacks)==null?void 0:u.onProgress;return f&&U(t.highWaterMark)?this.loadProgressively(d,r,e,t.highWaterMark,f):a?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var u,c;const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const g=d[o];g&&(r.loaded=r.total=g);const p={url:f.url,data:d,code:f.status},v=(u=this.callbacks)==null?void 0:u.onProgress;v&&!U(t.highWaterMark)&&v(r,e,d,f),(c=this.callbacks)==null||c.onSuccess(p,r,e,f)}).catch(d=>{var u;if(self.clearTimeout(this.requestTimeout),r.aborted)return;const c=d&&d.code||0,f=d?d.message:null;(u=this.callbacks)==null||u.onError({code:c,text:f},e,d?d.details:null,r)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,r=0,n){const a=new ba,o=e.body.getReader(),h=()=>o.read().then(l=>{if(l.done)return a.dataLength&&n(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const d=l.value,u=d.length;return t.loaded+=u,u<r||a.dataLength?(a.push(d),a.dataLength>=r&&n(t,s,a.flush().buffer,e)):n(t,s,d.buffer,e),h()}).catch(()=>Promise.reject());return h()}}function fh(i,e){return new self.Request(i.url,e)}class gh extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const mh=/^age:\s*[\d.]+\s*$/im;class ho{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Hi,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const n=this.xhrSetup;n?Promise.resolve().then(()=>{if(this.loader===s&&!this.stats.aborted)return n(s,t.url)}).catch(a=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",t.url,!0),n(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,r)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const r=t.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(r)for(const o in r)e.setRequestHeader(o,r[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&U(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const r=t.readyState,n=this.config;if(!s.aborted&&r>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,d=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const c=d??t.response;if(c!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const f=t.responseType==="arraybuffer"?c.byteLength:c.length;s.loaded=s.total=f,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first);const g=(a=this.callbacks)==null?void 0:a.onProgress;g&&g(s,e,c,t);const p={url:t.responseURL,data:c,code:l};return void((o=this.callbacks)==null||o.onSuccess(p,s,e,t))}}const u=n.loadPolicy.errorRetry;var h;Ns(u,s.retry,!1,{url:e.url,data:void 0,code:l})?this.retry(u):(ne.error(`${l} while loading ${e.url}`),(h=this.callbacks)==null||h.onError({code:l,text:t.statusText},e,t,s))}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Ns(e,this.stats.retry,!0))this.retry(e);else{var t;ne.warn(`timeout while loading ${(t=this.context)==null?void 0:t.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=ji(e,s.retry),s.retry++,ne.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&mh.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const ph=re(re({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:ho,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends Fe{constructor(i){super("abr",i.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;const{fragCurrent:s,partCurrent:r,hls:n}=this,{autoLevelEnabled:a,media:o}=n;if(!s||!o)return;const h=performance.now(),l=r?r.stats:s.stats,d=r?r.duration:s.duration,u=h-l.loading.start,c=n.minAutoLevel,f=s.level,g=this._nextAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||f<=c)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!a)return;const p=g>-1&&g!==f,v=!!e||p;if(!v&&(o.paused||!o.playbackRate||!o.readyState))return;const y=n.mainForwardBufferInfo;if(!v&&y===null)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(o.playbackRate);if(u<=Math.max(E,d/(2*T)*1e3))return;const A=y?y.len/T:0,L=l.loading.first?l.loading.first-l.loading.start:-1,b=l.loaded&&L>-1,S=this.getBwEstimate(),k=n.levels,D=k[f],P=Math.max(l.loaded,Math.round(d*(s.bitrate||D.averageBitrate)/8));let O=b?u-L:u;O<1&&b&&(O=Math.min(u,8*l.loaded/S));const N=b?1e3*l.loaded/O:0,B=E/1e3,F=N?(P-l.loaded)/N:8*P/S+B;if(F<=A)return;const w=N?8*N:S,_=((t=e?.details||this.hls.latestLevelDetails)==null?void 0:t.live)===!0,$=this.hls.config.abrBandWidthUpFactor;let x,C=Number.POSITIVE_INFINITY;for(x=f-1;x>c;x--){const W=k[x].maxBitrate,G=!k[x].details||_;if(C=this.getTimeToLoadFrag(B,w,d*W,G),C<Math.min(A,d+B))break}if(C>=F||C>10*d)return;b?this.bwEstimator.sample(u-Math.min(E,L),l.loaded):this.bwEstimator.sampleTTFB(u);const M=k[x].maxBitrate;this.getBwEstimate()*$>M&&this.resetEstimator(M);const V=this.findBestLevel(M,c,x,0,A,1,1);V>-1&&(x=V),this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${f} is loading too slowly;
28
+ Fragment duration: ${s.duration.toFixed(3)}
29
+ Time to underbuffer: ${A.toFixed(3)} s
30
+ Estimated load time for current fragment: ${F.toFixed(3)} s
31
+ Estimated load time for down switch fragment: ${C.toFixed(3)} s
32
+ TTFB estimate: ${0|L} ms
33
+ Current BW estimate: ${U(S)?0|S:"Unknown"} bps
34
+ New BW estimate: ${0|this.getBwEstimate()} bps
35
+ Switching to level ${x} @ ${0|M} bps`),n.nextLoadLevel=n.nextAutoLevel=x,this.clearTimer();const Y=()=>{if(this.clearTimer(),this.fragCurrent===s&&this.hls.loadLevel===x&&x>0){const W=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${x>0?"and switching down":""}
36
+ Fragment duration: ${s.duration.toFixed(3)} s
37
+ Time to underbuffer: ${W.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,x>c){let G=this.findBestLevel(this.hls.levels[c].bitrate,c,x,0,W,1,1);G===-1&&(G=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=G,this.resetEstimator(this.hls.levels[G].bitrate)}}};p||F>2*C?Y():this.timer=self.setInterval(Y,1e3*C),n.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:l})},this.hls=i,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(i){i&&(this.log(`setting initial bwe to ${i}`),this.hls.config.abrEwmaDefaultEstimate=i),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const i=this.hls.config;return new go(i.abrEwmaSlowVoD,i.abrEwmaFastVoD,i.abrEwmaDefaultEstimate)}registerListeners(){const{hls:i}=this;i.on(m.MANIFEST_LOADING,this.onManifestLoading,this),i.on(m.FRAG_LOADING,this.onFragLoading,this),i.on(m.FRAG_LOADED,this.onFragLoaded,this),i.on(m.FRAG_BUFFERED,this.onFragBuffered,this),i.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),i.on(m.LEVEL_LOADED,this.onLevelLoaded,this),i.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),i.on(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),i.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:i}=this;i&&(i.off(m.MANIFEST_LOADING,this.onManifestLoading,this),i.off(m.FRAG_LOADING,this.onFragLoading,this),i.off(m.FRAG_LOADED,this.onFragLoaded,this),i.off(m.FRAG_BUFFERED,this.onFragBuffered,this),i.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),i.off(m.LEVEL_LOADED,this.onLevelLoaded,this),i.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),i.off(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),i.off(m.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(i,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(i,e){const t=e.frag;if(!this.ignoreFragment(t)){var s;t.bitrateTest||(this.fragCurrent=t,this.partCurrent=(s=e.part)!=null?s:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(i,e){this.clearTimer()}onError(i,e){if(!e.fatal)switch(e.details){case I.BUFFER_ADD_CODEC_ERROR:case I.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case I.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:s,partCurrent:r}=this;if(t&&s&&t.sn===s.sn&&t.level===s.level){const n=performance.now(),a=r?r.stats:t.stats,o=n-a.loading.start,h=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&h>-1){const l=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(l,h),a.loaded)}else this.bwEstimator.sampleTTFB(o)}break}}}getTimeToLoadFrag(i,e,t,s){return i+t/e+(s?i+this.lastLevelLoadSec:0)}onLevelLoaded(i,e){const t=this.hls.config,{loading:s}=e.stats,r=s.end-s.first;U(r)&&(this.lastLevelLoadSec=r/1e3),e.details.live?this.bwEstimator.update(t.abrEwmaSlowLive,t.abrEwmaFastLive):this.bwEstimator.update(t.abrEwmaSlowVoD,t.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(i,{frag:e,part:t}){const s=t?t.stats:e.stats;if(e.type===Z&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=t?t.duration:e.duration,n=this.hls.levels[e.level],a=(n.loaded?n.loaded.bytes:0)+s.loaded,o=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:a,duration:o},n.realBitrate=Math.round(8*a/o)}if(e.bitrateTest){const r={stats:s,frag:e,part:t,id:e.type};this.onFragBuffered(m.FRAG_BUFFERED,r),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(i,e){const{frag:t,part:s}=e,r=s!=null&&s.stats.loaded?s.stats:t.stats;if(r.aborted||this.ignoreFragment(t))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),t.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(i){return i.type!==Z||i.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:i,minAutoLevel:e}=this.hls,t=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(t,e,i,0,s,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),i);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const i=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),t=this.lastLoadedFragLevel>-1;if(!(i===-1||e&&t&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return i;const s=e&&t?this.getNextABRAutoLevel():this.firstAutoLevel;if(i!==-1){const r=this.hls.levels;if(r.length>Math.max(i,s)&&r[i].loadError<=r[s].loadError)return i}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:i,partCurrent:e,hls:t}=this;if(t.levels.length<=1)return t.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:n}=t,a=e?e.duration:i?i.duration:0,o=this.getBwEstimate(),h=this.getStarvationDelay();let l=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(h){const p=this.findBestLevel(o,n,s,h,0,l,d);if(p>=0)return this.rebufferNotice=-1,p}let u=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!h){const p=this.bitrateTestDelay;p&&(u=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-p,this.info(`bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),l=d=1)}const c=this.findBestLevel(o,n,s,h,u,l,d);if(this.rebufferNotice!==c&&(this.rebufferNotice=c,this.info(`${h?"rebuffering expected":"buffer is empty"}, optimal quality level ${c}`)),c>-1)return c;const f=t.levels[n],g=t.loadLevelObj;return g&&f?.bitrate<g.bitrate?n:t.loadLevel}getStarvationDelay(){const i=this.hls,e=i.media;if(!e)return 1/0;const t=e&&e.playbackRate!==0?Math.abs(e.playbackRate):1,s=i.mainForwardBufferInfo;return(s?s.len:0)/t}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(i,e,t,s,r,n,a){var o;const h=s+r,l=this.lastLoadedFragLevel,d=l===-1?this.hls.firstLevel:l,{fragCurrent:u,partCurrent:c}=this,{levels:f,allAudioTracks:g,loadLevel:p,config:v}=this.hls;if(f.length===1)return 0;const y=f[d],E=!((o=this.hls.latestLevelDetails)==null||!o.live),T=p===-1||l===-1;let A,L="SDR",b=y?.frameRate||0;const{audioPreference:S,videoPreference:k}=v,D=this.audioTracksByGroup||(this.audioTracksByGroup=ia(g));let P=-1;if(T){if(this.firstSelection!==-1)return this.firstSelection;const w=this.codecTiers||(this.codecTiers=function(W,G,X,j){return W.slice(X,j+1).reduce((le,te,Ee)=>{if(!te.codecSet)return le;const K=te.audioGroups;let Q=le[te.codecSet];Q||(le[te.codecSet]=Q={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:Ee,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!K,fragmentError:0}),Q.minBitrate=Math.min(Q.minBitrate,te.bitrate);const he=Math.min(te.height,te.width);return Q.minHeight=Math.min(Q.minHeight,he),Q.minFramerate=Math.min(Q.minFramerate,te.frameRate),Q.minIndex=Math.min(Q.minIndex,Ee),Q.maxScore=Math.max(Q.maxScore,te.score),Q.fragmentError+=te.fragmentError,Q.videoRanges[te.videoRange]=(Q.videoRanges[te.videoRange]||0)+1,K&&K.forEach(de=>{if(!de)return;const ie=G.groups[de];ie&&(Q.hasDefaultAudio=Q.hasDefaultAudio||G.hasDefaultAudio?ie.hasDefault:ie.hasAutoSelect||!G.hasDefaultAudio&&!G.hasAutoSelectAudio,Object.keys(ie.channels).forEach(ge=>{Q.channels[ge]=(Q.channels[ge]||0)+ie.channels[ge]}))}),le},{})}(f,D,e,t)),_=function(W,G,X,j,le){const te=Object.keys(W),Ee=j?.channels,K=j?.audioCodec,Q=le?.videoCodec,he=Ee&&parseInt(Ee)===2;let de=!1,ie=!1,ge=1/0,se=1/0,Me=1/0,os=1/0,Bt=0,Tt=[];const{preferHDR:ls,allowedVideoRanges:Gt}=wo(G,le);for(let ue=te.length;ue--;){const me=W[te[ue]];de||(de=me.channels[2]>0),ge=Math.min(ge,me.minHeight),se=Math.min(se,me.minFramerate),Me=Math.min(Me,me.minBitrate),Gt.filter(Te=>me.videoRanges[Te]>0).length>0&&(ie=!0)}ge=U(ge)?ge:0,se=U(se)?se:0;const hs=Math.max(1080,ge),Kt=Math.max(30,se);Me=U(Me)?Me:X,X=Math.max(Me,X),ie||(G=void 0);const Re=te.length>1;return{codecSet:te.reduce((ue,me)=>{const Te=W[me];if(me===ue)return ue;if(Tt=ie?Gt.filter(js=>Te.videoRanges[js]>0):[],Re){if(Te.minBitrate>X)return Ke(me,`min bitrate of ${Te.minBitrate} > current estimate of ${X}`),ue;if(!Te.hasDefaultAudio)return Ke(me,"no renditions with default or auto-select sound found"),ue;if(K&&me.indexOf(K.substring(0,4))%5!=0)return Ke(me,`audio codec preference "${K}" not found`),ue;if(Ee&&!he){if(!Te.channels[Ee])return Ke(me,`no renditions with ${Ee} channel sound found (channels options: ${Object.keys(Te.channels)})`),ue}else if((!K||he)&&de&&Te.channels[2]===0)return Ke(me,"no renditions with stereo sound found"),ue;if(Te.minHeight>hs)return Ke(me,`min resolution of ${Te.minHeight} > maximum of ${hs}`),ue;if(Te.minFramerate>Kt)return Ke(me,`min framerate of ${Te.minFramerate} > maximum of ${Kt}`),ue;if(!Tt.some(js=>Te.videoRanges[js]>0))return Ke(me,`no variants with VIDEO-RANGE of ${oe(Tt)} found`),ue;if(Q&&me.indexOf(Q.substring(0,4))%5!=0)return Ke(me,`video codec preference "${Q}" not found`),ue;if(Te.maxScore<Bt)return Ke(me,`max score of ${Te.maxScore} < selected max of ${Bt}`),ue}return ue&&(xs(me)>=xs(ue)||Te.fragmentError>W[ue].fragmentError)?ue:(os=Te.minIndex,Bt=Te.maxScore,me)},void 0),videoRanges:Tt,preferHDR:ls,minFramerate:se,minBitrate:Me,minIndex:os}}(w,L,i,S,k),{codecSet:$,videoRanges:x,minFramerate:C,minBitrate:M,minIndex:V,preferHDR:Y}=_;P=V,A=$,L=Y?x[x.length-1]:x[0],b=C,i=Math.max(i,M),this.log(`picked start tier ${oe(_)}`)}else A=y?.codecSet,L=y?.videoRange;const O=c?c.duration:u?u.duration:0,N=this.bwEstimator.getEstimateTTFB()/1e3,B=[];for(let w=t;w>=e;w--){var F;const _=f[w],$=w>d;if(!_)continue;if(v.useMediaCapabilities&&!_.supportedResult&&!_.supportedPromise){const W=navigator.mediaCapabilities;typeof W?.decodingInfo=="function"&&Do(_,D,L,b,i,S)?(_.supportedPromise=ta(_,D,W,this.supportedCache),_.supportedPromise.then(G=>{if(!this.hls)return;_.supportedResult=G;const X=this.hls.levels,j=X.indexOf(_);G.error?this.warn(`MediaCapabilities decodingInfo error: "${G.error}" for level ${j} ${oe(G)}`):G.supported?G.decodingInfoResults.some(le=>le.smooth===!1||le.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${j} not smooth or powerEfficient: ${oe(G)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${j} ${oe(G)}`),j>-1&&X.length>1&&(this.log(`Removing unsupported level ${j}`),this.hls.removeLevel(j),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(G=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${G}`)})):_.supportedResult=Jn}if((A&&_.codecSet!==A||L&&_.videoRange!==L||$&&b>_.frameRate||!$&&b>0&&b<_.frameRate||(F=_.supportedResult)!=null&&(F=F.decodingInfoResults)!=null&&F.some(W=>W.smooth===!1))&&(!T||w!==P)){B.push(w);continue}const x=_.details,C=(c?x?.partTarget:x?.averagetargetduration)||O;let M;M=$?a*i:n*i;const V=O&&s>=2*O&&r===0?_.averageBitrate:_.maxBitrate,Y=this.getTimeToLoadFrag(N,M,V*C,x===void 0);if(M>=V&&(w===l||_.loadError===0&&_.fragmentError===0)&&(Y<=N||!U(Y)||E&&!this.bitrateTestDelay||Y<h)){const W=this.forcedAutoLevel;return w===p||W!==-1&&W===p||(B.length&&this.trace(`Skipped level(s) ${B.join(",")} of ${t} max with CODECS and VIDEO-RANGE:"${f[B[0]].codecs}" ${f[B[0]].videoRange}; not compatible with "${A}" ${L}`),this.info(`switch candidate:${d}->${w} adjustedbw(${Math.round(M)})-bitrate=${Math.round(M-V)} ttfb:${N.toFixed(1)} avgDuration:${C.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${Y.toFixed(1)} firstSelection:${T} codecSet:${_.codecSet} videoRange:${_.videoRange} hls.loadLevel:${p}`)),T&&(this.firstSelection=w),w}}return-1}set nextAutoLevel(i){const e=this.deriveNextAutoLevel(i);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(i){const{maxAutoLevel:e,minAutoLevel:t}=this.hls;return Math.min(Math.max(i,t),e)}},bufferController:class extends Fe{constructor(i,e){var t;super("buffer-controller",i.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var r;this.hls&&((r=this.mediaSource)==null?void 0:r.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:r,mediaSource:n}=this;s&&this.log("Media source opened"),r&&n&&(n.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:r,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:r}=this;s!==r&&this.error(`Media element src was set while attaching MediaSource (${r} > ${s})`)},this.hls=i,this.fragmentTracker=e,this.appendSource=(t=ut(i.config.preferManagedMediaSource),typeof self<"u"&&t===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:i}=this;i.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),i.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),i.on(m.MANIFEST_LOADING,this.onManifestLoading,this),i.on(m.MANIFEST_PARSED,this.onManifestParsed,this),i.on(m.BUFFER_RESET,this.onBufferReset,this),i.on(m.BUFFER_APPENDING,this.onBufferAppending,this),i.on(m.BUFFER_CODECS,this.onBufferCodecs,this),i.on(m.BUFFER_EOS,this.onBufferEos,this),i.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),i.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),i.on(m.FRAG_PARSED,this.onFragParsed,this),i.on(m.FRAG_CHANGED,this.onFragChanged,this),i.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:i}=this;i.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),i.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),i.off(m.MANIFEST_LOADING,this.onManifestLoading,this),i.off(m.MANIFEST_PARSED,this.onManifestParsed,this),i.off(m.BUFFER_RESET,this.onBufferReset,this),i.off(m.BUFFER_APPENDING,this.onBufferAppending,this),i.off(m.BUFFER_CODECS,this.onBufferCodecs,this),i.off(m.BUFFER_EOS,this.onBufferEos,this),i.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),i.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),i.off(m.FRAG_PARSED,this.onFragParsed,this),i.off(m.FRAG_CHANGED,this.onFragChanged,this),i.off(m.ERROR,this.onError,this)}transferMedia(){const{media:i,mediaSource:e}=this;if(!i)return null;const t={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const n=this.isQueued();(r||n)&&this.warn(`Transfering MediaSource with${n?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return!this.sourceBufferCount&&s&&s.mediaSource===e?ae(t,s.tracks):this.sourceBuffers.forEach(r=>{const[n]=r;n&&(t[n]=ae({},this.tracks[n]),this.removeBuffer(n)),r[0]=r[1]=null}),{media:i,mediaSource:e,tracks:t}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(i,e){var t;let s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(t=this.transferData)!=null&&t.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(i,e){const t=this.media=e.media;this.transferData=this.overrides=void 0;const s=ut(this.appendSource);if(s){const r=!!e.mediaSource;(r||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const n=this.mediaSource=e.mediaSource||new s;if(this.assignMediaSource(n),r)this._objectUrl=t.src,this.attachTransferred();else{const a=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{t.removeAttribute("src");const o=self.ManagedMediaSource;t.disableRemotePlayback=t.disableRemotePlayback||o&&n instanceof o,En(t),function(h,l){const d=self.document.createElement("source");d.type="video/mp4",d.src=l,h.appendChild(d)}(t,a),t.load()}catch{t.src=a}else t.src=a}t.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(i){var e,t;this.log(`${((e=this.transferData)==null?void 0:e.mediaSource)===i?"transferred":"created"} media source: ${(t=i.constructor)==null?void 0:t.name}`),i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.addEventListener("startstreaming",this._onStartStreaming),i.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const i=this.media,e=this.transferData;if(!e||!i)return;const t=this.tracks,s=e.tracks,r=s?Object.keys(s):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
38
+ required tracks: ${oe(t,(o,h)=>o==="initSegment"?void 0:h)};
39
+ transfer tracks: ${oe(s,(o,h)=>o==="initSegment"?void 0:h)}}`),!ur(s,t)){e.mediaSource=null,e.tracks=void 0;const o=i.currentTime,h=this.details,l=Math.max(o,h?.fragments[0].start||0);return l-o>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${o} -> ${l}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(t)}") start time: ${l} currentTime: ${o}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,e),void(i.currentTime=l))}this.transferData=void 0,r.forEach(o=>{const h=o,l=s[h];if(l){const d=l.buffer;if(d){const u=this.fragmentTracker,c=l.id;if(u.hasFragments(c)||u.hasParts(c)){const p=z.getBuffered(d);u.detectEvictedFragments(h,p,c,null,!0)}const f=ri(h),g=[h,d];this.sourceBuffers[f]=g,d.updating&&this.operationQueue&&this.operationQueue.prependBlocker(h),this.trackSourceBuffer(h,l)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var i;const e=(i=this.mediaSource)==null?void 0:i.readyState;return e==="open"||e==="ended"}onMediaDetaching(i,e){const t=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(t?"transferring":"detaching")),t)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=r.readyState==="open";try{const o=r.sourceBuffers;for(let h=o.length;h--;)a&&o[h].abort(),r.removeSourceBuffer(o[h]);a&&r.endOfStream()}catch(o){this.warn(`onMediaDetaching: ${o.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(s.removeEventListener("emptied",this._onMediaEmptied),t||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(s.removeAttribute("src"),this.appendSource&&En(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(m.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach(([i])=>{i&&this.resetBuffer(i)}),this.initTracks()}resetBuffer(i){var e;const t=(e=this.tracks[i])==null?void 0:e.buffer;if(this.removeBuffer(i),t)try{var s;(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}catch(r){this.warn(`onBufferReset ${i}`,r)}delete this.tracks[i]}removeBuffer(i){this.removeBufferListeners(i),this.sourceBuffers[ri(i)]=[null,null];const e=this.tracks[i];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new yl(this.tracks)}onBufferCodecs(i,e){var t;const s=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&r.some(o=>!s[o]);n||a?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`):(r.forEach(o=>{var h,l;const d=e[o],{id:u,codec:c,levelCodec:f,container:g,metadata:p,supplemental:v}=d;let y=s[o];const E=(h=this.transferData)==null||(h=h.tracks)==null?void 0:h[o],T=E!=null&&E.buffer?E:y,A=T?.pendingCodec||T?.codec,L=T?.levelCodec;y||(y=s[o]={buffer:void 0,listeners:[],codec:c,supplemental:v,container:g,levelCodec:f,metadata:p,id:u});const b=Rs(A,L),S=b?.replace(yn,"$1");let k=Rs(c,f);const D=(l=k)==null?void 0:l.replace(yn,"$1");k&&b&&S!==D&&(o.slice(0,5)==="audio"&&(k=Os(k,this.appendSource)),this.log(`switching codec ${A} to ${k}`),k!==(y.pendingCodec||y.codec)&&(y.pendingCodec=k),y.container=g,this.appendChangeType(o,g,k))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&((t=e.audio)==null?void 0:t.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((i,e)=>{const t=this.tracks[e];return i[e]={id:t.id,container:t.container,codec:t.codec,levelCodec:t.levelCodec},i},{})}appendChangeType(i,e,t){const s=`${e};codecs=${t}`,r={label:`change-type=${s}`,execute:()=>{const n=this.tracks[i];if(n){const a=n.buffer;a!=null&&a.changeType&&(this.log(`changing ${i} sourceBuffer type to ${s}`),a.changeType(s),n.codec=t,n.container=e)}this.shiftAndExecuteNext(i)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${i} SourceBuffer type`,n)}};this.append(r,i,this.isPending(this.tracks[i]))}blockAudio(i){var e;const t=i.start,s=t+.05*i.duration;if(((e=this.fragmentTracker.getAppendedFrag(t,Z))==null?void 0:e.gap)===!0)return;const r={label:"block-audio",execute:()=>{var n;const a=this.tracks.video;(this.lastVideoAppendEnd>s||a!=null&&a.buffer&&z.isBuffered(a.buffer,s)||((n=this.fragmentTracker.getAppendedFrag(s,Z))==null?void 0:n.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn("Error executing block-audio operation",n)}};this.blockedAudioAppend={op:r,frag:i},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:i,operationQueue:e}=this;i&&e&&(this.blockedAudioAppend=null,e.unblockAudio(i.op))}onBufferAppending(i,e){const{tracks:t}=this,{data:s,type:r,parent:n,frag:a,part:o,chunkMeta:h,offset:l}=e,d=h.buffering[r],{sn:u,cc:c}=a,f=self.performance.now();d.start=f;const g=a.stats.buffering,p=o?o.stats.buffering:null;g.start===0&&(g.start=f),p&&p.start===0&&(p.start=f);const v=t.audio;let y=!1;r==="audio"&&v?.container==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||h.id===1||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const E=t.video,T=E?.buffer;if(T&&u!=="initSegment"){const b=o||a,S=this.blockedAudioAppend;if(r!=="audio"||n==="main"||this.blockedAudioAppend||E.ending||E.ended){if(r==="video"){const k=b.end;if(S){const D=S.frag.start;(k>D||k<this.lastVideoAppendEnd||z.isBuffered(T,D))&&this.unblockAudio()}this.lastVideoAppendEnd=k}}else{const k=b.start+.05*b.duration,D=T.buffered,P=this.currentOp("video");D.length||P?!P&&!z.isBuffered(T,k)&&this.lastVideoAppendEnd<k&&this.blockAudio(b):this.blockAudio(b)}}const A=(o||a).start,L={label:`append-${r}`,execute:()=>{var b;d.executeStart=self.performance.now();const S=(b=this.tracks[r])==null?void 0:b.buffer;S&&(y?this.updateTimestampOffset(S,A,.1,r,u,c):l!==void 0&&U(l)&&this.updateTimestampOffset(S,l,1e-6,r,u,c)),this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{const b=self.performance.now();d.executeEnd=d.end=b,g.first===0&&(g.first=b),p&&p.first===0&&(p.first=b);const S={};this.sourceBuffers.forEach(([k,D])=>{k&&(S[k]=z.getBuffered(D))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(m.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:h,parent:a.type,timeRanges:S})},onError:b=>{var S;const k={type:H.MEDIA_ERROR,parent:a.type,details:I.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:h,error:b,err:b,fatal:!1},D=(S=this.media)==null?void 0:S.error;if(b.code===DOMException.QUOTA_EXCEEDED_ERR||b.name=="QuotaExceededError"||"quota"in b)k.details=I.BUFFER_FULL_ERROR;else if(b.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!D)k.errorAction=Lt(!0);else if(b.name===Va&&this.sourceBufferCount===0)k.errorAction=Lt(!0);else{const P=++this.appendErrors[r];this.warn(`Failed ${P}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${D||"no media error"})`),(P>=this.hls.config.appendErrorMaxRetry||D)&&(k.fatal=!0)}this.hls.trigger(m.ERROR,k)}};this.log(`queuing "${r}" append sn: ${u}${o?" p: "+o.index:""} of ${a.type===Z?"level":"track"} ${a.level} cc: ${c}`),this.append(L,r,this.isPending(this.tracks[r]))}getFlushOp(i,e,t){return this.log(`queuing "${i}" remove ${e}-${t}`),{label:"remove",execute:()=>{this.removeExecutor(i,e,t)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:i})},onError:s=>{this.warn(`Failed to remove ${e}-${t} from "${i}" SourceBuffer`,s)}}}onBufferFlushing(i,e){const{type:t,startOffset:s,endOffset:r}=e;t?this.append(this.getFlushOp(t,s,r),t):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,s,r),n)})}onFragParsed(i,e){const{frag:t,part:s}=e,r=[],n=s?s.elementaryStreams:t.elementaryStreams;n[Ei]?r.push("audiovideo"):(n[Oe]&&r.push("audio"),n[Ge]&&r.push("video")),r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${t.type} level: ${t.level} sn: ${t.sn}`),this.blockBuffers(()=>{const a=self.performance.now();t.stats.buffering.end=a,s&&(s.stats.buffering.end=a);const o=s?s.stats:t.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:t,part:s,stats:o,id:t.type})},r).catch(a=>{this.warn(`Fragment buffered callback ${a}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(i,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([i])=>{if(i){const e=this.tracks[i];if(e)return!e.ended||e.ending}return!1})}onBufferEos(i,e){var t;this.sourceBuffers.forEach(([r])=>{if(r){const n=this.tracks[r];e.type&&e.type!==r||(n.ending=!0,n.ended||(n.ended=!0,this.log(`${r} buffer reached EOS`)))}});const s=((t=this.overrides)==null?void 0:t.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([r])=>{var n;return r&&!((n=this.tracks[r])!=null&&n.ended)})?s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:r}=this;r&&r.readyState==="open"?(this.log("Calling mediaSource.endOfStream()"),r.endOfStream(),this.hls.trigger(m.BUFFERED_TO_END,void 0)):r&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${r.readyState}`)})):(this.tracksEnded(),this.hls.trigger(m.BUFFERED_TO_END,void 0)):e.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([i])=>{if(i!==null){const e=this.tracks[i];e&&(e.ending=!1)}})}onLevelUpdated(i,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const i=this.getDurationAndRange();i&&this.updateMediaSource(i)})}onError(i,e){if(e.details===I.BUFFER_APPEND_ERROR&&e.frag){var t;const s=(t=e.errorAction)==null?void 0:t.nextAutoLevel;U(s)&&s!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:i,details:e,media:t}=this;if(!t||e===null||!this.sourceBufferCount)return;const s=i.config,r=t.currentTime,n=e.levelTargetDuration,a=e.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:s.backBufferLength;if(U(a)&&a>=0){const h=Math.max(a,n),l=Math.floor(r/n)*n-h;this.flushBackBuffer(r,n,l)}const o=s.frontBufferFlushThreshold;if(U(o)&&o>0){const h=Math.max(s.maxBufferLength,o),l=Math.max(h,n),d=Math.floor(r/n)*n+l;this.flushFrontBuffer(r,n,d)}}flushBackBuffer(i,e,t){this.sourceBuffers.forEach(([s,r])=>{if(r){const a=z.getBuffered(r);if(a.length>0&&t>a.start(0)){var n;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:t});const o=this.tracks[s];if((n=this.details)!=null&&n.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:t});else if(o!=null&&o.ended)return void this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:t,type:s})}}})}flushFrontBuffer(i,e,t){this.sourceBuffers.forEach(([s,r])=>{if(r){const n=z.getBuffered(r),a=n.length;if(a<2)return;const o=n.start(a-1),h=n.end(a-1);if(t>o||i>=o&&i<=h)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:s})}})}getDurationAndRange(){var i;const{details:e,mediaSource:t}=this;if(!e||!this.media||t?.readyState!=="open")return null;const s=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&t.setLiveSeekableRange){const a=Math.max(0,e.fragmentStart);return{duration:1/0,start:a,end:Math.max(a,s)}}return{duration:1/0}}const r=(i=this.overrides)==null?void 0:i.duration;if(r)return U(r)?{duration:r}:null;const n=this.media.duration;return s>(U(t.duration)?t.duration:0)&&s>n||!U(n)?{duration:s}:null}updateMediaSource({duration:i,start:e,end:t}){const s=this.mediaSource;this.media&&s&&s.readyState==="open"&&(s.duration!==i&&(U(i)&&this.log(`Updating MediaSource duration to ${i.toFixed(3)}`),s.duration=i),e!==void 0&&t!==void 0&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${e}-${t}.`),s.setLiveSeekableRange(e,t)))}get tracksReady(){const i=this.pendingTrackCount;return i>0&&(i>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:i,pendingTrackCount:e,tracks:t}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${i}) ${oe(t)}`),this.tracksReady){var s;const r=(s=this.transferData)==null?void 0:s.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const i={};this.sourceBuffers.forEach(([e,t])=>{if(e){const s=this.tracks[e];i[e]={buffer:t,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(m.BUFFER_CREATED,{tracks:i}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{const i=new Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:i,reason:i.message})}}createSourceBuffers(){const{tracks:i,sourceBuffers:e,mediaSource:t}=this;if(!t)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in i){const n=r,a=i[n];if(this.isPending(a)){const o=this.getTrackCodec(a,n),h=`${a.container};codecs=${o}`;a.codec=o,this.log(`creating sourceBuffer(${h})${this.currentOp(n)?" Queued":""} ${oe(a)}`);try{const l=t.addSourceBuffer(h),d=ri(n),u=[n,l];e[d]=u,a.buffer=l}catch(l){var s;return this.error(`error while trying to add sourceBuffer: ${l.message}`),this.shiftAndExecuteNext(n),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[n],void this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:l,sourceBufferName:n,mimeType:h,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(i,e){const t=i.supplemental;let s=i.codec;t&&(e==="video"||e==="audiovideo")&&ts(t,"video")&&(s=function(n,a){const o=[];if(n){const h=n.split(",");for(let l=0;l<h.length;l++)Yi(h[l],"video")||o.push(h[l])}return a&&o.push(a),o.join(",")}(s,t));const r=Rs(s,i.levelCodec);return r?e.slice(0,5)==="audio"?Os(r,this.appendSource):r:""}trackSourceBuffer(i,e){const t=e.buffer;if(!t)return;const s=this.getTrackCodec(e,i);this.tracks[i]={buffer:t,codec:s,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(i),this.addBufferListener(i,"updatestart",this.onSBUpdateStart),this.addBufferListener(i,"updateend",this.onSBUpdateEnd),this.addBufferListener(i,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(i,"bufferedchange",(r,n)=>{const a=n.removedRanges;a!=null&&a.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var i,e;const t=((i=this.media)==null||(e=i.querySelector)==null?void 0:e.call(i,"source"))||this.media;return t?.src}onSBUpdateStart(i){const e=this.currentOp(i);e&&e.onStart()}onSBUpdateEnd(i){var e;if(((e=this.mediaSource)==null?void 0:e.readyState)==="closed")return void this.resetBuffer(i);const t=this.currentOp(i);t&&(t.onComplete(),this.shiftAndExecuteNext(i))}onSBUpdateError(i,e){var t;const s=new Error(`${i} SourceBuffer error. MediaSource readyState: ${(t=this.mediaSource)==null?void 0:t.readyState}`);this.error(`${s}`,e),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.BUFFER_APPENDING_ERROR,sourceBufferName:i,error:s,fatal:!1});const r=this.currentOp(i);r&&r.onError(s)}updateTimestampOffset(i,e,t,s,r,n){const a=e-i.timestampOffset;Math.abs(a)>=t&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${n})`),i.timestampOffset=e)}removeExecutor(i,e,t){const{media:s,mediaSource:r}=this,n=this.tracks[i],a=n?.buffer;if(!s||!r||!a)return this.warn(`Attempting to remove from the ${i} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(i);const o=U(s.duration)?s.duration:1/0,h=U(r.duration)?r.duration:1/0,l=Math.max(0,e),d=Math.min(t,o,h);d>l&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${l},${d}] from the ${i} SourceBuffer`),a.remove(l,d)):this.shiftAndExecuteNext(i)}appendExecutor(i,e){const t=this.tracks[e],s=t?.buffer;if(!s)throw new El(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);t.ending=!1,t.ended=!1,s.appendBuffer(i)}blockUntilOpen(i){if(this.isUpdating()||this.isQueued())this.blockBuffers(i).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{i()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([i,e])=>i&&e.updating)}isQueued(){return this.sourceBuffers.some(([i])=>i&&!!this.currentOp(i))}isPending(i){return!!i&&!i.buffer}blockBuffers(i,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(i);const{operationQueue:t}=this,s=e.map(r=>this.appendBlocker(r));return e.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(s).then(r=>{t===this.operationQueue&&(i(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(i){i.forEach(e=>{var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;s&&!s.updating&&this.shiftAndExecuteNext(e)})}append(i,e,t){this.operationQueue&&this.operationQueue.append(i,e,t)}appendBlocker(i){if(this.operationQueue)return this.operationQueue.appendBlocker(i)}currentOp(i){return this.operationQueue?this.operationQueue.current(i):null}executeNext(i){i&&this.operationQueue&&this.operationQueue.executeNext(i)}shiftAndExecuteNext(i){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(i)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((i,e)=>i+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((i,[e])=>i+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([i])=>i).filter(i=>!!i)}addBufferListener(i,e,t){const s=this.tracks[i];if(!s)return;const r=s.buffer;if(!r)return;const n=t.bind(this,i);s.listeners.push({event:e,listener:n}),r.addEventListener(e,n)}removeBufferListeners(i){const e=this.tracks[i];if(!e)return;const t=e.buffer;t&&(e.listeners.forEach(s=>{t.removeEventListener(s.event,s.listener)}),e.listeners.length=0)}},capLevelController:ar,errorController:class extends Fe{constructor(i){super("error-controller",i.logger),this.hls=void 0,this.playlistError=0,this.hls=i,this.registerListeners()}registerListeners(){const i=this.hls;i.on(m.ERROR,this.onError,this),i.on(m.MANIFEST_LOADING,this.onManifestLoading,this),i.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const i=this.hls;i&&(i.off(m.ERROR,this.onError,this),i.off(m.ERROR,this.onErrorOut,this),i.off(m.MANIFEST_LOADING,this.onManifestLoading,this),i.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(i){}stopLoad(){this.playlistError=0}getVariantLevelIndex(i){return i?.type===Z?i.level:this.getVariantIndex()}getVariantIndex(){var i;const e=this.hls,t=e.currentLevel;return(i=e.loadLevelObj)!=null&&i.details||t===-1?e.loadLevel:t}variantHasKey(i,e){if(i){var t;if((t=i.details)!=null&&t.hasKey(e))return!0;const s=i.audioGroups;if(s)return this.hls.allAudioTracks.filter(r=>s.indexOf(r.groupId)>=0).some(r=>{var n;return(n=r.details)==null?void 0:n.hasKey(e)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(i,e){var t;if(e.fatal)return;const s=this.hls,r=e.context;switch(e.details){case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case I.FRAG_PARSING_ERROR:if((t=e.frag)!=null&&t.gap)return void(e.errorAction=Lt());case I.FRAG_GAP:case I.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=We);case I.LEVEL_EMPTY_ERROR:case I.LEVEL_PARSING_ERROR:{var n;const o=e.parent===Z?e.level:s.loadLevel;e.details===I.LEVEL_EMPTY_ERROR&&(n=e.context)!=null&&(n=n.levelDetails)!=null&&n.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,o):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,o))}return;case I.LEVEL_LOAD_ERROR:case I.LEVEL_LOAD_TIMEOUT:return void(typeof r?.level=="number"&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level)));case I.AUDIO_TRACK_LOAD_ERROR:case I.AUDIO_TRACK_LOAD_TIMEOUT:case I.SUBTITLE_LOAD_ERROR:case I.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const o=s.loadLevelObj;if(o&&(r.type===Be&&o.hasAudioGroup(r.groupId)||r.type===qe&&o.hasSubtitleGroup(r.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=We,void(e.errorAction.flags=bs)}return;case I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:We,flags:Or});case I.KEY_SYSTEM_SESSION_UPDATE_FAILED:case I.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case I.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:We,flags:Mr});case I.BUFFER_ADD_CODEC_ERROR:case I.REMUX_ALLOC_ERROR:case I.BUFFER_APPEND_ERROR:var a;e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,(a=e.level)!=null?a:s.loadLevel));return;case I.INTERNAL_EXCEPTION:case I.BUFFER_APPENDING_ERROR:case I.BUFFER_FULL_ERROR:case I.LEVEL_SWITCH_ERROR:case I.BUFFER_STALLED_ERROR:case I.BUFFER_SEEK_OVER_HOLE:case I.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=Lt())}e.type===H.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=Lt())}getPlaylistRetryOrSwitchAction(i,e){const t=wr(this.hls.config.playlistLoadPolicy,i),s=this.playlistError++;if(Ns(t,s,Fs(i),i.response))return{action:Us,flags:Wt,retryConfig:t,retryCount:s};const r=this.getLevelSwitchAction(i,e);return t&&(r.retryConfig=t,r.retryCount=s),r}getFragRetryOrSwitchAction(i){const e=this.hls,t=this.getVariantLevelIndex(i.frag),s=e.levels[t],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=wr(aa(i)?n:r,i),o=e.levels.reduce((l,d)=>l+d.fragmentError,0);if(s&&(i.details!==I.FRAG_GAP&&s.fragmentError++,!oa(i))&&Ns(a,o,Fs(i),i.response))return{action:Us,flags:Wt,retryConfig:a,retryCount:o};const h=this.getLevelSwitchAction(i,t);return a&&(h.retryConfig=a,h.retryCount=o),h}getLevelSwitchAction(i,e){const t=this.hls;e==null&&(e=t.loadLevel);const s=this.hls.levels[e];if(s){var r,n;const h=i.details;s.loadError++,h===I.BUFFER_APPEND_ERROR&&s.fragmentError++;let l=-1;const{levels:d,loadLevel:u,minAutoLevel:c,maxAutoLevel:f}=t;t.autoLevelEnabled||t.config.preserveManualLevelOnError||(t.loadLevel=-1);const g=(r=i.frag)==null?void 0:r.type,p=(g===ke&&h===I.FRAG_PARSING_ERROR||i.sourceBufferName==="audio"&&(h===I.BUFFER_ADD_CODEC_ERROR||h===I.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:T})=>s.audioCodec!==T),v=i.sourceBufferName==="video"&&(h===I.BUFFER_ADD_CODEC_ERROR||h===I.BUFFER_APPEND_ERROR)&&d.some(({codecSet:T,audioCodec:A})=>s.codecSet!==T&&s.audioCodec===A),{type:y,groupId:E}=(n=i.context)!=null?n:{};for(let T=d.length;T--;){const A=(T+u)%d.length;if(A!==u&&A>=c&&A<=f&&d[A].loadError===0){var a,o;const L=d[A];if(h===I.FRAG_GAP&&g===Z&&i.frag){const b=d[A].details;if(b){const S=Et(i.frag,b.fragments,i.frag.start);if(S!=null&&S.gap)continue}}else if(y===Be&&L.hasAudioGroup(E)||y===qe&&L.hasSubtitleGroup(E)||g===ke&&(a=s.audioGroups)!=null&&a.some(b=>L.hasAudioGroup(b))||g===_e&&(o=s.subtitleGroups)!=null&&o.some(b=>L.hasSubtitleGroup(b))||p&&s.audioCodec===L.audioCodec||v&&s.codecSet===L.codecSet||!p&&s.codecSet!==L.codecSet)continue;l=A;break}}if(l>-1&&t.loadLevel!==l)return i.levelRetry=!0,this.playlistError=0,{action:We,flags:Wt,nextAutoLevel:l}}return{action:We,flags:bs}}onErrorOut(i,e){var t;switch((t=e.errorAction)==null?void 0:t.action){case la:break;case We:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===I.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(i){const e=this.hls,t=i.errorAction;if(!t)return;const{flags:s}=t,r=t.nextAutoLevel;switch(s){case Wt:this.switchLevel(i,r);break;case Or:{const o=this.getVariantLevelIndex(i.frag),h=e.levels[o],l=h?.attrs["HDCP-LEVEL"];if(t.hdcpLevel=l,l==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(l){e.maxHdcpLevel=Si[Si.indexOf(l)-1],t.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}}case Mr:{const o=i.decryptdata;if(o){const h=this.hls.levels,l=h.length;for(let u=l;u--;){var n,a;this.variantHasKey(h[u],o)&&(this.log(`Banned key found in level ${u} (${h[u].bitrate}bps) or audio group "${(n=h[u].audioGroups)==null?void 0:n.join(",")}" (${(a=i.frag)==null?void 0:a.type} fragment) ${Le(o.keyId||[])}`),h[u].fragmentError++,h[u].loadError++,this.log(`Removing level ${u} with key error (${i.error})`),this.hls.removeLevel(u))}const d=i.frag;if(this.hls.levels.length<l)t.resolved=!0;else if(d&&d.type!==Z){const u=d.decryptdata;u&&!o.matches(u)&&(t.resolved=!0)}}break}}t.resolved||this.switchLevel(i,r)}switchLevel(i,e){if(e!==void 0&&i.errorAction&&(this.warn(`switching to level ${e} after ${i.details}`),this.hls.nextAutoLevel=e,i.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,i.details===I.BUFFER_ADD_CODEC_ERROR&&i.mimeType&&i.sourceBufferName!=="audiovideo")){const t=Ti(i.mimeType),s=this.hls.levels;for(let r=s.length;r--;)s[r][`${i.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${r} for ${i.details} ("${t}" not supported)`),this.hls.removeLevel(r))}}},fpsController:class{constructor(i){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=i,this.registerListeners()}setStreamController(i){this.streamController=i}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(i,e){const t=this.hls.config;if(t.capLevelOnFPSDrop){const s=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),t.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(i,e,t){const s=performance.now();if(e){if(this.lastTime){const r=s-this.lastTime,n=t-this.lastDroppedFrames,a=e-this.lastDecodedFrames,o=1e3*n/r,h=this.hls;if(h.trigger(m.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:t}),o>0&&n>h.config.fpsDroppedMonitoringThreshold*a){let l=h.currentLevel;h.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+l),l>0&&(h.autoLevelCapping===-1||h.autoLevelCapping>=l)&&(l-=1,h.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:l,droppedLevel:h.currentLevel}),h.autoLevelCapping=l,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=t,this.lastDecodedFrames=e}}checkFPSInterval(){const i=this.media;if(i)if(this.isVideoPlaybackQualityAvailable){const e=i.getVideoPlaybackQuality();this.checkFPS(i,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(i,i.webkitDecodedFrameCount,i.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ma,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:uh,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends Di{constructor(i,e,t){super(i,e,t,"subtitle-stream-controller",_e),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:i}=this;i.on(m.LEVEL_LOADED,this.onLevelLoaded,this),i.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),i.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),i.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),i.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),i.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:i}=this;i.off(m.LEVEL_LOADED,this.onLevelLoaded,this),i.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),i.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),i.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),i.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),i.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(i,e){this.stopLoad(),this.state=J,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=i+this.timelineOffset,this.startPosition=e?-1:i,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(i,e){this.tracksBuffered=[],super.onMediaDetaching(i,e)}onLevelLoaded(i,e){this.mainDetails=e.details}onSubtitleFragProcessed(i,e){const{frag:t,success:s}=e;if(this.fragContextChanged(t)||(ve(t)&&(this.fragPrevious=t),this.state=J),!s)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=t.start;for(let h=0;h<r.length;h++)if(a>=r[h].start&&a<=r[h].end){n=r[h];break}const o=t.start+t.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(t),this.fragBufferedComplete(t,null),this.media&&this.tick()}onBufferFlushing(i,e){const{startOffset:t,endOffset:s}=e;if(t===0&&s!==Number.POSITIVE_INFINITY){const r=s-1;if(r<=0)return;e.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(n=>{for(let a=0;a<n.length;)if(n[a].end<=r)n.shift();else{if(!(n[a].start<r))break;n[a].start=r,a++}}),this.fragmentTracker.removeFragmentsInRange(t,r,_e)}}onError(i,e){const t=e.frag;t?.type===_e&&(e.details===I.FRAG_GAP&&this.fragmentTracker.fragBuffered(t,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ye&&(this.state=J))}onSubtitleTracksUpdated(i,{subtitleTracks:e}){this.levels&&vn(this.levels,e)?this.levels=e.map(t=>new Yt(t)):(this.tracksBuffered=[],this.levels=e.map(t=>{const s=new Yt(t);return this.tracksBuffered[s.id]=[],s}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,_e),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(i,e){var t;if(this.currentTrackId=e.id,(t=this.levels)==null||!t.length||this.currentTrackId===-1)return void this.clearInterval();const s=this.levels[this.currentTrackId];s!=null&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.state!==ye&&this.setInterval(500)}onSubtitleTrackLoaded(i,e){var t;const{currentTrackId:s,levels:r}=this,{details:n,id:a}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let h=0;if(n.live||(t=o.details)!=null&&t.live){if(n.deltaUpdateFailed)return;const d=this.mainDetails;if(!d)return void(this.startFragRequested=!1);const u=d.fragments[0];var l;o.details?(h=this.alignPlaylists(n,o.details,(l=this.levelLastLoaded)==null?void 0:l.details),h===0&&u&&(h=u.start,bi(n,h))):n.hasProgramDateTime&&d.hasProgramDateTime?(Ds(n,d),h=n.fragmentStart):u&&(h=u.start,bi(n,h)),d&&!this.startFragRequested&&this.setStartPosition(d,h)}o.details=n,this.levelLastLoaded=o,a===s&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:e.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===J)&&(Et(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0))}_handleFragmentLoadComplete(i){const{frag:e,payload:t}=i,s=e.decryptdata,r=this.hls;if(!this.fragContextChanged(e)&&t&&t.byteLength>0&&s!=null&&s.key&&s.iv&&xt(s.method)){const n=performance.now();this.decrypter.decrypt(new Uint8Array(t),s.key.buffer,s.iv.buffer,Qi(s.method)).catch(a=>{throw r.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:e}),a}).then(a=>{const o=performance.now();r.trigger(m.FRAG_DECRYPTED,{frag:e,payload:a,stats:{tstart:n,tdecrypt:o}})}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=J})}}doTick(){if(this.media){if(this.state===J){const{currentTrackId:i,levels:e}=this,t=e?.[i];if(!t||!e.length||!t.details||this.waitForLive(t))return;const{config:s}=this,r=this.getLoadPosition(),n=z.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,s.maxBufferHole),{end:a,len:o}=n,h=t.details;if(o>this.hls.maxBufferLength+h.levelTargetDuration)return;const l=h.fragments,d=l.length,u=h.edge;let c=null;const f=this.fragPrevious;if(a<u){const p=s.maxFragLookUpTolerance,v=a>u-p?0:p;c=Et(f,l,Math.max(l[0].start,a),v),!c&&f&&f.start<l[0].start&&(c=l[0])}else c=l[d-1];if(c=this.filterReplacedPrimary(c,t.details),!c)return;const g=l[c.sn-h.startSN-1];if(g&&g.cc===c.cc&&this.fragmentTracker.getState(g)===zt&&(c=g),this.fragmentTracker.getState(c)===zt){const p=this.mapToInitFragWhenRequired(c);p&&this.loadFragment(p,t,a)}}}else this.state=J}loadFragment(i,e,t){ve(i)?super.loadFragment(i,e,t):this._loadInitSegment(i,e)}get mediaBufferTimeRanges(){return new Yl(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends wi{constructor(i){super(i,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null;const t=vs(this.media.textTracks);for(let r=0;r<t.length;r++)if(t[r].mode==="hidden")e=t[r];else if(t[r].mode==="showing"){e=t[r];break}const s=this.findTrackForTextTrack(e);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(i){this._subtitleDisplay=i,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:i}=this;i.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),i.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),i.on(m.MANIFEST_LOADING,this.onManifestLoading,this),i.on(m.MANIFEST_PARSED,this.onManifestParsed,this),i.on(m.LEVEL_LOADING,this.onLevelLoading,this),i.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),i.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),i.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:i}=this;i.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),i.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),i.off(m.MANIFEST_LOADING,this.onManifestLoading,this),i.off(m.MANIFEST_PARSED,this.onManifestParsed,this),i.off(m.LEVEL_LOADING,this.onLevelLoading,this),i.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),i.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),i.off(m.ERROR,this.onError,this)}onMediaAttached(i,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(i){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,i)}onMediaDetaching(i,e){const t=this.media;if(!t)return;const s=!!e.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||t.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!s&&vs(t.textTracks).forEach(r=>{Pt(r)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(i,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(i,e){const{id:t,groupId:s,details:r}=e,n=this.tracksInGroup[t];if(!n||n.groupId!==s)return void this.warn(`Subtitle track with id:${t} and group:${s} not found in active group ${n?.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${t} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),t===this.trackId&&this.playlistLoaded(t,e,a)}onLevelLoading(i,e){this.switchLevel(e.level)}onLevelSwitching(i,e){this.switchLevel(e.level)}switchLevel(i){const e=this.hls.levels[i];if(!e)return;const t=e.subtitleGroups||null,s=this.groupIds;let r=this.currentTrack;if(!t||s?.length!==t?.length||t!=null&&t.some(n=>s?.indexOf(n)===-1)){this.groupIds=t,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(l=>!t||t.indexOf(l.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(l=>l.default)&&(this.selectDefaultTrack=!1),n.forEach((l,d)=>{l.id=d});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const a=this.hls.config.subtitlePreference;if(!r&&a){this.selectDefaultTrack=!1;const l=He(a,n);if(l>-1)r=n[l];else{const d=He(a,this.tracks);r=this.tracks[d]}}let o=this.findTrackId(r);o===-1&&r&&(o=this.findTrackId(null));const h={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${t?.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,h),o!==-1&&this.trackId===-1&&this.setSubtitleTrack(o)}}findTrackId(i){const e=this.tracksInGroup,t=this.selectDefaultTrack;for(let s=0;s<e.length;s++){const r=e[s];if((!t||r.default)&&(t||i)&&(!i||pt(r,i)))return s}if(i){for(let s=0;s<e.length;s++){const r=e[s];if(Xt(i.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const r=e[s];if(Xt(i.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(i){if(i){const e=this.tracksInGroup;for(let t=0;t<e.length;t++)if(xi(e[t],i))return t}return-1}onError(i,e){!e.fatal&&e.context&&(e.context.type!==qe||e.context.id!==this.trackId||this.groupIds&&this.groupIds.indexOf(e.context.groupId)===-1||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(i){this.selectDefaultTrack=!1,this.setSubtitleTrack(i)}setSubtitleOption(i){if(this.hls.config.subtitlePreference=i,i){if(i.id===-1)return this.setSubtitleTrack(-1),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const t=this.currentTrack;if(t&&pt(i,t))return t;const s=He(i,this.tracksInGroup);if(s>-1){const r=this.tracksInGroup[s];return this.setSubtitleTrack(s),r}if(t)return null;{const r=He(i,e);if(r>-1)return e[r]}}}return null}loadPlaylist(i){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,i)}loadingPlaylist(i,e){super.loadingPlaylist(i,e);const t=i.id,s=i.groupId,r=this.getUrlWithDirectives(i.url,e),n=i.details,a=n?.age;this.log(`Loading subtitle ${t} "${i.name}" lang:${i.lang} group:${s}${e?.msn!==void 0?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:t,groupId:s,deliveryDirectives:e||null,track:i})}toggleTrackModes(){const{media:i}=this;if(!i)return;const e=vs(i.textTracks),t=this.currentTrack;let s;if(t&&(s=e.filter(r=>xi(t,r))[0],s||this.warn(`Unable to find subtitle TextTrack with name "${t.name}" and language "${t.lang}"`)),[].slice.call(e).forEach(r=>{r.mode!=="disabled"&&r!==s&&(r.mode="disabled")}),s){const r=this.subtitleDisplay?"showing":"hidden";s.mode!==r&&(s.mode=r)}}setSubtitleTrack(i){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=i);if(i<-1||i>=e.length||!U(i))return void this.warn(`Invalid subtitle track id: ${i}`);this.selectDefaultTrack=!1;const t=this.currentTrack,s=e[i]||null;if(this.trackId=i,this.currentTrack=s,this.toggleTrackModes(),!s)return void this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:i});const r=!!s.details&&!s.details.live;if(i===this.trackId&&s===t&&r)return;this.log(`Switching to subtitle-track ${i}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));const{id:n,groupId:a="",name:o,type:h,url:l}=s;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:h,url:l});const d=this.switchParams(s.url,t?.details,s.details);this.loadPlaylist(d)}},timelineController:class{constructor(i){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=i,this.config=i.config,this.Cues=i.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},i.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),i.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),i.on(m.MANIFEST_LOADING,this.onManifestLoading,this),i.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),i.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),i.on(m.FRAG_LOADING,this.onFragLoading,this),i.on(m.FRAG_LOADED,this.onFragLoaded,this),i.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),i.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),i.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),i.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),i.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:i}=this;i.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),i.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),i.off(m.MANIFEST_LOADING,this.onManifestLoading,this),i.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),i.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),i.off(m.FRAG_LOADING,this.onFragLoading,this),i.off(m.FRAG_LOADED,this.onFragLoaded,this),i.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),i.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),i.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),i.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),i.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const i=new Ss(this,"textTrack1"),e=new Ss(this,"textTrack2"),t=new Ss(this,"textTrack3"),s=new Ss(this,"textTrack4");this.cea608Parser1=new Cn(1,i,e),this.cea608Parser2=new Cn(3,t,s)}addCues(i,e,t,s,r){let n=!1;for(let a=r.length;a--;){const o=r[a],h=hh(o[0],o[1],e,t);if(h>=0&&(o[0]=Math.min(o[0],e),o[1]=Math.max(o[1],t),n=!0,h/(t-e)>.5))return}if(n||r.push([e,t]),this.config.renderTextTracksNatively){const a=this.captionsTracks[i];this.Cues.newCue(a,e,t,s)}else{const a=this.Cues.newCue(null,e,t,s);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:a,track:i})}}onInitPtsFound(i,{frag:e,id:t,initPTS:s,timescale:r,trackId:n}){const{unparsedVttFrags:a}=this;t===Z&&(this.initPTS[e.cc]={baseTime:s,timescale:r,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.initPTS[o.frag.cc]?this.onFragLoaded(m.FRAG_LOADED,o):this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:o.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(i,e){const{media:t}=this;if(t)for(let s=0;s<t.textTracks.length;s++){const r=t.textTracks[s];if(Fn(r,{name:i,lang:e,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(i){this.config.renderTextTracksNatively?this.createNativeTrack(i):this.createNonNativeTrack(i)}createNativeTrack(i){if(this.captionsTracks[i])return;const{captionsProperties:e,captionsTracks:t,media:s}=this,{label:r,languageCode:n}=e[i],a=this.getExistingTrack(r,n);if(a)t[i]=a,Pt(t[i]),Ja(t[i],s);else{const o=this.createTextTrack("captions",r,n);o&&(o[i]=!0,t[i]=o)}}createNonNativeTrack(i){if(this.nonNativeCaptionsTracks[i])return;const e=this.captionsProperties[i];if(!e)return;const t={_id:i,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[i]=t,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[t]})}createTextTrack(i,e,t){const s=this.media;if(s)return s.addTextTrack(i,e,t)}onMediaAttaching(i,e){this.media=e.media,e.mediaSource||this._cleanTracks()}onMediaDetaching(i,e){const t=!!e.transferMedia;if(this.media=null,t)return;const{captionsTracks:s}=this;Object.keys(s).forEach(r=>{Pt(s[r]),delete s[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:i}=this;if(!i)return;const e=i.textTracks;if(e)for(let t=0;t<e.length;t++)Pt(e[t])}onSubtitleTracksUpdated(i,e){const t=e.subtitleTracks||[],s=t.some(r=>r.textCodec===di);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(vn(this.tracks,t))return void(this.tracks=t);if(this.textTracks=[],this.tracks=t,this.config.renderTextTracksNatively){const r=this.media,n=r?vs(r.textTracks):null;if(this.tracks.forEach((a,o)=>{let h;if(n){let l=null;for(let d=0;d<n.length;d++)if(n[d]&&Fn(n[d],a)){l=n[d],n[d]=null;break}l&&(h=l)}if(h)Pt(h);else{const l=lo(a);h=this.createTextTrack(l,a.name,a.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),n!=null&&n.length){const a=n.filter(o=>o!==null).map(o=>o.label);a.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${a.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const r=this.tracks.map(n=>({label:n.name,kind:n.type.toLowerCase(),default:n.default,subtitleTrack:n}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:r})}}}onManifestLoaded(i,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(t=>{const s=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!s)return;const r=`textTrack${s[1]}`,n=this.captionsProperties[r];n&&(n.label=t.name,t.lang&&(n.languageCode=t.lang),n.media=t)})}closedCaptionsForLevel(i){const e=this.hls.levels[i.level];return e?.attrs["CLOSED-CAPTIONS"]}onFragLoading(i,e){if(this.enabled&&e.frag.type===Z){var t,s;const{cea608Parser1:r,cea608Parser2:n,lastSn:a}=this,{cc:o,sn:h}=e.frag,l=(t=(s=e.part)==null?void 0:s.index)!=null?t:-1;r&&n&&(h!==a+1||h===a&&l!==this.lastPartIndex+1||o!==this.lastCc)&&(r.reset(),n.reset()),this.lastCc=o,this.lastSn=h,this.lastPartIndex=l}}onFragLoaded(i,e){const{frag:t,payload:s}=e;if(t.type===_e)if(s.byteLength){const r=t.decryptdata,n="stats"in e;if(r==null||!r.encrypted||n){const a=this.tracks[t.level],o=this.vttCCs;o[t.cc]||(o[t.cc]={start:t.start,prevCC:this.prevCC,new:!0},this.prevCC=t.cc),a&&a.textCodec===di?this._parseIMSC1(t,s):this._parseVTTs(e)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:new Error("Empty subtitle payload")})}_parseIMSC1(i,e){const t=this.hls;xn(e,this.initPTS[i.cc],s=>{this._appendCues(s,i.level),t.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},s=>{t.logger.log(`Failed to parse IMSC1: ${s}`),t.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:s})})}_parseVTTs(i){var e;const{frag:t,payload:s}=i,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[t.cc]&&a===-1)return void n.push(i);const o=this.hls;oh((e=t.initSegment)!=null&&e.data?Ne(t.initSegment.data,new Uint8Array(s)).buffer:s,this.initPTS[t.cc],this.vttCCs,t.cc,t.start,h=>{this._appendCues(h,t.level),o.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},h=>{const l=h.message==="Missing initPTS for VTT MPEGTS";l?n.push(i):this._fallbackToIMSC1(t,s),o.logger.log(`Failed to parse VTT cue: ${h}`),l&&a>t.cc||o.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:h})})}_fallbackToIMSC1(i,e){const t=this.tracks[i.level];t.textCodec||xn(e,this.initPTS[i.cc],()=>{t.textCodec=di,this._parseIMSC1(i,e)},()=>{t.textCodec="wvtt"})}_appendCues(i,e){const t=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||s.mode==="disabled")return;i.forEach(r=>eo(s,r))}else{const s=this.tracks[e];if(!s)return;const r=s.default?"default":"subtitles"+e;t.trigger(m.CUES_PARSED,{type:"subtitles",cues:i,track:r})}}onFragDecrypted(i,e){const{frag:t}=e;t.type===_e&&this.onFragLoaded(m.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(i,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:t,samples:s}=e;if(t.type!==Z||this.closedCaptionsForLevel(t)!=="NONE")for(let r=0;r<s.length;r++){const n=s[r].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();const a=this.extractCea608Data(n);this.cea608Parser1.addData(s[r].pts,a[0]),this.cea608Parser2.addData(s[r].pts,a[1])}}}onBufferFlushing(i,{startOffset:e,endOffset:t,endOffsetSubtitles:s,type:r}){const{media:n}=this;if(n&&!(n.currentTime<t)){if(!r||r==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(o=>Ui(a[o],e,t))}if(this.config.renderTextTracksNatively&&e===0&&s!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(o=>Ui(a[o],e,s))}}}extractCea608Data(i){const e=[[],[]],t=31&i[0];let s=2;for(let r=0;r<t;r++){const n=i[s++],a=127&i[s++],o=127&i[s++];if(!(a===0&&o===0)&&4&n){const h=3&n;h!==0&&h!==1||(e[h].push(a),e[h].push(o))}}return e}},audioStreamController:class extends Di{constructor(i,e,t){super(i,e,t,"audio-stream-controller",ke),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:i}=this;i.on(m.LEVEL_LOADED,this.onLevelLoaded,this),i.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),i.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),i.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),i.on(m.BUFFER_RESET,this.onBufferReset,this),i.on(m.BUFFER_CREATED,this.onBufferCreated,this),i.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),i.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),i.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),i.on(m.FRAG_LOADING,this.onFragLoading,this),i.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:i}=this;i&&(super.unregisterListeners(),i.off(m.LEVEL_LOADED,this.onLevelLoaded,this),i.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),i.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),i.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),i.off(m.BUFFER_RESET,this.onBufferReset,this),i.off(m.BUFFER_CREATED,this.onBufferCreated,this),i.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),i.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),i.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),i.off(m.FRAG_LOADING,this.onFragLoading,this),i.off(m.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(i,{frag:e,id:t,initPTS:s,timescale:r,trackId:n}){if(t===Z){const a=e.cc,o=this.fragCurrent;if(this.initPTS[a]={baseTime:s,timescale:r,trackId:n},this.log(`InitPTS for cc: ${a} found from main: ${s/r} (${s}/${r}) trackId: ${n}`),this.mainAnchor=e,this.state===Ht){const h=this.waitingData;(!h&&!this.loadingParts||h&&h.frag.cc!==a)&&this.syncWithAnchor(e,h?.frag)}else!this.hls.hasEnoughToStart&&o&&o.cc!==a?(o.abortRequests(),this.syncWithAnchor(e,o)):this.state===J&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(i,e){var t;const s=((t=this.mainFragLoading)==null?void 0:t.frag)||null;if(e&&s?.cc===e.cc)return;const r=(s||i).cc,n=na(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===J&&this.doTickIdle())}startLoad(i,e){if(!this.levels)return this.startPosition=i,void(this.state=ye);const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),t>0&&i===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),i=t,this.state=J):this.state=It,this.nextLoadPosition=this.lastCurrentTime=i+this.timelineOffset,this.startPosition=e?-1:i,this.tick()}doTick(){switch(this.state){case J:this.doTickIdle();break;case It:{const{levels:i,trackId:e}=this,t=i?.[e],s=t?.details;if(s&&!this.waitForLive(t)){if(this.waitForCdnTuneIn(s))break;this.state=Ht}break}case Mt:this.checkRetryDate();break;case Ht:{const i=this.waitingData;if(i){const{frag:e,part:t,cache:s,complete:r}=i,n=this.mainAnchor;if(this.initPTS[e.cc]!==void 0){this.waitingData=null,this.state=Ot;const a={frag:e,part:t,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(a),r&&super._handleFragmentLoadComplete(a)}else n&&n.cc!==i.frag.cc&&this.syncWithAnchor(n,i.frag)}else this.state=J}}this.onTickEnd()}resetLoadingState(){const i=this.waitingData;i&&(this.fragmentTracker.removeFragment(i.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:i}=this;i!=null&&i.readyState&&(this.lastCurrentTime=i.currentTime)}doTickIdle(){var i;const{hls:e,levels:t,media:s,trackId:r}=this,n=e.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||t==null||!t[r])return;const a=t[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o))return this.state=It,void(this.startFragRequested=!1);const h=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&h&&(this.bufferFlushed=!1,this.afterBufferFlushed(h,Oe,ke));const l=this.getFwdBufferInfo(h,ke);if(l===null)return;if(!this.switchingTrack&&this._streamEnded(l,o))return e.trigger(m.BUFFER_EOS,{type:"audio"}),void(this.state=$t);const d=l.len,u=e.maxBufferLength,c=o.fragments,f=c[0].start,g=this.getLoadPosition(),p=this.flushing?g:l.end;if(this.switchingTrack&&s){const E=g;o.PTSKnown&&E<f&&(l.end>f||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=f+.05)}if(d>=u&&!this.switchingTrack&&p<c[c.length-1].start)return;let v=this.getNextFragment(p,o);if(v&&this.isLoopLoading(v,p)&&(v=this.getNextFragmentLoopLoading(v,o,l,Z,u)),!v)return void(this.bufferFlushed=!0);let y=((i=this.mainFragLoading)==null?void 0:i.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&ve(v)&&!v.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===wt&&(this.mainFragLoading=y=null),y&&ve(y))){if(v.start>y.end){const E=this.fragmentTracker.getFragAtPos(p,Z);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(v.start>y.end)return}this.loadFragment(v,a,p)}onMediaDetaching(i,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(i,e)}onAudioTracksUpdated(i,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new Yt(t))}onAudioTrackSwitching(i,e){const t=!!e.url;this.trackId=e.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),t?(this.switchingTrack=e,this.flushAudioIfNeeded(e),this.state!==ye&&(this.setInterval(100),this.state=J,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(i,e){this.mainDetails=e.details;const t=this.cachedTrackLoadedData;t&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,t))}onAudioTrackLoaded(i,e){var t;const{levels:s}=this,{details:r,id:n,groupId:a,track:o}=e;if(!s)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);const h=this.mainDetails;if(!h||r.endCC>h.endCC||h.expired)return this.cachedTrackLoadedData=e,void(this.state!==ye&&(this.state=It));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const l=s[n];let d=0;if(r.live||(t=l.details)!=null&&t.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var u;l.details&&(d=this.alignPlaylists(r,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)),r.alignedSliding||(Ia(r,h),r.alignedSliding||Ds(r,h),d=r.fragmentStart)}l.details=r,this.levelLastLoaded=l,this.startFragRequested||this.setStartPosition(h,d),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:e.groupId}),this.state!==It||this.waitForCdnTuneIn(r)||(this.state=J),this.tick()}_handleFragmentLoadProgress(i){var e;const t=i.frag,{part:s,payload:r}=i,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);const h=o[a];if(!h)return void this.warn("Audio track is undefined on fragment load progress");const l=h.details;if(!l)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(t.start);const d=n.defaultAudioCodec||h.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new Ha(this.hls,ke,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const c=this.initPTS[t.cc],f=(e=t.initSegment)==null?void 0:e.data;if(c!==void 0){const p=s?s.index:-1,v=p!==-1,y=new zi(t.level,t.sn,t.stats.chunkCount,r.byteLength,p,v);u.push(r,f,d,"",t,s,l.totalduration,!1,y,c)}else{this.log(`Unknown video PTS for cc ${t.cc}, waiting for video PTS before demuxing audio frag ${t.sn} of [${l.startSN} ,${l.endSN}],track ${a}`);const{cache:g}=this.waitingData=this.waitingData||{frag:t,part:s,cache:new ba,complete:!1};g.push(new Uint8Array(r)),this.state!==ye&&(this.state=Ht)}}_handleFragmentLoadComplete(i){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(i)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(i,e){this.bufferFlushed=this.flushing=!1;const t=e.tracks.audio;t&&(this.mediaBuffer=t.buffer||null)}onFragLoading(i,e){!this.audioOnly&&e.frag.type===Z&&ve(e.frag)&&(this.mainFragLoading=e,this.state===J&&this.tick())}onFragBuffered(i,e){const{frag:t,part:s}=e;if(t.type===ke)if(this.fragContextChanged(t))this.warn(`Fragment ${t.sn}${s?" p: "+s.index:""} of level ${t.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(ve(t)){this.fragPrevious=t;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,re({},r)))}this.fragBufferedComplete(t,s),this.media&&this.tick()}else this.audioOnly||t.type!==Z||t.elementaryStreams.video||t.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}onError(i,e){var t;if(e.fatal)this.state=it;else switch(e.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ke,e);break;case I.AUDIO_TRACK_LOAD_ERROR:case I.AUDIO_TRACK_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==It||((t=e.context)==null?void 0:t.type)!==Be||(this.state=J);break;case I.BUFFER_ADD_CODEC_ERROR:case I.BUFFER_APPEND_ERROR:if(e.parent!=="audio")return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case I.BUFFER_FULL_ERROR:if(e.parent!=="audio")return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case I.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(i,{type:e}){e!==Ge&&(this.flushing=!0)}onBufferFlushed(i,{type:e}){if(e!==Ge){this.flushing=!1,this.bufferFlushed=!0,this.state===$t&&(this.state=J);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,ke),this.tick())}}_handleTransmuxComplete(i){var e;const t="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=i,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:h,level:l}=a,{details:d}=l,{audio:u,text:c,id3:f,initSegment:g}=r;if(!this.fragContextChanged(o)&&d){if(this.state=rt,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){const p=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(l,g.tracks,p,n),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:t,tracks:g.tracks})}if(u){const{startPTS:p,endPTS:v,startDTS:y,endDTS:E}=u;h&&(h.elementaryStreams[Oe]={startPTS:p,endPTS:v,startDTS:y,endDTS:E}),o.setElementaryStreamInfo(Oe,p,v,y,E),this.bufferFragmentData(u,o,h,n)}if(f!=null&&(e=f.samples)!=null&&e.length){const p=ae({id:t,frag:o,details:d},f);s.trigger(m.FRAG_PARSING_METADATA,p)}if(c){const p=ae({id:t,frag:o,details:d},c);s.trigger(m.FRAG_PARSING_USERDATA,p)}}else this.fragmentTracker.removeFragment(o)}_bufferInitSegment(i,e,t,s){if(this.state!==rt||(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio))return;const r=e.audio;r.id=ke;const n=i.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&n.split(",").length===1&&(r.levelCodec=n),this.hls.trigger(m.BUFFER_CODECS,e);const a=r.initSegment;if(a!=null&&a.byteLength){const o={type:"audio",frag:t,part:null,chunkMeta:s,parent:t.type,data:a};this.hls.trigger(m.BUFFER_APPENDING,o)}this.tickImmediate()}loadFragment(i,e,t){const s=this.fragmentTracker.getState(i);var r;if(this.switchingTrack||s===zt||s===_t)if(ve(i))if((r=e.details)!=null&&r.live&&!this.initPTS[i.cc]){this.log(`Waiting for video PTS in continuity counter ${i.cc} of live stream before loading audio fragment ${i.sn} of level ${this.trackId}`),this.state=Ht;const n=this.mainDetails;n&&n.fragmentStart!==e.details.fragmentStart&&Ds(e.details,n)}else super.loadFragment(i,e,t);else this._loadInitSegment(i,e);else this.clearTrackerIfNeeded(i)}flushAudioIfNeeded(i){if(this.media&&this.bufferedTrack){const{name:e,lang:t,assocLang:s,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;pt({name:e,lang:t,assocLang:s,characteristics:r,audioCodec:n,channels:a},i,ct)||(Ms(i.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=i)}}completeAudioSwitch(i){const{hls:e}=this;this.flushAudioIfNeeded(i),this.bufferedTrack=i,this.switchingTrack=null,e.trigger(m.AUDIO_TRACK_SWITCHED,re({},i))}},audioTrackController:class extends wi{constructor(i){super(i,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:i}=this;i.on(m.MANIFEST_LOADING,this.onManifestLoading,this),i.on(m.MANIFEST_PARSED,this.onManifestParsed,this),i.on(m.LEVEL_LOADING,this.onLevelLoading,this),i.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),i.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),i.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:i}=this;i.off(m.MANIFEST_LOADING,this.onManifestLoading,this),i.off(m.MANIFEST_PARSED,this.onManifestParsed,this),i.off(m.LEVEL_LOADING,this.onLevelLoading,this),i.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),i.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),i.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(i,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(i,e){const{id:t,groupId:s,details:r}=e,n=this.tracksInGroup[t];if(!n||n.groupId!==s)return void this.warn(`Audio track with id:${t} and group:${s} not found in active group ${n?.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${t} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),t===this.trackId&&this.playlistLoaded(t,e,a)}onLevelLoading(i,e){this.switchLevel(e.level)}onLevelSwitching(i,e){this.switchLevel(e.level)}switchLevel(i){const e=this.hls.levels[i];if(!e)return;const t=e.audioGroups||null,s=this.groupIds;let r=this.currentTrack;if(!t||s?.length!==t?.length||t!=null&&t.some(a=>s?.indexOf(a)===-1)){this.groupIds=t,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(u=>!t||t.indexOf(u.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(u=>u.default)&&(this.selectDefaultTrack=!1),a.forEach((u,c)=>{u.id=c});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.audioPreference;if(!r&&o){const u=He(o,a,ct);if(u>-1)r=a[u];else{const c=He(o,this.tracks);r=this.tracks[c]}}let h=this.findTrackId(r);h===-1&&r&&(h=this.findTrackId(null));const l={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${t?.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,l);const d=this.trackId;if(h!==-1&&d===-1)this.setAudioTrack(h);else if(a.length&&d===-1){var n;const u=new Error(`No audio track selected for current audio group-ID(s): ${(n=this.groupIds)==null?void 0:n.join(",")} track count: ${a.length}`);this.warn(u.message),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:u})}}}onError(i,e){!e.fatal&&e.context&&(e.context.type!==Be||e.context.id!==this.trackId||this.groupIds&&this.groupIds.indexOf(e.context.groupId)===-1||this.checkRetry(e))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(i){this.selectDefaultTrack=!1,this.setAudioTrack(i)}setAudioOption(i){const e=this.hls;if(e.config.audioPreference=i,i){const t=this.allAudioTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&pt(i,s,ct))return s;const r=He(i,this.tracksInGroup,ct);if(r>-1){const n=this.tracksInGroup[r];return this.setAudioTrack(r),n}if(s){let n=e.loadLevel;n===-1&&(n=e.firstAutoLevel);const a=function(o,h,l,d,u){const c=h[d],f=h.reduce((E,T,A)=>{const L=T.uri;return(E[L]||(E[L]=[])).push(A),E},{})[c.uri];f.length>1&&(d=Math.max.apply(Math,f));const g=c.videoRange,p=c.frameRate,v=c.codecSet.substring(0,4),y=Cr(h,d,E=>{if(E.videoRange!==g||E.frameRate!==p||E.codecSet.substring(0,4)!==v)return!1;const T=E.audioGroups,A=l.filter(L=>!T||T.indexOf(L.groupId)!==-1);return He(o,A,u)>-1});return y>-1?y:Cr(h,d,E=>{const T=E.audioGroups,A=l.filter(L=>!T||T.indexOf(L.groupId)!==-1);return He(o,A,u)>-1})}(i,e.levels,t,n,ct);if(a===-1)return null;e.nextLoadLevel=a}if(i.channels||i.audioCodec){const n=He(i,t);if(n>-1)return t[n]}}}return null}setAudioTrack(i){const e=this.tracksInGroup;if(i<0||i>=e.length)return void this.warn(`Invalid audio track id: ${i}`);this.selectDefaultTrack=!1;const t=this.currentTrack,s=e[i],r=s.details&&!s.details.live;if(i===this.trackId&&s===t&&r||(this.log(`Switching to audio-track ${i} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=i,this.currentTrack=s,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,re({},s)),r))return;const n=this.switchParams(s.url,t?.details,s.details);this.loadPlaylist(n)}findTrackId(i){const e=this.tracksInGroup;for(let t=0;t<e.length;t++){const s=e[t];if((!this.selectDefaultTrack||s.default)&&(!i||pt(i,s,ct)))return t}if(i){const{name:t,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=i;for(let h=0;h<e.length;h++)if(pt({name:t,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},e[h],ct))return h;for(let h=0;h<e.length;h++){const l=e[h];if(Xt(i.attrs,l.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return h}for(let h=0;h<e.length;h++){const l=e[h];if(Xt(i.attrs,l.attrs,["LANGUAGE"]))return h}}return-1}loadPlaylist(i){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&Ms(e.url,this.hls)&&this.scheduleLoading(e,i)}loadingPlaylist(i,e){super.loadingPlaylist(i,e);const t=i.id,s=i.groupId,r=this.getUrlWithDirectives(i.url,e),n=i.details,a=n?.age;this.log(`Loading audio-track ${t} "${i.name}" lang:${i.lang} group:${s}${e?.msn!==void 0?" at sn "+e.msn+" part "+e.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:r,id:t,groupId:s,deliveryDirectives:e||null,track:i})}},emeController:Ft,cmcdController:class{constructor(i){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=s=>{try{this.apply(s,{ot:be.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=s=>{try{const{frag:r,part:n}=s,a=this.hls.levels[r.level],o=this.getObjectType(r),h={d:1e3*(n||r).duration,ot:o};o!==be.VIDEO&&o!==be.AUDIO&&o!=be.MUXED||(h.br=a.bitrate/1e3,h.tb=this.getTopBandwidth(o)/1e3,h.bl=this.getBufferLength(o));const l=n?this.getNextPart(n):this.getNextFrag(r);l!=null&&l.url&&l.url!==r.url&&(h.nor=l.url),this.apply(s,h)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=i;const e=this.config=i.config,{cmcd:t}=e;t!=null&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=t.sessionId||i.sessionId,this.cid=t.contentId,this.useHeaders=t.useHeaders===!0,this.includeKeys=t.includeKeys,this.registerListeners())}registerListeners(){const i=this.hls;i.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),i.on(m.MEDIA_DETACHED,this.onMediaDetached,this),i.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const i=this.hls;i.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),i.off(m.MEDIA_DETACHED,this.onMediaDetached,this),i.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(i,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(i,e){var t,s;this.audioBuffer=(t=e.tracks.audio)==null?void 0:t.buffer,this.videoBuffer=(s=e.tracks.video)==null?void 0:s.buffer}createData(){var i;return{v:1,sf:Tl.HLS,sid:this.sid,cid:this.cid,pr:(i=this.media)==null?void 0:i.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(i,e={}){ae(e,this.createData());const t=e.ot===be.INIT||e.ot===be.VIDEO||e.ot===be.MUXED;this.starved&&t&&(e.bs=!0,e.su=!0,this.starved=!1),e.su==null&&(e.su=this.buffering);const{includeKeys:s}=this;s&&(e=Object.keys(e).reduce((n,a)=>(s.includes(a)&&(n[a]=e[a]),n),{}));const r={baseUrl:i.url};this.useHeaders?(i.headers||(i.headers={}),Fl(i.headers,e,r)):i.url=Ul(i.url,e,r)}getNextFrag(i){var e;const t=(e=this.hls.levels[i.level])==null?void 0:e.details;if(t){const s=i.sn-t.startSN;return t.fragments[s+1]}}getNextPart(i){var e;const{index:t,fragment:s}=i,r=(e=this.hls.levels[s.level])==null||(e=e.details)==null?void 0:e.partList;if(r){const{sn:n}=s;for(let a=r.length-1;a>=0;a--){const o=r[a];if(o.index===t&&o.fragment.sn===n)return r[a+1]}}}getObjectType(i){const{type:e}=i;return e==="subtitle"?be.TIMED_TEXT:i.sn==="initSegment"?be.INIT:e==="audio"?be.AUDIO:e==="main"?this.hls.audioTracks.length?be.VIDEO:be.MUXED:void 0}getTopBandwidth(i){let e,t=0;const s=this.hls;if(i===be.AUDIO)e=s.audioTracks;else{const r=s.maxAutoLevel,n=r>-1?r+1:s.levels.length;e=s.levels.slice(0,n)}return e.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(i){const e=this.media,t=i===be.AUDIO?this.audioBuffer:this.videoBuffer;return!t||!e?NaN:1e3*z.bufferInfo(t,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:i}=this.config,e=this.applyPlaylistData,t=i||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new t(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,r,n){e(s),this.loader.load(s,r,n)}}}createFragmentLoader(){const{fLoader:i}=this.config,e=this.applyFragmentData,t=i||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new t(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,r,n){e(s),this.loader.load(s,r,n)}}}},contentSteeringController:class extends Fe{constructor(i){super("content-steering",i.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=i,this.registerListeners()}registerListeners(){const i=this.hls;i.on(m.MANIFEST_LOADING,this.onManifestLoading,this),i.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),i.on(m.MANIFEST_PARSED,this.onManifestParsed,this),i.on(m.ERROR,this.onError,this)}unregisterListeners(){const i=this.hls;i&&(i.off(m.MANIFEST_LOADING,this.onManifestLoading,this),i.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),i.off(m.MANIFEST_PARSED,this.onManifestParsed,this),i.off(m.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((i,e)=>(i.indexOf(e.pathwayId)===-1&&i.push(e.pathwayId),i),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(i){this.updatePathwayPriority(i)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const i=1e3*this.timeToLoad-(performance.now()-this.updated);if(i>0)return void this.scheduleRefresh(this.uri,i)}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(i){const e=this.levels;e&&(this.levels=e.filter(t=>t!==i))}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(i,e){const{contentSteering:t}=e;t!==null&&(this.pathwayId=t.pathwayId,this.uri=t.uri,this.started&&this.startLoad())}onManifestParsed(i,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(i,e){const{errorAction:t}=e;if(t?.action===We&&t.flags===bs){const s=this.levels;let r=this._pathwayPriority,n=this.pathwayId;if(e.context){const{groupId:a,pathwayId:o,type:h}=e.context;a&&s?n=this.getPathwayForGroupId(a,h,n):o&&(n=o)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&s&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),t.resolved=this.pathwayId!==n),e.details!==I.BUFFER_APPEND_ERROR||e.fatal?t.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${n} levels: ${s&&s.length} priorities: ${oe(r)} penalized: ${oe(this.penalizedPathways)}`):t.resolved=!0}}filterParsedLevels(i){this.levels=i;let e=this.getLevelsForPathway(this.pathwayId);if(e.length===0){const t=i[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${t}"`),e=this.getLevelsForPathway(t),this.pathwayId=t}return e.length!==i.length&&this.log(`Found ${e.length}/${i.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(i){return this.levels===null?[]:this.levels.filter(e=>i===e.pathwayId)}updatePathwayPriority(i){let e;this._pathwayPriority=i;const t=this.penalizedPathways,s=performance.now();Object.keys(t).forEach(r=>{s-t[r]>3e5&&delete t[r]});for(let r=0;r<i.length;r++){const n=i[r];if(n in t)continue;if(n===this.pathwayId)return;const a=this.hls.nextLoadLevel,o=this.hls.levels[a];if(e=this.getLevelsForPathway(n),e.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,Aa(e),this.hls.trigger(m.LEVELS_UPDATED,{levels:e});const h=this.hls.levels[a];o&&h&&this.levels&&(h.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&h.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${h.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(i,e,t){const s=this.getLevelsForPathway(t).concat(this.levels||[]);for(let r=0;r<s.length;r++)if(e===Be&&s[r].hasAudioGroup(i)||e===qe&&s[r].hasSubtitleGroup(i))return s[r].pathwayId;return t}clonePathways(i){const e=this.levels;if(!e)return;const t={},s={};i.forEach(r=>{const{ID:n,"BASE-ID":a,"URI-REPLACEMENT":o}=r;if(e.some(l=>l.pathwayId===n))return;const h=this.getLevelsForPathway(a).map(l=>{const d=new ce(l.attrs);d["PATHWAY-ID"]=n;const u=d.AUDIO&&`${d.AUDIO}_clone_${n}`,c=d.SUBTITLES&&`${d.SUBTITLES}_clone_${n}`;u&&(t[d.AUDIO]=u,d.AUDIO=u),c&&(s[d.SUBTITLES]=c,d.SUBTITLES=c);const f=Za(l.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),g=new Yt({attrs:d,audioCodec:l.audioCodec,bitrate:l.bitrate,height:l.height,name:l.name,url:f,videoCodec:l.videoCodec,width:l.width});if(l.audioGroups)for(let p=1;p<l.audioGroups.length;p++)g.addGroupId("audio",`${l.audioGroups[p]}_clone_${n}`);if(l.subtitleGroups)for(let p=1;p<l.subtitleGroups.length;p++)g.addGroupId("text",`${l.subtitleGroups[p]}_clone_${n}`);return g});e.push(...h),bn(this.audioTracks,t,o,n),bn(this.subtitleTracks,s,o,n)})}loadSteeringManifest(i){const e=this.hls.config,t=e.loader;let s;this.loader&&this.loader.destroy(),this.loader=new t(e);try{s=new self.URL(i)}catch{return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${i}`)}if(s.protocol!=="data:"){const l=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+l)}const r={responseType:"json",url:s.href},n=e.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},h={onSuccess:(l,d,u,c)=>{this.log(`Loaded steering manifest: "${s}"`);const f=l.data;if(f?.VERSION!==1)return void this.log(`Steering VERSION ${f.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":v}=f;if(g)try{this.uri=new self.URL(g,s).href}catch{return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`)}this.scheduleRefresh(this.uri||u.url),p&&this.clonePathways(p);const y={steeringManifest:f,url:s.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,y),v&&this.updatePathwayPriority(v)},onError:(l,d,u,c)=>{if(this.log(`Error loading steering manifest: ${l.code} ${l.text} (${d.url})`),this.stopLoad(),l.code===410)return this.enabled=!1,void this.log(`Steering manifest ${d.url} no longer available`);let f=1e3*this.timeToLoad;if(l.code===429){const g=this.loader;if(typeof g?.getResponseHeader=="function"){const p=g.getResponseHeader("Retry-After");p&&(f=1e3*parseFloat(p))}return void this.log(`Steering manifest ${d.url} rate limited`)}this.scheduleRefresh(this.uri||d.url,f)},onTimeout:(l,d,u)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,o,h)}scheduleRefresh(i,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;const s=(t=this.hls)==null?void 0:t.media;!s||s.ended?this.scheduleRefresh(i,1e3*this.timeToLoad):this.loadSteeringManifest(i)},e)}},interstitialsController:class extends Fe{constructor(i,e){super("interstitials",i.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(t===void 0||this.playbackDisabled||!this.schedule)return;const s=t-this.timelinePos;if(Math.abs(s)<1/7056e5)return;const r=s<=-.01;this.timelinePos=t,this.bufferedPos=t;const n=this.playingItem;if(!n)return void this.checkBuffer();if(r&&this.schedule.resetErrorsInRange(t,t-s)&&this.updateSchedule(!0),this.checkBuffer(),r&&t<n.start||t>=n.end){var a;const u=this.findItemIndex(n);let c=this.schedule.findItemIndexAtTime(t);if(c===-1&&(c=u+(r?-1:1),this.log(`seeked ${r?"back ":""}to position not covered by schedule ${t} (resolving from ${u} to ${c})`)),!this.isInterstitial(n)&&(a=this.media)!=null&&a.paused&&(this.shouldPlay=!1),!r&&c>u){const f=this.schedule.findJumpRestrictedIndex(u+1,c);if(f>u)return void this.setSchedulePosition(f)}return void this.setSchedulePosition(c)}const o=this.playingAsset;if(!o){if(this.playingLastItem&&this.isInterstitial(n)){const u=n.event.assetList[0];u&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,u))}return}const h=o.timelineStart,l=o.duration||0;var d;(r&&t<h||t>=h+l)&&((d=n.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(n.event,n),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,o))},this.onTimeupdate=()=>{const t=this.currentTime;if(t===void 0||this.playbackDisabled||!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const s=this.playingItem;if(!s||this.playingLastItem)return;if(t>=s.end){this.timelinePos=s.end;const n=this.findItemIndex(s);this.setSchedulePosition(n+1)}const r=this.playingAsset;r&&t>=r.timelineStart+(r.duration||0)&&this.setScheduleToAssetAtTime(t,r)},this.onScheduleUpdate=(t,s)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,a=r.events||[],o=r.items||[],h=r.durations,l=t.map(g=>g.identifier),d=!(!a.length&&!l.length);(d||s)&&this.log(`INTERSTITIALS_UPDATED (${a.length}): ${a}
40
+ Schedule: ${o.map(g=>$e(g))} pos: ${this.timelinePos}`),l.length&&this.log(`Removed events ${l}`);let u=null,c=null;n&&(u=this.updateItem(n,this.timelinePos),this.itemsMatch(n,u)?this.playingItem=u:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f&&(c=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,c)?this.bufferingItem=c:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),t.forEach(g=>{g.assetList.forEach(p=>{this.clearAssetPlayer(p.identifier,null)})}),this.playerQueue.forEach(g=>{if(g.interstitial.appendInPlace){const p=g.assetItem.timelineStart,v=g.timelineOffset-p;if(v)try{g.timelineOffset=p}catch(y){Math.abs(v)>Nt&&this.warn(`${y} ("${g.assetId}" ${g.timelineOffset}->${p})`)}}}),d||s){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:o.slice(0),durations:h,removedIds:l}),this.isInterstitial(n)&&l.includes(n.event.identifier))return this.warn(`Interstitial "${n.event.identifier}" removed while playing`),void this.primaryFallback(n.event);n&&this.trimInPlace(u,n),f&&c!==u&&this.trimInPlace(c,f),this.checkBuffer()}},this.hls=i,this.HlsPlayerClass=e,this.assetListLoader=new Vl(i),this.schedule=new Hl(this.onScheduleUpdate,i.logger),this.registerListeners()}registerListeners(){const i=this.hls;i&&(i.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),i.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),i.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),i.on(m.MANIFEST_LOADING,this.onManifestLoading,this),i.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),i.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),i.on(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),i.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),i.on(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),i.on(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),i.on(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),i.on(m.BUFFER_APPENDED,this.onBufferAppended,this),i.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),i.on(m.BUFFERED_TO_END,this.onBufferedToEnd,this),i.on(m.MEDIA_ENDED,this.onMediaEnded,this),i.on(m.ERROR,this.onError,this),i.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){const i=this.hls;i&&(i.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),i.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),i.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),i.off(m.MANIFEST_LOADING,this.onManifestLoading,this),i.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),i.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),i.off(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),i.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),i.off(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),i.off(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),i.off(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),i.off(m.BUFFER_CODECS,this.onBufferCodecs,this),i.off(m.BUFFER_APPENDED,this.onBufferAppended,this),i.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),i.off(m.BUFFERED_TO_END,this.onBufferedToEnd,this),i.off(m.MEDIA_ENDED,this.onMediaEnded,this),i.off(m.ERROR,this.onError,this),i.off(m.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var i;(i=this.getBufferingPlayer())==null||i.resumeBuffering()}pauseBuffering(){var i;(i=this.getBufferingPlayer())==null||i.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const i=this.primaryMedia||this.media;i&&this.removeMediaListeners(i)}removeMediaListeners(i){De(i,"play",this.onPlay),De(i,"pause",this.onPause),De(i,"seeking",this.onSeeking),De(i,"timeupdate",this.onTimeupdate)}onMediaAttaching(i,e){const t=this.media=e.media;Ie(t,"seeking",this.onSeeking),Ie(t,"timeupdate",this.onTimeupdate),Ie(t,"play",this.onPlay),Ie(t,"pause",this.onPause)}onMediaAttached(i,e){const t=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,t===null)this.checkStart();else if(!s){this.clearScheduleState();const r=this.findItemIndex(t);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(i,e){const t=!!e.transferMedia,s=this.media;if(this.media=null,!t&&(s&&this.removeMediaListeners(s),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 i=this,e=()=>i.bufferingItem||i.waitingItem,t=l=>l&&i.getAssetPlayer(l.identifier),s=(l,d,u,c,f)=>{if(l){let g=l[d].start;const p=l.event;if(p){if(d==="playout"||p.timelineOccupancy!==Hs.Point){const v=t(u);v?.interstitial===p&&(g+=v.assetItem.startOffset+v[f])}}else g+=(c==="bufferedPos"?r():i[c])-l.start;return g}return 0},r=()=>{const l=i.bufferedPos;return l===Number.MAX_VALUE?n("primary"):Math.max(l,0)},n=l=>{var d,u;return(d=i.primaryDetails)!=null&&d.live?i.primaryDetails.edge:((u=i.schedule)==null?void 0:u.durations[l])||0},a=(l,d)=>{var u,c;const f=i.effectivePlayingItem;if(f!=null&&(u=f.event)!=null&&u.restrictions.skip||!i.schedule)return;i.log(`seek to ${l} "${d}"`);const g=i.effectivePlayingItem,p=i.schedule.findItemIndexAtTime(l,d),v=(c=i.schedule.items)==null?void 0:c[p],y=i.getBufferingPlayer(),E=y?.interstitial,T=E?.appendInPlace,A=g&&i.itemsMatch(g,v);if(g&&(T||A)){const L=t(i.playingAsset),b=L?.media||i.primaryMedia;if(b){const S=d==="primary"?b.currentTime:s(g,d,i.playingAsset,"timelinePos","currentTime"),k=l-S,D=(T?S:b.currentTime)+k;if(D>=0&&(!L||T||D<=L.duration))return void(b.currentTime=D)}}if(v){let L=l;if(d!=="primary"){const S=l-v[d].start;L=v.start+S}const b=!i.isInterstitial(v);if(i.isInterstitial(g)&&!g.event.appendInPlace||!b&&!v.event.appendInPlace){if(g){const S=i.findItemIndex(g);if(p>S){const D=i.schedule.findJumpRestrictedIndex(S+1,p);if(D>S)return void i.setSchedulePosition(D)}let k=0;if(b)i.timelinePos=L,i.checkBuffer();else{const D=v.event.assetList,P=l-(v[d]||v).start;for(let O=D.length;O--;){const N=D[O];if(N.duration&&P>=N.startOffset&&P<N.startOffset+N.duration){k=O;break}}}i.setSchedulePosition(p,k)}}else{const S=i.media||(T?y?.media:null);S&&(S.currentTime=L)}}},o=()=>{const l=i.effectivePlayingItem;if(i.isInterstitial(l))return l;const d=e();return i.isInterstitial(d)?d:null},h={get bufferedEnd(){const l=e(),d=i.bufferingItem;var u;return d&&d===l&&(s(d,"playout",i.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((u=i.bufferingAsset)==null?void 0:u.startOffset))||0},get currentTime(){const l=o(),d=i.effectivePlayingItem;return d&&d===l?s(d,"playout",i.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(l){const d=o(),u=i.effectivePlayingItem;u&&u===d&&a(l+u.playout.start,"playout")},get duration(){const l=o();return l?l.playout.end-l.playout.start:0},get assetPlayers(){var l;const d=(l=o())==null?void 0:l.event.assetList;return d?d.map(u=>i.getAssetPlayer(u.identifier)):[]},get playingIndex(){var l;const d=(l=o())==null?void 0:l.event;return d&&i.effectivePlayingAsset?d.findAssetIndex(i.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var l;return((l=i.schedule)==null||(l=l.events)==null?void 0:l.slice(0))||[]},get schedule(){var l;return((l=i.schedule)==null||(l=l.items)==null?void 0:l.slice(0))||[]},get interstitialPlayer(){return o()?h:null},get playerQueue(){return i.playerQueue.slice(0)},get bufferingAsset(){return i.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const l=e();return i.findItemIndex(l)},get playingAsset(){return i.effectivePlayingAsset},get playingItem(){return i.effectivePlayingItem},get playingIndex(){const l=i.effectivePlayingItem;return i.findItemIndex(l)},primary:{get bufferedEnd(){return r()},get currentTime(){const l=i.timelinePos;return l>0?l:0},set currentTime(l){a(l,"primary")},get duration(){return n("primary")},get seekableStart(){var l;return((l=i.primaryDetails)==null?void 0:l.fragmentStart)||0}},integrated:{get bufferedEnd(){return s(e(),"integrated",i.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(i.effectivePlayingItem,"integrated",i.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(l){a(l,"integrated")},get duration(){return n("integrated")},get seekableStart(){var l;return((d,u)=>{var c;if(d!==0&&u!=="primary"&&(c=i.schedule)!=null&&c.length){var f;const g=i.schedule.findItemIndexAtTime(d),p=(f=i.schedule.items)==null?void 0:f[g];if(p)return d+(p[u].start-p.start)}return d})(((l=i.primaryDetails)==null?void 0:l.fragmentStart)||0,"integrated")}},skip:()=>{const l=i.effectivePlayingItem,d=l?.event;if(d&&!d.restrictions.skip){const u=i.findItemIndex(l);if(d.appendInPlace){const c=l.playout.start+l.event.duration;a(c+.001,"playout")}else i.advanceAfterAssetEnded(d,u,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var i;const e=this.playingItem,t=(i=this.schedule)==null?void 0:i.items;return!!(this.playbackStarted&&e&&t)&&this.findItemIndex(e)===t.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var i,e;if(this.mediaSelection===null)return;const t=this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&!t.event.appendInPlace)return;let s=this.media;!s&&(i=this.bufferingItem)!=null&&(i=i.event)!=null&&i.appendInPlace&&(s=this.primaryMedia);const r=(e=s)==null?void 0:e.currentTime;return r!==void 0&&U(r)?r:void 0}get primaryMedia(){var i;return this.media||((i=this.detachedData)==null?void 0:i.media)||null}isInterstitial(i){return!(i==null||!i.event)}retreiveMediaSource(i,e){const t=this.getAssetPlayer(i);t&&this.transferMediaFromPlayer(t,e)}transferMediaFromPlayer(i,e){const t=i.interstitial.appendInPlace,s=i.media;if(t&&s===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&s)return void(this.detachedData={media:s});const r=i.transferMedia();this.log(`transfer MediaSource from ${i} ${oe(r)}`),this.detachedData=r}else e&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(i,e){var t,s;if(i.media===e)return;let r=null;const n=this.hls,a=i!==n,o=a&&i.interstitial.appendInPlace,h=(t=this.detachedData)==null?void 0:t.mediaSource;let l;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),l="Primary";else if(h){const f=this.getBufferingPlayer();f?(r=f.transferMedia(),l=`${f}`):l="detached MediaSource"}else l="detached media";if(!r){if(h)r=this.detachedData,this.log(`using detachedData: MediaSource ${oe(r)}`);else if(!this.detachedData||n.media===e){const f=this.playerQueue;f.length>1&&f.forEach(g=>{if(a&&g.interstitial.appendInPlace!==o){const p=g.interstitial;this.clearInterstitial(g.interstitial,null),p.appendInPlace=!1,p.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${p}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}}const d=r&&"mediaSource"in r&&((s=r.mediaSource)==null?void 0:s.readyState)!=="closed",u=d&&r?r:e;this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?i:"Primary"} from ${l} (media.currentTime: ${e.currentTime})`);const c=this.schedule;if(u===r&&c){const f=a&&i.assetId===c.assetIdAtEnd;u.overrides={duration:c.duration,endOfStream:!a||f,cueRemoval:!a}}i.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const i=this.schedule,e=i?.events;if(!e||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const t=this.timelinePos,s=this.effectivePlayingItem;if(t===-1){const r=this.hls.startPosition;if(this.log(ys("checkStart",r)),this.timelinePos=r,e.length&&e[0].cue.pre){const n=i.findEventIndex(e[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){const n=this.timelinePos=r>0?r:0,a=i.findItemIndexAtTime(n);this.setSchedulePosition(a)}}else if(s&&!this.playingItem){const r=i.findItemIndex(s);this.setSchedulePosition(r)}}advanceAssetBuffering(i,e){const t=i.event,s=t.findAssetIndex(e),r=oi(t,s);if(t.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const a=(n=this.schedule.items)==null?void 0:n[this.findItemIndex(i)+1];a&&this.bufferedToItem(a)}}else this.bufferedToEvent(i,r)}advanceAfterAssetEnded(i,e,t){const s=oi(i,t);if(i.isAssetPastPlayoutLimit(s)){if(this.schedule){const r=this.schedule.items;if(r){const n=e+1;if(n>=r.length)return void this.setSchedulePosition(-1);const a=i.resumeTime;this.timelinePos<a&&(this.log(ys("advanceAfterAssetEnded",a)),this.timelinePos=a,i.appendInPlace&&this.advanceInPlace(a),this.checkBuffer(this.bufferedPos<a)),this.setSchedulePosition(n)}}}else{if(i.appendInPlace){const r=i.assetList[s];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(e,s)}}setScheduleToAssetAtTime(i,e){const t=this.schedule;if(!t)return;const s=e.parentIdentifier,r=t.getEvent(s);if(r){const n=t.findEventIndex(s),a=t.findAssetIndex(r,i);this.advanceAfterAssetEnded(r,n,a-1)}}setSchedulePosition(i,e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s||this.playbackDisabled)return;const r=i>=0?s[i]:null;this.log(`setSchedulePosition ${i}, ${e} (${r&&$e(r)}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const l=n.event,d=this.playingAsset,u=d?.identifier,c=u?this.getAssetPlayer(u):null;if(c&&u&&(!this.eventItemsMatch(n,r)||e!==void 0&&u!==l.assetList[e].identifier)){var o;const f=l.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${l.assetList.length} ${Ct(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:f,event:l,schedule:s.slice(0),scheduleIndex:i,player:c}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(l,this.findItemIndex(this.playingItem),f));this.retreiveMediaSource(u,r),!c.media||(o=this.detachedData)!=null&&o.mediaSource||c.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${l} ${$e(n)}`),l.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:l,schedule:s.slice(0),scheduleIndex:i}),l.cue.once)){var h;this.updateSchedule();const f=(h=this.schedule)==null?void 0:h.items;if(r&&f){const g=this.findItemIndex(r);this.advanceSchedule(g,f,e,n,a)}return}}this.advanceSchedule(i,s,e,n,a)}advanceSchedule(i,e,t,s,r){const n=this.schedule;if(!n)return;const a=e[i]||null,o=this.primaryMedia,h=this.playerQueue;if(h.length&&h.forEach(l=>{const d=l.interstitial,u=n.findEventIndex(d.identifier);(u<i||u>i+1)&&this.clearInterstitial(d,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const l=a.event;if(t===void 0){const f=oi(l,(t=n.findAssetIndex(l,this.timelinePos))-1);if(l.isAssetPastPlayoutLimit(f)||l.appendInPlace&&this.timelinePos===a.end)return void this.advanceAfterAssetEnded(l,i,t);t=f}const d=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let u=this.preloadAssets(l,t);if(this.eventItemsMatch(a,d||s)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${$e(a)} ${l.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:l,schedule:e.slice(0),scheduleIndex:i})),!l.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${l}`);if(l.assetListLoader&&(l.assetListLoader.destroy(),l.assetListLoader=void 0),!o)return void this.log(`Waiting for attachMedia to start Interstitial ${l}`);this.waitingItem=this.endedItem=null,this.playingItem=a;const c=l.assetList[t];if(!c)return void this.advanceAfterAssetEnded(l,i,t||0);if(u||(u=this.getAssetPlayer(c.identifier)),u===null||u.destroyed){const f=l.assetList.length;this.warn(`asset ${t+1}/${f} player destroyed ${l}`),u=this.createAssetPlayer(l,c,t),u.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&l.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(u,t,e,i,o),this.shouldPlay&&Dn(u.media)}else a?(this.resumePrimary(a,i,s),this.shouldPlay&&Dn(this.hls.media)):r&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var i;return(i=this.mediaSelection)==null?void 0:i.main.details}get primaryLive(){var i;return!((i=this.primaryDetails)==null||!i.live)}resumePrimary(i,e,t){var s,r;if(this.playingItem=i,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(i),this.log(`resuming ${$e(i)}`),(s=this.detachedData)==null||!s.mediaSource){let a=this.timelinePos;(a<i.start||a>=i.end)&&(a=this.getPrimaryResumption(i,e),this.log(ys("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,i)}if(!t)return;const n=(r=this.schedule)==null?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${$e(i)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:e}),this.checkBuffer())}getPrimaryResumption(i,e){const t=i.start;if(this.primaryLive){const s=this.primaryDetails;if(e===0)return this.hls.startPosition;if(s&&(t<s.fragmentStart||t>s.edge))return this.hls.liveSyncPosition||-1}return t}isAssetBuffered(i){const e=this.getAssetPlayer(i.identifier);return e!=null&&e.hls?e.hls.bufferedToEnd:z.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=i.timelineStart+(i.duration||0)}attachPrimary(i,e,t){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,s),t&&this.startLoadingPrimaryAt(i,t)),t||(this.log(ys("attachPrimary",i)),this.timelinePos=i,this.startLoadingPrimaryAt(i,t))}startLoadingPrimaryAt(i,e){var t;const s=this.hls;!s.loadingEnabled||!s.media||Math.abs((((t=s.mainForwardBufferInfo)==null?void 0:t.start)||s.media.currentTime)-i)>.5?s.startLoad(i,e):s.bufferingEnabled||s.resumeBuffering()}onManifestLoading(){var i;this.stopLoad(),(i=this.schedule)==null||i.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(i,e){if(e.level===-1||!this.schedule)return;const t=this.hls.levels[e.level];if(!t.details)return;const s=re(re({},this.mediaSelection||this.altSelection),{},{main:t});this.mediaSelection=s,this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(i,e){const t=this.hls.audioTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=re(re({},this.altSelection),{},{audio:t}));const r=re(re({},s),{},{audio:t});this.mediaSelection=r}onSubtitleTrackUpdated(i,e){const t=this.hls.subtitleTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=re(re({},this.altSelection),{},{subtitles:t}));const r=re(re({},s),{},{subtitles:t});this.mediaSelection=r}onAudioTrackSwitching(i,e){const t=Pr(e);this.playerQueue.forEach(({hls:s})=>s&&(s.setAudioOption(e)||s.setAudioOption(t)))}onSubtitleTrackSwitch(i,e){const t=Pr(e);this.playerQueue.forEach(({hls:s})=>s&&(s.setSubtitleOption(e)||e.id!==-1&&s.setSubtitleOption(t)))}onBufferCodecs(i,e){const t=e.tracks;t&&(this.requiredTracks=t)}onBufferAppended(i,e){this.checkBuffer()}onBufferFlushed(i,e){const t=this.playingItem;if(t&&!this.itemsMatch(t,this.bufferingItem)&&!this.isInterstitial(t)){const s=this.timelinePos;this.bufferedPos=s,this.checkBuffer()}}onBufferedToEnd(i){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 r=e[s];if(r.cue.post){var t;const n=this.schedule.findEventIndex(r.identifier),a=(t=this.schedule.items)==null?void 0:t[n];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(i){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(i,e){var t;const s=(t=this.schedule)==null?void 0:t.items;return i&&s&&s[this.findItemIndex(i,e)]||null}trimInPlace(i,e){if(this.isInterstitial(i)&&i.event.appendInPlace&&e.end-i.end>.25){i.event.assetList.forEach((r,n)=>{i.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(r.identifier,null)});const t=i.end+.25,s=z.bufferInfo(this.primaryMedia,t,0);(s.end>t||(s.nextStart||0)>t)&&(this.log(`trim buffered interstitial ${$e(i)} (was ${$e(e)})`),this.attachPrimary(t,null,!0),this.flushFrontBuffer(t))}}itemsMatch(i,e){return!!e&&(i===e||i.event&&e.event&&this.eventItemsMatch(i,e)||!i.event&&!e.event&&this.findItemIndex(i)===this.findItemIndex(e))}eventItemsMatch(i,e){var t;return!!e&&(i===e||i.event.identifier===((t=e.event)==null?void 0:t.identifier))}findItemIndex(i,e){return i&&this.schedule?this.schedule.findItemIndex(i,e):-1}updateSchedule(i=!1){var e;const t=this.mediaSelection;t&&((e=this.schedule)==null||e.updateSchedule(t,[],i))}checkBuffer(i){var e;const t=(e=this.schedule)==null?void 0:e.items;if(!t)return;const s=z.bufferInfo(this.primaryMedia,this.timelinePos,0);i&&(this.bufferedPos=this.timelinePos),i||(i=s.len<1),this.updateBufferedPos(s.end,t,i)}updateBufferedPos(i,e,t){const s=this.schedule,r=this.bufferingItem;if(this.bufferedPos>i||!s)return;if(e.length===1&&this.itemsMatch(e[0],r))return void(this.bufferedPos=i);const n=this.playingItem,a=this.findItemIndex(n);let o=s.findItemIndexAtTime(i);if(this.bufferedPos<i){var h;const l=this.findItemIndex(r),d=Math.min(l+1,e.length-1),u=e[d];if((o===-1&&r&&i>=r.end||(h=u.event)!=null&&h.appendInPlace&&i+.01>=u.start)&&(o=d),this.isInterstitial(r)){const c=r.event;if(d-a>1&&c.appendInPlace===!1||c.assetList.length===0&&c.assetListLoader)return}if(this.bufferedPos=i,o>l&&o>a)this.bufferedToItem(u);else{const c=this.primaryDetails;this.primaryLive&&c&&i>c.edge-c.targetduration&&u.start<c.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(u)&&this.preloadAssets(u.event,0)}}else t&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(e[o]))}assetsBuffered(i,e){return i.event.assetList.length!==0&&!i.event.assetList.some(t=>{const s=this.getAssetPlayer(t.identifier);return!(s!=null&&s.bufferedInPlaceToEnd(e))})}setBufferingItem(i){const e=this.bufferingItem,t=this.schedule;if(!this.itemsMatch(i,e)&&t){const{items:s,events:r}=t;if(!s||!r)return e;const n=this.isInterstitial(i),a=this.getBufferingPlayer();this.bufferingItem=i,this.bufferedPos=Math.max(i.start,Math.min(i.end,this.timelinePos));const o=a?a.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${$e(i)}`+(e?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const h=t.findAssetIndex(i.event,this.bufferedPos);i.event.assetList.forEach((l,d)=>{const u=this.getAssetPlayer(l.identifier);u&&(d===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:s.slice(0),bufferingIndex:this.findItemIndex(i),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==i&&(this.bufferingItem=i);return e}bufferedToItem(i,e=0){const t=this.setBufferingItem(i);if(!this.playbackDisabled){if(this.isInterstitial(i))this.bufferedToEvent(i,e);else if(t!==null){this.bufferingAsset=null;const s=this.detachedData;s?s.mediaSource?this.attachPrimary(i.start,i,!0):this.preloadPrimary(i):this.preloadPrimary(i)}}}preloadPrimary(i){const e=this.findItemIndex(i),t=this.getPrimaryResumption(i,e);this.startLoadingPrimaryAt(t)}bufferedToEvent(i,e){const t=i.event,s=t.assetList.length===0&&!t.assetListLoader,r=t.cue.once;if(s||!r){const n=this.preloadAssets(t,e);if(n!=null&&n.interstitial.appendInPlace){const a=this.primaryMedia;a&&this.bufferAssetPlayer(n,a)}}}preloadAssets(i,e){const t=i.assetUrl,s=i.assetList.length,r=s===0&&!i.assetListLoader,n=i.cue.once;if(r){const o=i.timelineStart;if(i.appendInPlace){var a;const u=this.playingItem;this.isInterstitial(u)||(u==null||(a=u.nextEvent)==null?void 0:a.identifier)!==i.identifier||this.flushFrontBuffer(o+.25)}let h,l=0;if(!this.playingItem&&this.primaryLive&&(l=this.hls.startPosition,l===-1&&(l=this.hls.liveSyncPosition||0)),l&&!i.cue.pre&&!i.cue.post){const u=l-o;u>0&&(h=Math.round(1e3*u)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${t?1:s} ${i}${h?` live-start: ${l} start-offset: ${h}`:""}`),t)return this.createAsset(i,0,0,o,i.duration,t);const d=this.assetListLoader.loadAssetList(i,h);d&&(i.assetListLoader=d)}else if(!n&&s){for(let h=e;h<s;h++){const l=i.assetList[h],d=this.getAssetPlayerQueueIndex(l.identifier);d!==-1&&!this.playerQueue[d].destroyed||l.error||this.createAssetPlayer(i,l,h)}const o=i.assetList[e];if(o){const h=this.getAssetPlayer(o.identifier);return h&&h.loadSource(),h}}return null}flushFrontBuffer(i){const e=this.requiredTracks;e&&(this.log(`Removing front buffer starting at ${i}`),Object.keys(e).forEach(t=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:i,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(i){const e=this.playerQueue;for(let t=0;t<e.length;t++)if(i===e[t].assetId)return t;return-1}getAssetPlayer(i){const e=this.getAssetPlayerQueueIndex(i);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:i,primaryMedia:e}=this;if(e){for(let t=0;t<i.length;t++)if(i[t].media===e)return i[t]}return null}createAsset(i,e,t,s,r,n){const a={parentIdentifier:i.identifier,identifier:Bl(i,n,e),duration:r,startOffset:t,timelineStart:s,uri:n};return this.createAssetPlayer(i,a,e)}createAssetPlayer(i,e,t){const s=this.hls,r=s.userConfig;let n=r.videoPreference;const a=s.loadLevelObj||s.levels[s.currentLevel];(n||a)&&(n=ae({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=s.audioTracks[s.audioTrack],h=s.subtitleTracks[s.subtitleTrack];let l=0;if(this.primaryLive||i.appendInPlace){const E=this.timelinePos-e.timelineStart;if(E>1){const T=e.duration;T&&E<T&&(l=E)}}const d=e.identifier,u=re(re({},r),{},{maxMaxBufferLength:Math.min(180,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:l,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:h||r.subtitlePreference});i.appendInPlace&&(i.appendInPlaceStarted=!0,e.timelineStart&&(u.timelineOffset=e.timelineStart));const c=u.cmcd;c!=null&&c.sessionId&&c.contentId&&(u.cmcd=ae({},c,{contentId:es(e.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${i} and asset ${d}`);const f=new Kl(this.HlsPlayerClass,u,i,e);this.playerQueue.push(f),i.assetList[t]=e;let g=!0;const p=E=>{if(E.live){var T;const b=new Error(`Interstitials MUST be VOD assets ${i}`),S={fatal:!0,type:H.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:b},k=((T=this.schedule)==null?void 0:T.findEventIndex(i.identifier))||-1;return void this.handleAssetItemError(S,i,k,t,b.message)}const A=E.edge-E.fragmentStart,L=e.duration;(g||L===null||A>L)&&(g=!1,this.log(`Interstitial asset "${d}" duration change ${L} > ${A}`),e.duration=A,this.updateSchedule())};f.on(m.LEVEL_UPDATED,(E,{details:T})=>p(T)),f.on(m.LEVEL_PTS_UPDATED,(E,{details:T})=>p(T)),f.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(E,T)=>{const A=this.getAssetPlayer(d);if(A&&T.tracks){A.off(m.BUFFER_CODECS,v),A.tracks=T.tracks;const L=this.primaryMedia;this.bufferingAsset===A.assetItem&&L&&!A.media&&this.bufferAssetPlayer(A,L)}};f.on(m.BUFFER_CODECS,v),f.on(m.BUFFERED_TO_END,()=>{var E;const T=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${T}`),!T||!this.schedule)return;const A=this.schedule.findEventIndex(i.identifier),L=(E=this.schedule.items)==null?void 0:E[A];this.isInterstitial(L)&&this.advanceAssetBuffering(L,e)});const y=E=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const T=this.schedule.findEventIndex(i.identifier);this.advanceAfterAssetEnded(i,T,E)};return f.once(m.MEDIA_ENDED,y(t)),f.once(m.PLAYOUT_LIMIT_REACHED,y(1/0)),f.on(m.ERROR,(E,T)=>{if(!this.schedule)return;const A=this.getAssetPlayer(d);if(T.details===I.BUFFER_STALLED_ERROR)return A!=null&&A.appendInPlace?void this.handleInPlaceStall(i):(this.onTimeupdate(),void this.checkBuffer(!0));this.handleAssetItemError(T,i,this.schedule.findEventIndex(i.identifier),t,`Asset player error ${T.error} ${i}`)}),f.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const E=new Error(`Asset player destroyed unexpectedly ${d}`),T={fatal:!0,type:H.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:E};this.handleAssetItemError(T,i,this.schedule.findEventIndex(i.identifier),t,E.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Ct(e)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:t,event:i,player:f}),f}clearInterstitial(i,e){this.clearAssetPlayers(i,e),i.reset()}clearAssetPlayers(i,e){i.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)})}resetAssetPlayer(i){const e=this.getAssetPlayerQueueIndex(i);if(e!==-1){this.log(`reset asset player "${i}" after error`);const t=this.playerQueue[e];this.transferMediaFromPlayer(t,null),t.resetDetails()}}clearAssetPlayer(i,e){const t=this.getAssetPlayerQueueIndex(i);if(t!==-1){const s=this.playerQueue[t];this.log(`clear ${s} toSegment: ${e&&$e(e)}`),this.transferMediaFromPlayer(s,e),this.playerQueue.splice(t,1),s.destroy()}}emptyPlayerQueue(){let i;for(;i=this.playerQueue.pop();)i.destroy();this.playerQueue=[]}startAssetPlayer(i,e,t,s,r){const{interstitial:n,assetItem:a,assetId:o}=i,h=n.assetList.length,l=this.playingAsset;this.endedAsset=null,this.playingAsset=a,l&&l.identifier===o||(l&&(this.clearAssetPlayer(l.identifier,t[s]),delete l.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${h} ${Ct(a)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:e,event:n,schedule:t.slice(0),scheduleIndex:s,player:i})),this.bufferAssetPlayer(i,r)}bufferAssetPlayer(i,e){var t,s;if(!this.schedule)return;const{interstitial:r,assetItem:n}=i,a=this.schedule.findEventIndex(r.identifier),o=(t=this.schedule.items)==null?void 0:t[a];if(!o)return;i.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const h=this.getBufferingPlayer();if(h===i)return;const l=r.appendInPlace;if(l&&h?.interstitial.appendInPlace===!1)return;const d=h?.tracks||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(l&&n!==this.playingAsset){if(!i.tracks)return void this.log(`Waiting for track info before buffering ${i}`);if(d&&!ur(d,i.tracks)){const u=new Error(`Asset ${Ct(n)} SourceBuffer tracks ('${Object.keys(i.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),c={fatal:!0,type:H.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},f=r.findAssetIndex(n);return void this.handleAssetItemError(c,r,a,f,u.message)}}this.transferMediaTo(i,e)}handleInPlaceStall(i){const e=this.schedule,t=this.primaryMedia;if(!e||!t)return;const s=t.currentTime,r=e.findAssetIndex(i,s),n=i.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||s-n.timelineStart,h=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+h} in ${a} ${i} (media.currentTime: ${s})`),o&&(h/t.playbackRate<.5||a.bufferedInPlaceToEnd(t))&&a.hls){const l=e.findEventIndex(i.identifier);this.advanceAfterAssetEnded(i,l,r)}}}}advanceInPlace(i){const e=this.primaryMedia;e&&e.currentTime<i&&(e.currentTime=i)}handleAssetItemError(i,e,t,s,r){if(i.details===I.BUFFER_STALLED_ERROR)return;const n=e.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n&&Ct(n)} ${i.error}`),!this.schedule)return;const a=n?.identifier||"",o=this.getAssetPlayerQueueIndex(a),h=this.playerQueue[o]||null,l=this.schedule.items,d=ae({},i,{fatal:!1,errorAction:Lt(!0),asset:n,assetListIndex:s,event:e,schedule:l,scheduleIndex:t,player:h});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,d),!i.fatal)return;const u=this.playingAsset,c=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),e.assetList.some(g=>!g.error))for(let g=s;g<e.assetList.length;g++)this.resetAssetPlayer(e.assetList[g].identifier);else e.error=f;this.updateSchedule(!0),e.error?this.primaryFallback(e):u&&u.identifier===a?this.advanceAfterAssetEnded(e,t,s):c&&c.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,c)}primaryFallback(i){const e=i.timelineStart,t=this.effectivePlayingItem;let s=this.timelinePos;if(t){this.log(`Fallback to primary from event "${i.identifier}" start: ${e} pos: ${s} playing: ${$e(t)} error: ${i.error}`),s===-1&&(s=this.hls.startPosition);const n=this.updateItem(t,s);this.itemsMatch(t,n)&&this.clearInterstitial(i,null),i.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(s===-1)return void this.checkStart();if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(s);this.setSchedulePosition(r)}onAssetListLoaded(i,e){var t,s;const r=e.event,n=r.identifier,a=e.assetListResponse.ASSETS;if((t=this.schedule)==null||!t.hasEvent(n))return;const o=r.timelineStart,h=r.duration;let l=0;a.forEach((g,p)=>{const v=parseFloat(g.DURATION);this.createAsset(r,p,l,o+l,v,g.URI),l+=v}),r.duration=l,this.log(`Loaded asset-list with duration: ${l} (was: ${h}) ${r}`);const d=this.waitingItem,u=d?.event.identifier===n;this.updateSchedule();const c=(s=this.bufferingItem)==null?void 0:s.event;if(u){var f;const g=this.schedule.findEventIndex(n),p=(f=this.schedule.items)==null?void 0:f[g];if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r);this.setBufferingItem(p)}this.setSchedulePosition(g)}else if(c?.identifier===n){const g=r.assetList[0];if(g){const p=this.getAssetPlayer(g.identifier);if(c.appendInPlace){const v=this.primaryMedia;p&&v&&this.bufferAssetPlayer(p,v)}else p&&p.loadSource()}}}onError(i,e){if(this.schedule)switch(e.details){case I.ASSET_LIST_PARSING_ERROR:case I.ASSET_LIST_LOAD_ERROR:case I.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case I.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function Bi(i){return i&&typeof i=="object"?Array.isArray(i)?i.map(Bi):Object.keys(i).reduce((e,t)=>(e[t]=Bi(i[t]),e),{}):i}function vh(i,e){const t=i.loader;t!==Nn&&t!==ho?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),i.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}()&&(i.loader=Nn,i.progressive=!0,i.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}class yh extends da{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var s;this.hls&&(this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;const s=this.media=t.media;Ie(s,"playing",this.onMediaPlaying),Ie(s,"waiting",this.onMediaWaiting),Ie(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(De(s,"playing",this.onMediaPlaying),De(s,"waiting",this.onMediaWaiting),De(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if((e=this.media)==null||!e.readyState||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,r;const n=(s=this.hls)==null?void 0:s.config;if(!n)return;const a=this.media;if(!a)return;const{seeking:o}=a,h=this.seeking&&!o,l=!this.seeking&&o,d=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t)return t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),void(this.waiting===0&&this.stallResolved(e));if(l||h)return void(h&&this.stallResolved(e));if(d)return this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1})));if(!z.getBuffered(a).length)return void(this.nudgeRetry=0);const u=z.bufferInfo(a,e,0),c=u.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const b=Un(this.hls.inFlightFragments,e),S=u.len>2,k=!c||b||c-e>2&&!f.getPartialFragment(e);if(S||k)return;this.moved=!1}const g=(r=this.hls)==null?void 0:r.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(u.len>0)&&!c)return;const b=Math.max(c,u.start||0)-e,S=g==null||!g.live?2:2*g.targetduration,k=Ls(e,f);if(b>0&&(b<=S||k))return void(a.paused||this._trySkipBufferHole(k))}const p=n.detectStallWithCurrentTimeMs,v=self.performance.now(),y=this.waiting;let E=this.stalled;if(E===null){if(!(y>0&&v-y<p))return void(this.stalled=v);E=this.stalled=y}const T=v-E;if(!o&&(T>=p||y)&&this.hls){var A;if(((A=this.mediaSource)==null?void 0:A.readyState)==="ended"&&(g==null||!g.live)&&Math.abs(e-(g?.edge||0))<1)return this.ended?void 0:(this.ended=e||1,void this.hls.trigger(m.MEDIA_ENDED,{stalled:!0}));if(this._reportStall(u),!this.media||!this.hls)return}const L=z.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(L,T,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&r&&r.length>1&&e>r.end(0)){const n=z.bufferedInfo(z.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){const a=z.timeRangesToArray(r),o=z.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const h=z.bufferedInfo(a,e,0).bufferedIndex,l=a[o].end,d=a[o+1].start;if((h===-1||h>o)&&d-l<1&&e-l<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${d} buffered index: ${h}`);this.warn(u.message),this.media.currentTime+=1e-6;let c=Ls(e,this.fragmentTracker);c&&"fragment"in c?c=c.fragment:c||(c=void 0);const f=z.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:c,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var r,n;const{fragmentTracker:a,media:o}=this,h=(r=this.hls)==null?void 0:r.config;if(!o||!a||!h)return;const l=(n=this.hls)==null?void 0:n.latestLevelDetails,d=Ls(s,a);if((d||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(d)||!this.media))return;const u=e.buffered,c=this.adjacentTraversal(e,s);(u&&u.length>1&&e.len>h.maxBufferHole||e.nextStart&&(e.nextStart-s<h.maxBufferHole||c))&&(t>1e3*h.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,r=e.nextStart;if(s&&r){const n=s.getFragAtPos(t,Z),a=s.getFragAtPos(r,Z);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:r,stalled:n}=this;if(!r&&n!==null&&s&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${oe(e)})`);this.warn(a.message),t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:r}=this,n=(t=this.hls)==null?void 0:t.config;if(!r||!s||!n)return 0;const a=r.currentTime,o=z.bufferInfo(r,a,0),h=a<o.start?o.start:o.nextStart;if(h&&this.hls){const d=o.len<=n.maxBufferHole,u=o.len>0&&o.len<1&&r.readyState<3,c=h-a;if(c>0&&(d||u)){if(c>n.maxBufferHole){let g=!1;if(a===0){const p=s.getAppendedFrag(0,Z);p&&h<p.end&&(g=!0)}if(!g&&e){var l;if((l=this.hls.loadLevelObj)==null||!l.details||Un(this.hls.inFlightFragments,h))return 0;let p=!1,v=e.end;for(;v<h;){const y=Ls(v,s);if(!y){p=!0;break}v+=y.duration}if(p)return 0}}const f=Math.max(h+.05,a+.1);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,r.currentTime=f,e==null||!e.gap){const g=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:H.MEDIA_ERROR,details:I.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(m.ERROR,p)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:r}=this,n=t?.config;if(!s||!n)return 0;const a=s.currentTime;if(this.nudgeRetry++,r<n.nudgeMaxRetry){const o=a+(r+1)*n.nudgeOffset,h=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(h.message),s.currentTime=o,t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.BUFFER_NUDGE_ON_STALL,error:h,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function Un(i,e){const t=$n(i.main);if(t&&t.start<=e)return t;const s=$n(i.audio);return s&&s.start<=e?s:null}function $n(i){if(!i)return null;switch(i.state){case J:case ye:case $t:case it:return null}return i.frag}function Ls(i,e){return e.getAppendedFrag(i,Z)||e.getPartialFragment(i)}function Gi(){if(typeof self<"u")return self.VTTCue||self.TextTrackCue}function gi(i,e,t,s,r){let n=new i(e,t,"");try{n.value=s,r&&(n.type=r)}catch{n=new i(e,t,oe(r?re({type:r},s):s))}return n}const As=(()=>{const i=Gi();try{i&&new i(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Eh{constructor(e){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=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.removeCues&&Pt(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return Ja(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:r}=this.hls.config;if(!s&&!r)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=Gi();if(a)for(let o=0;o<n.length;o++){const h=n[o].type;if(h===xe.emsg&&!s||!r)continue;const l=xa(n[o].data),d=n[o].pts;let u=d+n[o].duration;u>As&&(u=As),u-d<=0&&(u=d+.25);for(let c=0;c<l.length;c++){const f=l[c];if(!Oa(f)){this.updateId3CueEnds(d,h);const g=gi(a,d,u,f,h);g&&this.id3Track.addCue(g)}}}}updateId3CueEnds(e,t){var s;const r=(s=this.id3Track)==null?void 0:s.cues;if(r)for(let n=r.length;n--;){const a=r[n];a.type===t&&a.startTime<e&&a.endTime===As&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:r}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:h}}=a;if(n&&(o||h)){let l;l=r==="audio"?d=>d.type===xe.audioId3&&h:r==="video"?d=>d.type===xe.emsg&&o:d=>d.type===xe.audioId3&&h||d.type===xe.emsg&&o,Ui(n,t,s,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=Gi();if(s&&r&&!a){const{fragmentStart:p,fragmentEnd:v}=e;let y=this.assetCue;y?(y.startTime=p,y.endTime=v):o&&(y=this.assetCue=gi(o,p,v,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),y&&(y.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(y),y.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:h}=this,{dateRanges:l}=e,d=Object.keys(l);let u=this.dateRangeCuesAppended;var c;if(h&&t)if((c=h.cues)!=null&&c.length){const p=Object.keys(u).filter(v=>!d.includes(v));for(let v=p.length;v--;){var f;const y=p[v],E=(f=u[y])==null?void 0:f.cues;delete u[y],E&&Object.keys(E).forEach(T=>{const A=E[T];if(A){A.removeEventListener("enter",this.onEventCueEnter);try{h.removeCue(A)}catch{}}})}}else u=this.dateRangeCuesAppended={};const g=e.fragments[e.fragments.length-1];if(d.length!==0&&U(g?.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<d.length;p++){const v=d[p],y=l[v],E=y.startTime,T=u[v],A=T?.cues||{};let L=T?.durationKnown||!1,b=As;const{duration:S,endDate:k}=y;if(k&&S!==null)b=E+S,L=!0;else if(y.endOnNext&&!L){const P=d.reduce((O,N)=>{if(N!==y.id){const B=l[N];if(B.class===y.class&&B.startDate>y.startDate&&(!O||y.startDate<O.startDate))return B}return O},null);P&&(b=P.startTime,L=!0)}const D=Object.keys(y.attr);for(let P=0;P<D.length;P++){const O=D[P];if(!Ko(O))continue;const N=A[O];if(N)!L||T!=null&&T.durationKnown?Math.abs(N.startTime-E)>.01&&(N.startTime=E,N.endTime=b):N.endTime=b;else if(o){let B=y.attr[O];Ho(O)&&(B=Hn(B));const F=gi(o,E,b,{key:O,data:B},xe.dateRange);F&&(F.id=v,this.id3Track.addCue(F),A[O]=F,a&&(O!=="X-ASSET-LIST"&&O!=="X-ASSET-URL"||F.addEventListener("enter",this.onEventCueEnter)))}}u[v]={cues:A,dateRange:y,durationKnown:L}}}}}class Th{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const r=this.computeLatency();if(r===null)return;this._latency=r;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const h=r-o;if(h<Math.min(this.maxLatency,o+s.targetduration)&&h>.05&&this.forwardBufferLength>1){const l=Math.min(2,Math.max(1,a)),d=Math.round(2/(1+Math.exp(-.75*h-this.edgeStalled))*20)/20,u=Math.min(l,Math.max(1,d));this.changeMediaPlaybackRate(t,u)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:r}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,h=this.hls.userConfig;let l=o&&s||t;(this._targetLatencyUpdated||h.liveSyncDuration||h.liveSyncDurationCount||l===0)&&(l=n!==void 0?n:a*r);const d=r;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const s=this.levelDetails;if(s===null)return null;const r=s.edge,n=e-t-this.edgeStalled,a=r-s.totalduration,o=r-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,n),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===I.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(e,t){var s,r;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(r=this.targetLatency)==null?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class Sh extends wi{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,r=[],n={},a={};let o=!1,h=!1,l=!1;t.levels.forEach(d=>{const u=d.attrs;let{audioCodec:c,videoCodec:f}=d;c&&(d.audioCodec=c=Os(c,s)||void 0),f&&(f=d.videoCodec=function(D){const P=D.split(",");for(let O=0;O<P.length;O++){const N=P[O].split(".");N.length>2&&N[0]==="avc1"&&(P[O]=`avc1.${parseInt(N[1]).toString(16)}${("000"+parseInt(N[2]).toString(16)).slice(-4)}`)}return P.join(",")}(f));const{width:g,height:p,unknownCodecs:v}=d,y=v?.length||0;if(o||(o=!(!g||!p)),h||(h=!!f),l||(l=!!c),y||c&&!this.isAudioSupported(c)||f&&!this.isVideoSupported(f))return void this.log(`Some or all CODECS not supported "${u.CODECS}"`);const{CODECS:E,"FRAME-RATE":T,"HDCP-LEVEL":A,"PATHWAY-ID":L,RESOLUTION:b,"VIDEO-RANGE":S}=u,k=`${`${L||"."}-`}${d.bitrate}-${b}-${T}-${E}-${S}-${A}`;if(n[k])if(n[k].uri===d.url||d.attrs["PATHWAY-ID"])n[k].addGroupId("audio",u.AUDIO),n[k].addGroupId("text",u.SUBTITLES);else{const D=a[k]+=1;d.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const P=this.createLevel(d);n[k]=P,r.push(P)}else{const D=this.createLevel(d);n[k]=D,a[k]=1,r.push(D)}}),this.filterAndSortMediaOptions(r,t,o,h,l)}createLevel(e){const t=new Yt(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const r=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(r.message),t.supportedResult=ea(r,[])}return t}isAudioSupported(e){return ts(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return ts(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,r,n){var a;let o=[],h=[],l=e;const d=((a=t.stats)==null?void 0:a.parsing)||{};if((s||r)&&n&&(l=l.filter(({videoCodec:E,videoRange:T,width:A,height:L})=>{return(!!E||!(!A||!L))&&!!(b=T)&&Is.indexOf(b)>-1;var b})),l.length===0)return Promise.resolve().then(()=>{if(this.hls){let E="no level with compatible codecs found in manifest",T=E;t.levels.length&&(T=`one or more CODECS in variant not supported: ${oe(t.levels.map(L=>L.attrs.CODECS).filter((L,b,S)=>S.indexOf(L)===b))}`,this.warn(T),E+=` (${T})`);const A=new Error(E);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:I.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:A,reason:T})}}),void(d.end=performance.now());t.audioTracks&&(o=t.audioTracks.filter(E=>!E.audioCodec||this.isAudioSupported(E.audioCodec)),Bn(o)),t.subtitles&&(h=t.subtitles,Bn(h));const u=l.slice(0);l.sort((E,T)=>{if(E.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(E.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&E.height!==T.height)return E.height-T.height;if(E.frameRate!==T.frameRate)return E.frameRate-T.frameRate;if(E.videoRange!==T.videoRange)return Is.indexOf(E.videoRange)-Is.indexOf(T.videoRange);if(E.videoCodec!==T.videoCodec){const A=Lr(E.videoCodec),L=Lr(T.videoCodec);if(A!==L)return L-A}if(E.uri===T.uri&&E.codecSet!==T.codecSet){const A=xs(E.codecSet),L=xs(T.codecSet);if(A!==L)return L-A}return E.averageBitrate!==T.averageBitrate?E.averageBitrate-T.averageBitrate:0});let c=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==u.length)){for(let E=0;E<u.length;E++)if(u[E].pathwayId===l[0].pathwayId){c=u[E];break}}this._levels=l;for(let E=0;E<l.length;E++)if(l[E]===c){var f;this._firstLevel=E;const T=c.bitrate,A=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${T}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const L=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);L>A&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=L)}break}const g=n&&!r,p=this.hls.config,v=!(!p.audioStreamController||!p.audioTrackController),y={levels:l,audioTracks:o,subtitleTracks:h,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:r,altAudio:v&&!g&&o.some(E=>!!E.url)};d.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,y)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const d=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:I.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:d,reason:d.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,r=this.currentLevel,n=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&r&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${n?" with Pathway "+n:""}`);const h={level:e,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,h);const l=a.details;if(!l||l.live){const d=this.switchParams(a.uri,r?.details,l);this.loadPlaylist(d)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(r=>t.indexOf(r)!==-1);if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=s}}onError(e,t){!t.fatal&&t.context&&t.context.type===et&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===Z){const s=t.elementaryStreams;if(!Object.keys(s).some(n=>!!s[n]))return;const r=this._levels[t.level];r!=null&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(e,t){var s;const{level:r,details:n}=t,a=t.levelInfo;var o;if(!a)return this.warn(`Invalid level index ${r}`),void((o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0));if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let h=a.details;h===t.details&&h.advanced&&(h=void 0),this.playlistLoaded(r,t,h)}else(s=t.deliveryDirectives)!=null&&s.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((n,a)=>a!==e||(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));Aa(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const r=s.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(m.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Bn(i){const e={};i.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function uo(){return self.SourceBuffer||self.WebKitSourceBuffer}function Gn(){if(!ut())return!1;const i=uo();return!i||i.prototype&&typeof i.prototype.appendBuffer=="function"&&typeof i.prototype.remove=="function"}class Lh extends Di{constructor(e,t,s){super(e,t,s,"stream-controller",Z),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const r=this.media,n=r?r.currentTime:null;if(n===null||!U(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;const a=this.getFwdBufferInfoAtPos(r,n,Z,0);a!==null&&a.len!==0?this.tick():this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let n=r.startLevel;n===-1&&(r.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=r.firstAutoLevel),r.nextLoadLevel=n,this.level=r.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=J,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=ye}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case vt:{const{levels:e,level:t}=this,s=e?.[t],r=s?.details;if(r&&(!r.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(r))break;this.state=J;break}if(this.hls.nextLoadLevel!==this.level){this.state=J;break}break}case Mt:this.checkRetryDate()}this.state===J&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=this.buffering?e.nextLoadLevel:e.loadLevel;if(s==null||!s[n])return;const a=s[n],o=this.getMainFwdBufferInfo();if(o===null)return;const h=this.getLevelDetails();if(h&&this._streamEnded(o,h)){const p={};return this.altAudio===2&&(p.type="video"),this.hls.trigger(m.BUFFER_EOS,p),void(this.state=$t)}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const l=a.details;if(!l||this.state===vt||this.waitForLive(a))return this.level=n,this.state=vt,void(this.startFragRequested=!1);const d=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(d>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(c,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&ve(f)&&this.fragmentTracker.getState(f)!==wt){var g;const p=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,v=l.fragments[p-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){const p=this.audioOnly&&!this.altAudio?Oe:Ge,v=(p===Ge?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,p,Z)}f=this.getNextFragmentLoopLoading(f,l,o,Z,u)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,a,c))}loadFragment(e,t,s){const r=this.fragmentTracker.getState(e);r===zt||r===_t?ve(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Z)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);const n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<2*n.targetduration)return}if(!t.paused&&e){const o=e[this.hls.nextLoadLevel],h=this.fragLastKbps;s=h&&this.fragCurrent?this.fragCurrent.duration*o.maxBitrate/(1e3*h)+1:0}else s=0;const a=this.getBufferedFrag(t.currentTime+s);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const h=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,d=Math.max(a.end,h+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case ki:case Ot:case Mt:case rt:case Gs:this.state=J}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;Ie(s,"playing",this.onMediaPlaying),Ie(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(De(s,"playing",this.onMediaPlaying),De(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,r=!1;for(let n=0;n<t.levels.length;n++){const a=t.levels[n].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,r=r||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&r&&!function(){var n;const a=uo();return typeof(a==null||(n=a.prototype)==null?void 0:n.changeType)=="function"}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==J)return;const r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=vt)}onLevelLoaded(e,t){var s;const{levels:r,startFragRequested:n}=this,a=t.level,o=t.details,h=o.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${a}`);this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${h}`);const l=t.levelInfo,d=this.fragCurrent;!d||this.state!==Ot&&this.state!==Mt||d.level!==t.level&&d.loader&&this.abortCurrentFrag();let u=0;if(o.live||(s=l.details)!=null&&s.live){var c;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,l.details,(c=this.levelLastLoaded)==null?void 0:c.details)}if(l.details=o,this.levelLastLoaded=l,n||this.setStartPosition(o,u),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:a}),this.state===vt){if(this.waitForCdnTuneIn(o))return;this.state=J}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const r=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,h=n>=a-t.maxFragLookUpTolerance&&n<=o;if(r!==null&&s.duration>r&&(n<r||!h)){const d=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!h&&s.readyState<4||n<o-d)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),s.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const u=z.bufferInfo(s,r,0);if((l=u.buffered)==null||!l.length||u.start<=n)return void(s.currentTime=r);const{nextStart:c}=z.bufferedInfo(u.buffered,n,0);c&&(s.currentTime=c)}else s.currentTime=r}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:r,payload:n}=e,{levels:a}=this;if(!a)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const o=a[s.level];if(!o)return void this.warn(`Level ${s.level} not found on progress`);const h=o.details;if(!h)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=o.videoCodec,d=h.PTSKnown||!h.live,u=(t=s.initSegment)==null?void 0:t.data,c=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new Ha(this.hls,Z,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=r?r.index:-1,p=g!==-1,v=new zi(s.level,s.sn,s.stats.chunkCount,n.byteLength,g,p),y=this.initPTS[s.cc];f.push(n,u,c,l,s,r,h.totalduration,d,v,y)}onAudioTrackSwitching(e,t){const s=this.hls,r=this.altAudio!==0;if(Ms(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),void s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Ms(t.url,this.hls);if(s){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let r,n,a=!1;for(const o in s){const h=s[o];if(h.id==="main"){if(n=o,r=h,o==="video"){const l=s[o];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:r}=t,n=s.type===Z;if(n){if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Gs&&(this.state=J));const o=r?r.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),ve(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,r)}const a=this.media;a&&(!this._hasEnoughToStart&&z.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal)this.state=it;else switch(t.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Z,t);break;case I.LEVEL_LOAD_ERROR:case I.LEVEL_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==vt||((s=t.context)==null?void 0:s.type)!==et||(this.state=J);break;case I.BUFFER_ADD_CODEC_ERROR:case I.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case I.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case I.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=J,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Oe||!this.altAudio){const s=(t===Ge?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,Z),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking)return void this.log(`could not seek to ${s}, already seeking at ${t}`);const r=this.timelineOffset;r&&s&&(s+=r);const n=this.getLevelDetails(),a=z.getBuffered(e),o=a.length?a.start(0):0,h=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||h>0&&(h<l||this.loadingParts&&h<2*(n?.partTarget||0)))&&(this.log(`adjusting start position by ${h} to match buffer start`),s+=h,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=t.indexOf("mp4a.40.5")!==-1?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:r}=this,n=s?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=J,this.startFragRequested=!1,this.bitrateTest=!1;const a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),r.trigger(m.FRAG_LOADED,s),n.bitrateTest=!1}).catch(s=>{this.state!==ye&&this.state!==it&&(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:h,level:l}=a,{video:d,text:u,id3:c,initSegment:f}=r,{details:g}=l,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=rt,f){const v=f.tracks;if(v){const A=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(l,v,A,n),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:t,tracks:v})}const y=f.initPTS,E=f.timescale,T=this.initPTS[o.cc];if(U(y)&&(!T||T.baseTime!==y||T.timescale!==E)){const A=f.trackId;this.initPTS[o.cc]={baseTime:y,timescale:E,trackId:A},s.trigger(m.INIT_PTS_FOUND,{frag:o,id:t,initPTS:y,timescale:E,trackId:A})}}if(d&&g){p&&d.type==="audiovideo"&&this.logMuxedErr(o);const v=g.fragments[o.sn-1-g.startSN],y=o.sn===g.startSN,E=!v||o.cc>v.cc;if(r.independent!==!1){const{startPTS:T,endPTS:A,startDTS:L,endDTS:b}=d;if(h)h.elementaryStreams[d.type]={startPTS:T,endPTS:A,startDTS:L,endDTS:b};else if(d.firstKeyFrame&&d.independent&&n.id===1&&!E&&(this.couldBacktrack=!0),d.dropped&&d.independent){const S=this.getMainFwdBufferInfo(),k=(S?S.end:this.getLoadPosition())+this.config.maxBufferHole,D=d.firstKeyFramePTS?d.firstKeyFramePTS:T;if(!y&&k<D-this.config.maxBufferHole&&!E)return void this.backtrack(o);E&&(o.gap=!0),o.setElementaryStreamInfo(d.type,o.start,A,o.start,b,!0)}else y&&T-(g.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(d.type,T,A,L,b),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(d,o,h,n,y||E)}else{if(!y&&!E)return void this.backtrack(o);o.gap=!0}}if(p){const{startPTS:v,endPTS:y,startDTS:E,endDTS:T}=p;h&&(h.elementaryStreams[Oe]={startPTS:v,endPTS:y,startDTS:E,endDTS:T}),o.setElementaryStreamInfo(Oe,v,y,E,T),this.bufferFragmentData(p,o,h,n)}if(g&&c!=null&&c.samples.length){const v={id:t,frag:o,details:g,samples:c.samples};s.trigger(m.FRAG_PARSING_METADATA,v)}if(g&&u){const v={id:t,frag:o,details:g,samples:u.samples};s.trigger(m.FRAG_PARSING_USERDATA,v)}}}logMuxedErr(e){this.warn(`${ve(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,r){if(this.state!==rt)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:n,video:a,audiovideo:o}=t;if(n){const l=e.audioCodec;let d=Rs(n.codec,l);d==="mp4a"&&(d="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){d&&(d=d.indexOf("mp4a.40.5")!==-1?"mp4a.40.2":"mp4a.40.5");const c=n.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(d="mp4a.40.5")}d&&d.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(d="mp4a.40.2",this.log(`Android: force audio codec to ${d}`)),l&&l!==d&&this.log(`Swapping manifest audio codec "${l}" for "${d}"`),n.levelCodec=d,n.id=Z,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${d||""}/${l||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=Z;const l=a.codec;if(l?.length===4)switch(l){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e"}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${a.codec!==l?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const h=Object.keys(t);if(h.length){if(this.hls.trigger(m.BUFFER_CODECS,t),!this.hls)return;h.forEach(l=>{const d=t[l].initSegment;d!=null&&d.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:d,frag:s,part:null,chunkMeta:r,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Z)}get maxBufferLength(){const{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=J}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(z.isBuffered(e,s)?t=this.getAppendedFrag(s):z.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const r=this.fragPlaying,n=t.level;r&&t.sn===r.sn&&r.level===n||(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),r&&r.level===n||this.hls.trigger(m.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return U(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(U(t)){const s=this.getLevelDetails(),r=this.currentFrag||(s?Et(null,s.fragments,t):null);if(r){const n=r.programDateTime;if(n!==null){const a=n+1e3*(t-r.start);return new Date(a)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class Ah extends Fe{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const r=this.keyIdToKeyInfo[s].loader;if(r){var t;if(e&&e!==((t=r.context)==null?void 0:t.frag.type))return;r.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=I.KEY_LOAD_ERROR,s,r,n){return new tt({type:H.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:s,networkDetails:r})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,n=t.length;r<n;r++){const a=t[r];if(e.cc<=a.cc&&(!ve(e)||!ve(a)||e.sn<a.sn)||!s&&r==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const h=ks(o);return h?this.emeController.getKeySystemAccess([h]):void 0})}if(this.config.requireKeySystemAccessOnStart){const r=jt(this.config);if(r.length)return this.emeController.getKeySystemAccess(r)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,r;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,l))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=mi(n);let h=this.keyIdToKeyInfo[o];if((s=h)!=null&&s.decryptdata.key)return n.key=h.decryptdata.key,Promise.resolve({frag:e,keyInfo:h});if(this.emeController&&(r=h)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(h.decryptdata)){case"usable":case"usable-in-future":return h.keyLoadPromise.then(l=>{const{keyInfo:d}=l;return n.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+Le(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),h=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(h,e):this.loadKeyEME(h,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(h,e);default:return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){const a=function(o){const h=[];return Xn(o,l=>h.push(l.subarray(8,24))),h}(t.initSegment.data);if(a.length){let o=a[0];o.some(h=>h!==0)?(this.log(`Using keyId found in init segment ${Le(o)}`),dt.setKeyIdForUri(e.decryptdata.uri,o)):(o=dt.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Le(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!ve(t))return Promise.resolve(s);const n=this.emeController.loadKey(s);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,s))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,r=new s.loader(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,a)=>{const o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},h=s.keyLoadPolicy.default,l={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,c,f,g)=>{const{frag:p,keyInfo:v}=f,y=mi(v.decryptdata);if(!p.decryptdata||v!==this.keyIdToKeyInfo[y])return a(this.createKeyLoadError(p,I.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));v.decryptdata.key=p.decryptdata.key=new Uint8Array(u.data),p.keyLoader=null,v.loader=null,n({frag:p,keyInfo:v})},onError:(u,c,f,g)=>{this.resetLoader(c),a(this.createKeyLoadError(t,I.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),f,re({url:o.url,data:void 0},u)))},onTimeout:(u,c,f)=>{this.resetLoader(c),a(this.createKeyLoadError(t,I.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(u,c,f)=>{this.resetLoader(c),a(this.createKeyLoadError(t,I.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(o,l,d)})}resetLoader(e){const{frag:t,keyInfo:s,url:r}=e,n=s.loader;t.keyLoader===n&&(t.keyLoader=null,s.loader=null);const a=mi(s.decryptdata)||r;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}function mi(i){if(i.keyFormat!==Ys){const e=i.keyId;if(e)return Le(e)}return i.uri}function Kn(i){const{type:e}=i;switch(e){case Be:return ke;case qe:return _e;default:return Z}}function pi(i,e){let t=i.url;return t!==void 0&&t.indexOf("data:")!==0||(t=e.url),t}class Rh{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,r=t.loader,n=new(s||r)(t);return this.loaders[e.type]=n,n}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:nt,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:r,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:h}=t;this.load({id:s,level:r,pathwayId:n,responseType:"text",type:et,url:a,deliveryDirectives:o,levelOrTrack:h})}onAudioTrackLoading(e,t){const{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:Be,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:r,url:n,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:r,level:null,responseType:"text",type:qe,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[et];if(s){const r=s.context;r&&!t.levels.some(n=>n===r.levelOrTrack)&&(s.abort(),delete this.loaders[et])}}load(e){var t;const s=this.hls.config;let r,n=this.getInternalLoader(e);if(n){const l=this.hls.logger,d=n.context;if(d&&d.levelOrTrack===e.levelOrTrack&&(d.url===e.url||d.deliveryDirectives&&!e.deliveryDirectives))return void(d.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${d.url}`));l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}if(r=e.type===nt?s.manifestLoadPolicy.default:ae({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),U((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===et&&e.level!==null?l=this.hls.levels[e.level].details:e.type===Be&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===qe&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const d=l.partTarget,u=l.targetduration;if(d&&u){const c=1e3*Math.max(3*d,.8*u);r=ae({},r,{maxTimeToFirstByteMs:Math.min(c,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},h={onSuccess:(l,d,u,c)=>{const f=this.getInternalLoader(u);this.resetInternalLoader(u.type);const g=l.data;d.parsing.start=performance.now(),Xe.isMediaPlaylist(g)||u.type!==nt?this.handleTrackOrLevelPlaylist(l,d,u,c||null,f):this.handleMasterPlaylist(l,d,u,c)},onError:(l,d,u,c)=>{this.handleNetworkError(d,u,!1,l,c)},onTimeout:(l,d,u)=>{this.handleNetworkError(d,u,!0,void 0,l)}};n.load(e,o,h)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,r){const n=this.hls,a=e.data,o=pi(e,s),h=Xe.parseMasterPlaylist(a,o);if(h.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,s,h.playlistParsingError,r,t);const{contentSteering:l,levels:d,sessionData:u,sessionKeys:c,startTimeOffset:f,variableList:g}=h;this.variableList=g,d.forEach(E=>{const{unknownCodecs:T}=E;if(T){const{preferManagedMediaSource:A}=this.hls.config;let{audioCodec:L,videoCodec:b}=E;for(let S=T.length;S--;){const k=T[S];ts(k,"audio",A)?(E.audioCodec=L=L?`${L},${k}`:k,Ut.audio[L.substring(0,4)]=2,T.splice(S,1)):ts(k,"video",A)&&(E.videoCodec=b=b?`${b},${k}`:k,Ut.video[b.substring(0,4)]=2,T.splice(S,1))}}});const{AUDIO:p=[],SUBTITLES:v,"CLOSED-CAPTIONS":y}=Xe.parseMasterPlaylistMedia(a,o,h);p.length&&(p.some(E=>!E.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ce({}),bitrate:0,url:""}))),n.trigger(m.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:v,captions:y,contentSteering:l,url:o,stats:t,networkDetails:r,sessionData:u,sessionKeys:c,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,s,r,n){const a=this.hls,{id:o,level:h,type:l}=s,d=pi(e,s),u=U(h)?h:U(o)?o:0,c=Kn(s),f=Xe.parseLevelPlaylist(e.data,d,u,c,0,this.variableList);if(l===nt){const g={attrs:new ce({}),bitrate:0,details:f,name:"",url:d};f.requestScheduled=t.loading.start+Ta(f,0),a.trigger(m.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:d,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,r,n)}handleManifestParsingError(e,t,s,r,n){this.hls.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:I.MANIFEST_PARSING_ERROR,fatal:t.type===nt,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:r,stats:n})}handleNetworkError(e,t,s=!1,r,n){let a=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===et?a+=`: ${e.level} id: ${e.id}`:e.type!==Be&&e.type!==qe||(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let h=I.UNKNOWN,l=!1;const d=this.getInternalLoader(e);switch(e.type){case nt:h=s?I.MANIFEST_LOAD_TIMEOUT:I.MANIFEST_LOAD_ERROR,l=!0;break;case et:h=s?I.LEVEL_LOAD_TIMEOUT:I.LEVEL_LOAD_ERROR,l=!1;break;case Be:h=s?I.AUDIO_TRACK_LOAD_TIMEOUT:I.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case qe:h=s?I.SUBTITLE_TRACK_LOAD_TIMEOUT:I.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(e.type);const u={type:H.NETWORK_ERROR,details:h,fatal:l,url:e.url,loader:d,context:e,error:o,networkDetails:t,stats:n};if(r){const c=t?.url||e.url;u.response=re({url:c,data:void 0},r)}this.hls.trigger(m.ERROR,u)}handlePlaylistLoaded(e,t,s,r,n,a){const o=this.hls,{type:h,level:l,levelOrTrack:d,id:u,groupId:c,deliveryDirectives:f}=r,g=pi(t,r),p=Kn(r);let v=typeof r.level=="number"&&p===Z?l:void 0;const y=e.playlistParsingError;if(y){if(this.hls.logger.warn(`${y} ${e.url}`),!o.config.ignorePlaylistParsingErrors)return void o.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:I.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:y,reason:y.message,response:t,context:r,level:v,parent:p,networkDetails:n,stats:s});e.playlistParsingError=null}if(!e.fragments.length){const E=e.playlistParsingError=new Error("No Segments found in Playlist");return void o.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:I.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:t,context:r,level:v,parent:p,networkDetails:n,stats:s})}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),a.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),h){case nt:case et:if(v)if(d){if(d!==o.levels[v]){const E=o.levels.indexOf(d);E>-1&&(v=E)}}else v=0;o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:d||o.levels[0],level:v||0,id:u||0,stats:s,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:h===nt});break;case Be:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:d,id:u||0,groupId:c||"",stats:s,networkDetails:n,deliveryDirectives:f});break;case qe:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:d,id:u||0,groupId:c||"",stats:s,networkDetails:n,deliveryDirectives:f})}}}class yt{static get version(){return qt}static isMSESupported(){return Gn()}static isSupported(){return function(){if(!Gn())return!1;const e=ut();return typeof e?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(ss(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(ss(t,"audio"))))}()}static getMediaSource(){return ut()}static get Events(){return m}static get MetadataSchema(){return xe}static get ErrorTypes(){return H}static get ErrorDetails(){return I}static get DefaultConfig(){return yt.defaultConfig?yt.defaultConfig:ph}static set DefaultConfig(e){yt.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new er,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(F,w,_){const $=vi();if(typeof console=="object"&&F===!0||typeof F=="object"){const x=["debug","log","info","warn","error"];x.forEach(C=>{$[C]=dr(C,F,_)});try{$.log(`Debug logs enabled for "${w}" in hls.js version 1.6.15`)}catch{return vi()}x.forEach(C=>{yi[C]=dr(C,F)})}else ae(yi,$);return $}(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=function(F,w,_){if((w.liveSyncDurationCount||w.liveMaxLatencyDurationCount)&&(w.liveSyncDuration||w.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(w.liveMaxLatencyDurationCount!==void 0&&(w.liveSyncDurationCount===void 0||w.liveMaxLatencyDurationCount<=w.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(w.liveMaxLatencyDuration!==void 0&&(w.liveSyncDuration===void 0||w.liveMaxLatencyDuration<=w.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const $=Bi(F),x=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(C=>{const M=`${C==="level"?"playlist":C}LoadPolicy`,V=w[M]===void 0,Y=[];x.forEach(W=>{const G=`${C}Loading${W}`,X=w[G];if(X!==void 0&&V){Y.push(G);const j=$[M].default;switch(w[M]={default:j},W){case"TimeOut":j.maxLoadTimeMs=X,j.maxTimeToFirstByteMs=X;break;case"MaxRetry":j.errorRetry.maxNumRetry=X,j.timeoutRetry.maxNumRetry=X;break;case"RetryDelay":j.errorRetry.retryDelayMs=X,j.timeoutRetry.retryDelayMs=X;break;case"MaxRetryTimeout":j.errorRetry.maxRetryDelayMs=X,j.timeoutRetry.maxRetryDelayMs=X}}}),Y.length&&_.warn(`hls.js config: "${Y.join('", "')}" setting(s) are deprecated, use "${M}": ${oe(w[M])}`)}),re(re({},$),w)}(yt.DefaultConfig,e,t);this.userConfig=e,s.progressive&&vh(s,t);const{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:h}=s,l=new o(this),d=this.abrController=new r(this),u=new Mo(this),c=s.interstitialsController,f=c?this.interstitialsController=new c(this,yt):null,g=this.bufferController=new n(this,u),p=this.capLevelController=new a(this),v=new h(this),y=new Rh(this),E=s.contentSteeringController,T=E?new E(this):null,A=this.levelController=new Sh(this,T),L=new Eh(this),b=new Ah(this.config,this.logger),S=this.streamController=new Lh(this,u,b),k=this.gapController=new yh(this,u);p.setStreamController(S),v.setStreamController(S);const D=[y,A,S];f&&D.splice(1,0,f),T&&D.splice(1,0,T),this.networkControllers=D;const P=[d,g,k,p,v,L,u];this.audioTrackController=this.createController(s.audioTrackController,D);const O=s.audioStreamController;O&&D.push(this.audioStreamController=new O(this,u,b)),this.subtitleTrackController=this.createController(s.subtitleTrackController,D);const N=s.subtitleStreamController;N&&D.push(this.subtititleStreamController=new N(this,u,b)),this.createController(s.timelineController,P),b.emeController=this.emeController=this.createController(s.emeController,P),this.cmcdController=this.createController(s.cmcdController,P),this.latencyController=this.createController(Th,P),this.coreComponents=P,D.push(l);const B=l.onErrorOut;typeof B=="function"&&this.on(m.ERROR,B,l),this.on(m.MANIFEST_LOADED,y.onManifestLoaded,y)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,r){this._emitter.off(e,t,s,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const r=e===m.ERROR;this.trigger(m.ERROR,{type:H.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:r,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(m.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const n=new Error(`attachMedia failed: invalid argument (${e})`);return void this.trigger(m.ERROR,{type:H.OTHER_ERROR,details:I.ATTACH_MEDIA_ERROR,fatal:!0,error:n})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,r=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(m.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(m.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,r=this._url=Ki.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&s&&(s!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(m.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),this.started&&this.networkControllers);s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[Z]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[ke]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[_e]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch{try{const s=URL.createObjectURL(new Blob),r=s.toString();return URL.revokeObjectURL(s),r.slice(r.lastIndexOf("/")+1)}catch{let r=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const a=(r+16*Math.random())%16|0;return r=Math.floor(r/16),(n=="x"?a:3&a|8).toString(16)})}}}()),e}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(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){(function(t){return Si.indexOf(t)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let r=0;r<s;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let r;if(r=t===-1&&e!=null&&e.length?e.length-1:t,s)for(let n=r;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=s)return n}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!((e=this.bufferController)==null||!e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return ta(e,ia(t),navigator.mediaCapabilities)}}yt.defaultConfig=void 0;export{yt as u};