UNPKG

iobroker.lovelace

Version:

With this adapter you can build visualization for ioBroker with Home Assistant Lovelace UI

1 lines 339 kB
export const __rspack_esm_id=29091;export const __rspack_esm_ids=[29091];export const __webpack_modules__={65213(t,e,r){var i=r(44576),s=r(79039),n=i.RegExp,a=!s(function(){var t=!0;try{n(".","d")}catch(e){t=!1}var e={},r="",i=t?"dgimsy":"gimsy",s=function(t,i){Object.defineProperty(e,t,{get:function(){return r+=i,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var o in t&&(a.hasIndices="d"),a)s(o,a[o]);return Object.getOwnPropertyDescriptor(n.prototype,"flags").get.call(e)!==i||r!==i});t.exports={correct:a}},67979(t,e,r){var i=r(28551);t.exports=function(){var t=i(this),e="";return t.hasIndices&&(e+="d"),t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.unicodeSets&&(e+="v"),t.sticky&&(e+="y"),e}},69479(t,e,r){var i=r(43724),s=r(62106),n=r(65213),a=r(67979);i&&!n.correct&&(s(RegExp.prototype,"flags",{configurable:!0,get:a}),n.correct=!0)},10318(t,e,r){r.d(e,{default:()=>gn});r(74423),r(44114),r(16573),r(78100),r(77936),r(18111),r(22489),r(7588),r(61701),r(18237),r(13579),r(33110),r(69479),r(37467),r(44732),r(79577),r(16632),r(34226),r(9486),r(20456),r(64979),r(14603),r(47566),r(98721);const i=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},s=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=n},n=Number.MAX_SAFE_INTEGER||9007199254740991;let a=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),o=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.UNKNOWN="unknown",t}({}),l=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});var d="manifest",h="level",u="audioTrack",c="subtitleTrack",f="main",g="audio",m="subtitle";class p{sample(t,e){const r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}constructor(t,e=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}}class v{update(t,e){const{slow_:r,fast_:i,ttfb_:s}=this;r.halfLife!==t&&(this.slow_=new p(t,r.getEstimate(),r.getTotalWeight())),i.halfLife!==e&&(this.fast_=new p(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.ttfb_=new p(t,s.getEstimate(),s.getTotalWeight()))}sample(t,e){const r=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/r;this.fast_.sample(r,i),this.slow_.sample(r,i)}sampleTTFB(t){const e=t/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(r,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}constructor(t,e,r,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new p(t),this.fast_=new p(e),this.defaultTTFB_=i,this.ttfb_=new p(t)}}function E(t,e,r){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var i=r.call(t,e);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function y(){return y=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var i in r)({}).hasOwnProperty.call(r,i)&&(t[i]=r[i])}return t},y.apply(null,arguments)}function T(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,i)}return r}function S(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?T(Object(r),!0).forEach(function(e){E(t,e,r[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):T(Object(r)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))})}return t}class L{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const r=`[${t}]:`;this.trace=R,this.debug=e.debug.bind(null,r),this.log=e.log.bind(null,r),this.warn=e.warn.bind(null,r),this.info=e.info.bind(null,r),this.error=e.error.bind(null,r)}}const R=function(){},A={trace:R,debug:R,log:R,warn:R,info:R,error:R};function b(){return y({},A)}function D(t,e,r){return e[t]?e[t].bind(e):function(t,e){const r=self.console[t];return r?r.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):R}(t,r)}const k=b();const _=k;function I(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var C,x;var w=x?C:(x=1,C={}),P=I(w);function O(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function F(t,e=!1){if("undefined"!=typeof TextDecoder){const r=new TextDecoder("utf-8").decode(t);if(e){const t=r.indexOf("\0");return-1!==t?r.substring(0,t):r}return r.replace(/\0/g,"")}const r=t.length;let i,s,n,a="",o=0;for(;o<r;){if(i=t[o++],0===i&&e)return a;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:s=t[o++],a+=String.fromCharCode((31&i)<<6|63&s);break;case 14:s=t[o++],n=t[o++],a+=String.fromCharCode((15&i)<<12|(63&s)<<6|63&n)}}return a}function M(t){let e="";for(let r=0;r<t.length;r++){let i=t[r].toString(16);i.length<2&&(i="0"+i),e+=i}return e}function N(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var B,$={exports:{}};var U,G,V,H,K,Y=(B||(B=1,U=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,G=/^(?=([^\/?#]*))\1([^]*)$/,V=/(?:\/|^)\.(?=\/)/g,H=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,$.exports=K={buildAbsoluteURL:function(t,e,r){if(r=r||{},t=t.trim(),!(e=e.trim())){if(!r.alwaysNormalize)return t;var i=K.parseURL(t);if(!i)throw new Error("Error trying to parse base URL.");return i.path=K.normalizePath(i.path),K.buildURLFromParts(i)}var s=K.parseURL(e);if(!s)throw new Error("Error trying to parse relative URL.");if(s.scheme)return r.alwaysNormalize?(s.path=K.normalizePath(s.path),K.buildURLFromParts(s)):e;var n=K.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");if(!n.netLoc&&n.path&&"/"!==n.path[0]){var a=G.exec(n.path);n.netLoc=a[1],n.path=a[2]}n.netLoc&&!n.path&&(n.path="/");var o={scheme:n.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(o.netLoc=n.netLoc,"/"!==s.path[0]))if(s.path){var l=n.path,d=l.substring(0,l.lastIndexOf("/")+1)+s.path;o.path=K.normalizePath(d)}else o.path=n.path,s.params||(o.params=n.params,s.query||(o.query=n.query));return null===o.path&&(o.path=r.alwaysNormalize?K.normalizePath(s.path):s.path),K.buildURLFromParts(o)},parseURL:function(t){var e=U.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(V,"");t.length!==(t=t.replace(H,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}}),$.exports);class W{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 j="audio",q="video",X="audiovideo";class z{setByteRange(t,e){const r=t.split("@",2);let i;i=1===r.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[j]:null,[q]:null,[X]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new W),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Y.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[j]=null,t[q]=null,t[X]=null}constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const r=tt(t,e);r&&(r.enumerable=!0,Object.defineProperty(t,e,r))}(this,"stats")}}function Q(t){return"initSegment"!==t.sn}class Z extends z{get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],e=this.byteRange[1];if(i(t)&&i(e))return e-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const r=this._decryptdata=e[t[0]]||null;r&&(this._decryptdata=r.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=i(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e;const t=Object.keys(this.levelkeys),r=t.length;if(r>1||1===r&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){i(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return Q(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var r;const i=e[t];!i||null!=(r=this._decryptdata)&&r.keyId||(this._decryptdata=i.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,r,i,s,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,s)):a[t]={startPTS:e,endPTS:r,startDTS:i,endDTS:s,partial:n}}constructor(t,e){super(e),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}}class J extends z{get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}constructor(t,e,r,i,s){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=i;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,s),s&&(this.fragOffset=s.fragOffset+s.duration)}}function tt(t,e){const r=Object.getPrototypeOf(t);if(r){const t=Object.getOwnPropertyDescriptor(r,e);return t||tt(r,e)}}const et=Math.pow(2,32)-1,rt=[].push,it={video:1,audio:2,id3:3,text:4};function st(t){return String.fromCharCode.apply(null,t)}function nt(t,e){const r=t[e]<<8|t[e+1];return r<0?65536+r:r}function at(t,e){const r=lt(t,e);return r<0?4294967296+r:r}function ot(t,e){let r=at(t,e);return r*=Math.pow(2,32),r+=at(t,e+4),r}function lt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function dt(t,e){const r=[];if(!e.length)return r;const i=t.byteLength;for(let s=0;s<i;){const n=at(t,s),a=n>1?s+n:i;if(st(t.subarray(s+4,s+8))===e[0])if(1===e.length)r.push(t.subarray(s+8,a));else{const i=dt(t.subarray(s+8,a),e.slice(1));i.length&&rt.apply(r,i)}s=a}return r}function ht(t){const e=[],r=t[0];let i=8;const s=at(t,i);i+=4;let n=0,a=0;0===r?(n=at(t,i),a=at(t,i+4),i+=8):(n=ot(t,i),a=ot(t,i+8),i+=16),i+=2;let o=t.length+a;const l=nt(t,i);i+=2;for(let r=0;r<l;r++){let r=i;const n=at(t,r);r+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return _.warn("SIDX has hierarchical references (not supported)"),null;const l=at(t,r);r+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/s,start:o,end:o+a-1}}),o+=a,r+=4,i=r}return{earliestPresentationTime:n,timescale:s,version:r,referencesCount:l,references:e}}function ut(t){const e=[],r=dt(t,["moov","trak"]);for(let t=0;t<r.length;t++){const i=r[t],s=dt(i,["tkhd"])[0];if(s){let t=s[0];const r=at(s,0===t?12:20),n=dt(i,["mdia","mdhd"])[0];if(n){t=n[0];const s=at(n,0===t?12:20),a=dt(i,["mdia","hdlr"])[0];if(a){const t=st(a.subarray(8,12)),n={soun:j,vide:q}[t],o=ct(dt(i,["mdia","minf","stbl","stsd"])[0]);n?(e[r]={timescale:s,type:n,stsd:o},e[n]=S({timescale:s,id:r},o)):e[r]={timescale:s,type:t,stsd:o}}}}}return dt(t,["moov","mvex","trex"]).forEach(t=>{const r=at(t,4),i=e[r];i&&(i.default={duration:at(t,12),flags:at(t,20)})}),e}function ct(t){const e=t.subarray(8),r=e.subarray(86),i=st(e.subarray(4,8));let s,n=i;const a="enca"===i||"encv"===i;if(a){const t=dt(e,[i])[0];dt(t.subarray("enca"===i?28:78),["sinf"]).forEach(t=>{const e=dt(t,["schm"])[0];if(e){const r=st(e.subarray(4,8));if("cbcs"===r||"cenc"===r){const e=dt(t,["frma"])[0];e&&(n=st(e))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=dt(r,["avcC"])[0];t&&t.length>3&&(n+="."+mt(t[1])+mt(t[2])+mt(t[3]),s=ft("avc1"===o?"dva1":"dvav",r));break}case"mp4a":{const t=dt(e,[i])[0],r=dt(t.subarray(28),["esds"])[0];if(r&&r.length>7){let t=4;if(3!==r[t++])break;t=gt(r,t),t+=2;const e=r[t++];if(128&e&&(t+=2),64&e&&(t+=r[t++]),4!==r[t++])break;t=gt(r,t);const i=r[t++];if(64!==i)break;if(n+="."+mt(i),t+=12,5!==r[t++])break;t=gt(r,t);const s=r[t++];let a=(248&s)>>3;31===a&&(a+=1+((7&s)<<3)+((224&r[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=dt(r,["hvcC"])[0];if(t&&t.length>12){const e=t[1],r=["","A","B","C"][e>>6],i=31&e,s=at(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+r+i,n+="."+function(t){let e=0;for(let r=0;r<32;r++)e|=(t>>r&1)<<31-r;return e>>>0}(s).toString(16).toUpperCase(),n+="."+a+o;let d="";for(let t=l.length;t--;){const e=l[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}n+=d}s=ft("hev1"==o?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=ft(n,r)||n;break;case"vp09":{const t=dt(r,["vpcC"])[0];if(t&&t.length>6){const e=t[4],r=t[5],i=t[6]>>4&15;n+="."+pt(e)+"."+pt(r)+"."+pt(i)}break}case"av01":{const t=dt(r,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,i=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,d=2===e&&o?l?12:10:o?10:8,h=(16&t[2])>>4,u=(8&t[2])>>3,c=(4&t[2])>>2,f=3&t[2],g=1,m=1,p=1,v=0;n+="."+e+"."+pt(i)+a+"."+pt(d)+"."+h+"."+u+c+f+"."+pt(g)+"."+pt(m)+"."+pt(p)+"."+v,s=ft("dav1",r)}break}}return{codec:n,encrypted:a,supplemental:s}}function ft(t,e){const r=dt(e,["dvvC"]),i=r.length?r[0]:dt(e,["dvcC"])[0];if(i){const e=i[2]>>1&127,r=i[2]<<5&32|i[3]>>3&31;return t+"."+pt(e)+"."+pt(r)}}function gt(t,e){const r=e+5;for(;128&t[e++]&&e<r;);return e}function mt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function pt(t){return(t<10?"0":"")+t}function vt(t,e){dt(t,["moov","trak"]).forEach(t=>{const r=dt(t,["mdia","minf","stbl","stsd"])[0];if(!r)return;const i=r.subarray(8);let s=dt(i,["enca"]);const n=s.length>0;n||(s=dt(i,["encv"])),s.forEach(t=>{dt(n?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const r=function(t){const e=dt(t,["schm"])[0];if(e){const r=st(e.subarray(4,8));if("cbcs"===r||"cenc"===r){const e=dt(t,["schi","tenc"])[0];if(e)return e}}}(t);r&&e(r,n)})})})}function Et(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function yt(t,e){const r=[],i=e.samples,s=e.timescale,n=e.id;let a=!1;return dt(i,["moof"]).map(o=>{const l=o.byteOffset-8;dt(o,["traf"]).map(o=>{const d=dt(o,["tfdt"]).map(t=>{const e=t[0];let r=at(t,4);return 1===e&&(r*=Math.pow(2,32),r+=at(t,8)),r/s})[0];return void 0!==d&&(t=d),dt(o,["tfhd"]).map(d=>{const h=at(d,4),u=16777215&at(d,0);let c=0;const f=!!(16&u);let g=0;const m=!!(32&u);let p=8;h===n&&(!!(1&u)&&(p+=8),!!(2&u)&&(p+=4),!!(8&u)&&(c=at(d,p),p+=4),f&&(g=at(d,p),p+=4),m&&(p+=4),"video"===e.type&&(a=Tt(e.codec)),dt(o,["trun"]).map(n=>{const o=n[0],d=16777215&at(n,0),h=!!(1&d);let u=0;const f=!!(4&d),m=!!(256&d);let p=0;const v=!!(512&d);let E=0;const y=!!(1024&d),T=!!(2048&d);let S=0;const L=at(n,4);let R=8;h&&(u=at(n,R),R+=4),f&&(R+=4);let A=u+l;for(let l=0;l<L;l++){if(m?(p=at(n,R),R+=4):p=c,v?(E=at(n,R),R+=4):E=g,y&&(R+=4),T&&(S=0===o?at(n,R):lt(n,R),R+=4),e.type===q){let e=0;for(;e<E;){const n=at(i,A);if(A+=4,St(a,i[A])){Lt(i.subarray(A,A+n),a?2:1,t+S/s,r)}A+=n,e+=n+4}}t+=p/s}}))})})}),r}function Tt(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function St(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Lt(t,e,r,i){const s=Rt(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<s.length;){a=0;do{if(n>=s.length)break;l=s[n++],a+=l}while(255===l);o=0;do{if(n>=s.length)break;l=s[n++],o+=l}while(255===l);const t=s.length-n;let e=n;if(o<t)n+=o;else if(o>t){_.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===s[e++]){const t=nt(s,e);if(e+=2,49===t){const t=at(s,e);if(e+=4,1195456820===t){const t=s[e++];if(3===t){const n=s[e++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let t=1;t<l;t++)d[t]=s[e++]}i.push({type:t,payloadType:a,pts:r,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let r=0;r<16;r++){const i=s[e++].toString(16);t.push(1==i.length?"0"+i:i),3!==r&&5!==r&&7!==r&&9!==r||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=s[e++];i.push({payloadType:a,pts:r,uuid:t.join(""),userData:F(l),userDataBytes:l})}}}function Rt(t){const e=t.byteLength,r=[];let i=1;for(;i<e-2;)0===t[i]&&0===t[i+1]&&3===t[i+2]?(r.push(i+2),i+=2):i++;if(0===r.length)return t;const s=e-r.length,n=new Uint8Array(s);let a=0;for(i=0;i<s;a++,i++)a===r[0]&&(a++,r.shift()),n[i]=t[a];return n}const At=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),bt={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 Dt(t,e){const r=bt[e];return!!r&&!!r[t.slice(0,4)]}function kt(t,e,r=!0){return!t.split(",").some(t=>!_t(t,e,r))}function _t(t,e,r=!0){var i;const s=O(r);return null!=(i=null==s?void 0:s.isTypeSupported(It(t,e)))&&i}function It(t,e){return`${e}/mp4;codecs=${t}`}function Ct(t){if(t){const e=t.substring(0,4);return bt.video[e]}return 2}function xt(t){const e=At();return t.split(",").reduce((t,r)=>{const i=e&&Tt(r)?9:bt.video[r];return i?(2*i+t)/(t?3:2):(bt.audio[r]+t)/(t?2:1)},0)}const wt={};const Pt=/flac|opus|mp4a\.40\.34/i;function Ot(t,e=!0){return t.replace(Pt,t=>function(t,e=!0){if(wt[t])return wt[t];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let s=0;s<r.length;s++){var i;if(_t(r[s],"audio",e))return wt[t]=r[s],r[s];if("mp3"===r[s]&&null!=(i=O(e))&&i.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function Ft(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(Mt(t,"audio")||Mt(t,"video")))return t;if(e){const r=e.split(",");if(r.length>1){if(t)for(let e=r.length;e--;)if(r[e].substring(0,4)===t.substring(0,4))return r[e];return r[0]}}return e||t}function Mt(t,e){return Dt(t,e)&&_t(t,e)}function Nt(t){if(t.startsWith("av01.")){const e=t.split("."),r=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=r[t-4];return e.join(".")}return t}function Bt(t){const e=O(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1}}function $t(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Ut=["NONE","TYPE-0","TYPE-1",null];const Gt=["SDR","PQ","HLG"];var Vt="",Ht="YES",Kt="v2";function Yt(t){const{canSkipUntil:e,canSkipDateRanges:r,age:i}=t;return e&&i<e/2?r?Kt:Ht:Vt}class Wt{addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}constructor(t,e,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=r}}class jt{get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return qt(this._audioGroups,t)}hasSubtitleGroup(t){return qt(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const r=null==(e=t.supplemental)?void 0:e.videoCodec;r&&r!==t.videoCodec&&(this.codecSet+=`,${r.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}}function qt(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Xt(t,e){let r=!1,i=[];if(t&&(r="SDR"!==t,i=[t]),e){i=e.allowedVideoRanges||Gt.slice(0);const t="SDR"!==i.join("")&&!e.videoCodec;r=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),r||(i=["SDR"])}return{preferHDR:r,allowedVideoRanges:i}}const zt=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(r,i)=>{if(t&&(i=t(r,i)),"object"==typeof i&&null!==i){if(e.has(i))return;e.add(i)}return i}})(e));function Qt(t,e){_.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Zt(t){return t.reduce((t,e)=>{let r=t.groups[e.groupId];r||(r=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(e);const i=e.channels||"2";return r.channels[i]=(r.channels[i]||0)+1,r.hasDefault=r.hasDefault||e.default,r.hasAutoSelect=r.hasAutoSelect||e.autoselect,r.hasDefault&&(t.hasDefaultAudio=!0),r.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Jt(t,e){var r;return!!t&&t!==(null==(r=e.loadLevelObj)?void 0:r.uri)}const te=function(t,e){let r=0,i=t.length-1,s=null,n=null;for(;r<=i;){s=(r+i)/2|0,n=t[s];const a=e(n);if(a>0)r=s+1;else{if(!(a<0))return n;i=s-1}}return null};function ee(t,e,r=0,i=0,s=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const i=t.endDTS-r;i>0&&i<15e-7&&(r+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===r&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===re(r,i,n)||function(t,e,r){if(e&&0===e.start&&e.level<t.level&&(e.endPTS||0)>0){const i=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),r);return t.start<=i}return!1}(n,t,Math.min(s,i))))return n;const a=te(e,re.bind(null,r,i));return!a||a===t&&n?n:a}function re(t=0,e=0,r){if(r.start<=t&&r.start+r.duration>t)return 0;const i=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=t?1:r.start-i>t&&r.start?-1:0}function ie(t,e,r){const i=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>t}function se(t){switch(t.details){case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_TIMEOUT:case o.LEVEL_LOAD_TIMEOUT:case o.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ne(t){return t.details.startsWith("key")}function ae(t){return ne(t)&&!!t.frag&&!t.frag.decryptdata}function oe(t,e){const r=se(e);return t.default[(r?"timeout":"error")+"Retry"]}function le(t,e){const r="linear"===t.backoff?1:Math.pow(2,e);return Math.min(r*t.retryDelayMs,t.maxRetryDelayMs)}function de(t){return S(S({},t),{errorRetry:null,timeoutRetry:null})}function he(t,e,r,i){if(!t)return!1;const s=null==i?void 0:i.code,n=e<t.maxNumRetry&&(function(t){return ue(t)||!!t&&(t<400||t>499)}(s)||!!r);return t.shouldRetry?t.shouldRetry(t,e,r,i,n):n}function ue(t){return 0===t&&!1===navigator.onLine}var ce=0,fe=2,ge=3,me=5,pe=0,ve=1,Ee=2,ye=4;function Te(t){const e={action:ce,flags:pe};return t&&(e.resolved=!0),e}const Se=/^(\d+)x(\d+)$/,Le=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Re{get clientAttrs(){return Object.keys(this).filter(t=>"X-"===t.substring(0,2))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const r=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)r[t]=parseInt(e.slice(2*t,2*t+2),16);return r}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const r=this[t];return r?parseFloat(r):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const r=this[t];return(r?r.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=Se.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let r;const i={};for(Le.lastIndex=0;null!==(r=Le.exec(t));){const s=r[1].trim();let n=r[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(s){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o));else if(!o&&!a)switch(s){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":_.warn(`${t}: attribute ${s} is missing quotes`)}i[s]=n}return i}constructor(t,e){"string"==typeof t&&(t=Re.parseAttrList(t,e)),y(this,t)}}function Ae(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function be(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class De{get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(_.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(i(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&i(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}constructor(t,e,r=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==e?void 0:e.tagAnchor)||null,this.tagOrder=null!=(s=null==e?void 0:e.tagOrder)?s:r,e){const r=e.attr;for(const e in r)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==r[e]){_.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=y(new Re({}),r,t)}if(this.attr=t,e?(this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=(null==e?void 0:e.endDate)||new Date(this.attr["END-DATE"]);i(t.getTime())&&(this._endDate=t)}}}class ke{reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,r=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!r||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let r=e.decryptdata;return r||(e.setKeyFormat(t.keyFormat),r=e.decryptdata),!!r&&t.matches(r)})}get hasProgramDateTime(){return!!this.fragments.length&&i(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let r=t.length;r--;)if(t[r].index>e)return t[r].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}}function _e(t,e){return t.length===e.length&&!t.some((t,r)=>t!==e[r])}function Ie(t,e){return!t&&!e||!(!t||!e)&&_e(t,e)}var Ce=0,xe=1;function we(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function Pe(t){switch(t){case"AES-128":case"AES-256":return Ce;case"AES-256-CTR":return xe;default:throw new Error(`invalid full segment method ${t}`)}}let Oe={};class Fe{static clearKeyUriToKeyIdMap(){Oe={}}static setKeyIdForUri(t,e){Oe[t]=e}static addKeyIdForUri(t){const e=Object.keys(Oe).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,e),Oe[t]=r,r}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&_e(t.keyFormatVersions,this.keyFormatVersions)&&Ie(t.iv,this.iv)&&Ie(t.keyId,this.keyId)}isSupported(){if(this.method){if(we(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method}return!1}getDecryptData(t,e){if(!this.encrypted||!this.uri)return null;if(we(this.method)){let e=this.iv;e||("number"!=typeof t&&(_.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),e=function(t){const e=new Uint8Array(16);for(let r=12;r<16;r++)e[r]=t>>8*(15-r)&255;return e}(t));return new Fe(this.method,this.uri,"identity",this.keyFormatVersions,e)}return this}constructor(t,e,r,i=[1],s=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=r,this.keyFormatVersions=i,this.iv=s,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!we(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(N(n)))}}const Me=/#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,Ne=/#EXT-X-MEDIA:(.*)/g,Be=/^#EXT(?:INF|-X-TARGETDURATION):/m,$e=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Ue=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 Ge{static findGroup(t,e){for(let r=0;r<t.length;r++){const i=t[r];if(i.id===e)return i}}static resolve(t,e){return Y.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Be.test(t)}static parseMasterPlaylist(t,e){const r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},i=[];if(Me.lastIndex=0,!t.startsWith("#EXTM3U"))return r.playlistParsingError=new Error("no EXTM3U delimiter"),r;let s;for(;null!=(s=Me.exec(t));)if(s[1]){var n;const t=new Re(s[1],r),a=s[2],o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Ge.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),We(t.CODECS,o);const d=t["SUPPLEMENTAL-CODECS"];d&&(o.supplemental={},We(d,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||i.push(o),r.levels.push(o)}else if(s[3]){const t=s[3],i=s[4];switch(t){case"SESSION-DATA":{const t=new Re(i,r),e=t["DATA-ID"];e&&(null===r.sessionData&&(r.sessionData={}),r.sessionData[e]=t);break}case"SESSION-KEY":{const t=Ke(i,e,r);t.encrypted&&t.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(t)):_.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":break;case"CONTENT-STEERING":{const t=new Re(i,r);r.contentSteering={uri:Ge.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=Ye(i)}}const a=i.length>0&&i.length<r.levels.length;return r.levels=a?i:r.levels,0===r.levels.length&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(t,e,r){let i;const s={},n=r.levels,a={AUDIO:n.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:n.map(t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(Ne.lastIndex=0;null!==(i=Ne.exec(t));){const t=new Re(i[1],r),n=t.TYPE;if(n){const r=a[n],i=s[n]||[];s[n]=i;const l=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],h=t.CHANNELS,u=t.CHARACTERISTICS,c=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Ge.resolve(t.URI,e):""};if(d&&(f.assocLang=d),h&&(f.channels=h),u&&(f.characteristics=u),c&&(f.instreamId=c),null!=r&&r.length){const t=Ge.findGroup(r,f.groupId)||r[0];je(f,t,"audioCodec"),je(f,t,"textCodec")}i.push(f)}}return s}static parseLevelPlaylist(t,e,r,s,n,a){var o;const l={url:e},d=new ke(e),h=d.fragments,u=[];let c,f,g,m,p=null,v=0,E=0,T=0,S=0,L=0,R=null,A=new Z(s,l),b=-1,D=!1,k=null;if($e.lastIndex=0,d.m3u8=t,d.hasVariableRefs=!1,"#EXTM3U"!==(null==(o=$e.exec(t))?void 0:o[0]))return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;null!==(c=$e.exec(t));){D&&(D=!1,A=new Z(s,l),A.playlistOffset=T,A.setStart(T),A.sn=v,A.cc=S,L&&(A.bitrate=L),A.level=r,p&&(A.initSegment=p,p.rawProgramDateTime&&(A.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),k&&(A.setByteRange(k),k=null)));const t=c[1];if(t){A.duration=parseFloat(t);const e=(" "+c[2]).slice(1);A.title=e||null,A.tagList.push(e?["INF",t,e]:["INF",t])}else if(c[3]){if(i(A.duration)){A.playlistOffset=T,A.setStart(T),g&&ze(A,g,d),A.sn=v,A.level=r,A.cc=S,h.push(A);const t=(" "+c[3]).slice(1);A.relurl=t,qe(A,R,u),R=A,T+=A.duration,v++,E=0,D=!0}}else{if(c=c[0].match(Ue),!c){_.warn("No matches on slow regex match for level playlist!");continue}for(f=1;f<c.length&&void 0===c[f];f++);const t=(" "+c[f]).slice(1),n=(" "+c[f+1]).slice(1),a=c[f+2]?(" "+c[f+2]).slice(1):null;switch(t){case"BYTERANGE":R?A.setByteRange(n,R):A.setByteRange(n);break;case"PROGRAM-DATE-TIME":A.rawProgramDateTime=n,A.tagList.push(["PROGRAM-DATE-TIME",n]),-1===b&&(b=h.length);break;case"PLAYLIST-TYPE":d.type&&Qe(d,t,c),d.type=n.toUpperCase();break;case"MEDIA-SEQUENCE":0!==d.startSN?Qe(d,t,c):h.length>0&&Ze(d,t,c),v=d.startSN=parseInt(n);break;case"SKIP":{d.skippedSegments&&Qe(d,t,c);const e=new Re(n,d),r=e.decimalInteger("SKIPPED-SEGMENTS");if(i(r)){d.skippedSegments+=r;for(let t=r;t--;)h.push(null);v+=r}const s=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(s.split("\t")));break}case"TARGETDURATION":0!==d.targetduration&&Qe(d,t,c),d.targetduration=Math.max(parseInt(n),1);break;case"VERSION":null!==d.version&&Qe(d,t,c),d.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":case"DEFINE":break;case"ENDLIST":d.live||Qe(d,t,c),d.live=!1;break;case"#":(n||a)&&A.tagList.push(a?[n,a]:[n]);break;case"DISCONTINUITY":S++,A.tagList.push(["DIS"]);break;case"GAP":A.gap=!0,A.tagList.push([t]);break;case"BITRATE":A.tagList.push([t,n]),L=1e3*parseInt(n),i(L)?A.bitrate=L:L=0;break;case"DATERANGE":{const t=new Re(n,d),e=new De(t,d.dateRanges[t.ID],d.dateRangeTagCount);d.dateRangeTagCount++,e.isValid||d.skippedSegments?d.dateRanges[e.id]=e:_.warn(`Ignoring invalid DATERANGE tag: "${n}"`),A.tagList.push(["EXT-X-DATERANGE",n]);break}case"DISCONTINUITY-SEQUENCE":0!==d.startCC?Qe(d,t,c):h.length>0&&Ze(d,t,c),d.startCC=S=parseInt(n);break;case"KEY":{const t=Ke(n,e,d);if(t.isSupported()){if("NONE"===t.method){g=void 0;break}g||(g={});const e=g[t.keyFormat];null!=e&&e.matches(t)||(e&&(g=y({},g)),g[t.keyFormat]=t)}else _.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${n}" (light build)`);break}case"START":d.startTimeOffset=Ye(n);break;case"MAP":{const t=new Re(n,d);if(A.duration){const e=new Z(s,l);Xe(e,t,r,g),p=e,A.initSegment=p,p.rawProgramDateTime&&!A.rawProgramDateTime&&(A.rawProgramDateTime=p.rawProgramDateTime)}else{const e=A.byteRangeEndOffset;if(e){const t=A.byteRangeStartOffset;k=`${e-t}@${t}`}else k=null;Xe(A,t,r,g),p=A,D=!0}p.cc=S;break}case"SERVER-CONTROL":m&&Qe(d,t,c),m=new Re(n),d.canBlockReload=m.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=m.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&m.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=m.optionalFloat("PART-HOLD-BACK",0),d.holdBack=m.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{d.partTarget&&Qe(d,t,c);const e=new Re(n);d.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=d.partList;t||(t=d.partList=[]);const e=E>0?t[t.length-1]:void 0,r=E++,i=new Re(n,d),s=new J(i,A,l,r,e);t.push(s),A.duration+=s.duration;break}case"PRELOAD-HINT":{const t=new Re(n,d);d.preloadHint=t;break}case"RENDITION-REPORT":{const t=new Re(n,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(t);break}default:_.warn(`line parsed but not handled: ${c}`)}}}R&&!R.relurl?(h.pop(),T-=R.duration,d.partList&&(d.fragmentHint=R)):d.partList&&(qe(A,R,u),A.cc=S,d.fragmentHint=A,g&&ze(A,g,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const I=h.length,C=h[0],x=h[I-1];if(T+=d.skippedSegments*d.targetduration,T>0&&I&&x){d.averagetargetduration=T/I;const t=x.sn;d.endSN="initSegment"!==t?t:0,d.live||(x.endList=!0),b>0&&(!function(t,e){let r=t[e];for(let i=e;i--;){const e=t[i];if(!e)return;e.programDateTime=r.programDateTime-1e3*e.duration,r=e}}(h,b),C&&u.unshift(C))}return d.fragmentHint&&(T+=d.fragmentHint.duration),d.totalduration=T,u.length&&d.dateRangeTagCount&&C&&Ve(u,d),d.endCC=S,d}}function Ve(t,e){let r=t.length;if(!r){if(!e.hasProgramDateTime)return;{const i=e.fragments[e.fragments.length-1];t.push(i),r++}}const i=t[r-1],s=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],d=l.startDate.getTime();l.tagAnchor=i.ref;for(let i=r;i--;){var a;if((null==(a=t[i])?void 0:a.sn)<e.startSN)break;const r=He(e,d,t,i,s);if(-1!==r){l.tagAnchor=e.fragments[r].ref;break}}}}function He(t,e,r,i,s){const n=r[i];if(n){const o=n.programDateTime;if(e>=o||0===i){var a;if(e<=o+1e3*(((null==(a=r[i+1])?void 0:a.start)||s)-n.start)){const s=r[i].sn-t.startSN;if(s<0)return-1;const n=t.fragments;if(n.length>r.length){for(let a=(r[i+1]||n[n.length-1]).sn-t.startSN;a>s;a--){const t=n[a].programDateTime;if(e>=t&&e<t+1e3*n[a].duration)return a}}return s}}}return-1}function Ke(t,e,r){var i,s;const n=new Re(t,r),a=null!=(i=n.METHOD)?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,h=null!=(s=n.KEYFORMAT)?s:"identity";o&&n.IV&&!l&&_.error(`Invalid IV: ${n.IV}`);const u=o?Ge.resolve(o,e):"",c=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Fe(a,u,h,c,l,n.KEYID)}function Ye(t){const e=new Re(t).decimalFloatingPoint("TIME-OFFSET");return i(e)?e:null}function We(t,e){let r=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text"].forEach(t=>{const i=r.filter(e=>Dt(e,t));i.length&&(e[`${t}Codec`]=i.map(t=>t.split("/")[0]).join(","),r=r.filter(t=>-1===i.indexOf(t)))}),e.unknownCodecs=r}function je(t,e,r){const i=e[r];i&&(t[r]=i)}function qe(t,e,r){t.rawProgramDateTime?r.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function Xe(t,e,r,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=r,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function ze(t,e,r){t.levelkeys=e;const{encryptedFragments:i}=r;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||i.push(t)}function Qe(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${r[0]})`)}function Ze(t,e,r){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${r[0]})`)}function Je(t,e){const r=e.startPTS;if(i(r)){let i,s=0;e.sn>t.sn?(s=r-t.start,i=t):(s=t.start-r,i=e),i.duration!==s&&i.setDuration(s)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.setStart(t.start+(t.minEndPTS-t.start)):e.setStart(t.start+t.duration)}else e.setStart(Math.max(t.start-e.duration,0))}function tr(t,e,r,s,n,a,o){s-r<=0&&(o.warn("Fragment should have a positive duration",e),s=r+e.duration,a=n+e.duration);let l=r,d=s;const h=e.startPTS,u=e.endPTS;if(i(h)){const c=Math.abs(h-r);t&&c>t.totalduration?o.warn(`media timestamps and playlist times differ by ${c}s for level ${e.level} ${t.url}`):i(e.deltaPTS)?e.deltaPTS=Math.max(c,e.deltaPTS):e.deltaPTS=c,l=Math.max(r,h),r=Math.min(r,h),n=void 0!==e.startDTS?Math.min(n,e.startDTS):n,d=Math.min(s,u),s=Math.max(s,u),a=void 0!==e.endDTS?Math.max(a,e.endDTS):a}const c=r-e.start;0!==e.start&&e.setStart(r),e.setDuration(s-e.start),e.startPTS=r,e.maxStartPTS=l,e.startDTS=n,e.endPTS=s,e.minEndPTS=d,e.endDTS=a;const f=e.sn;if(!t||f<t.startSN||f>t.endSN)return 0;let g;const m=f-t.startSN,p=t.fragments;for(p[m]=e,g=m;g>0;g--)Je(p[g],p[g-1]);for(g=m;g<p.length-1;g++)Je(p[g],p[g+1]);return t.fragmentHint&&Je(p[p.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,c}function er(t,e,r){if(t===e)return;let s=null;const n=t.fragments;for(let t=n.length-1;t>=0;t--){const e=n[t].initSegment;if(e){s=e;break}}let a;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,r){const i=e.skippedSegments,s=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let d=s;d<=n;d++){const s=l[a+d];let n=o[d];if(i&&!n&&s&&(n=e.fragments[d]=s),s&&n){r(s,n,d,o);const i=s.relurl,a=n.relurl;if(i&&dr(i,a))return void(e.playlistParsingError=rr(`media sequence mismatch ${n.sn}:`,t,e,s,n));if(s.cc!==n.cc)return void(e.playlistParsingError=rr(`discontinuity sequence mismatch (${s.cc}!=${n.cc})`,t,e,s,n))}}}(t,e,(t,r,n,o)=>{if((!e.startCC||e.skippedSegments)&&r.cc!==t.cc){const i=t.cc-r.cc;for(let t=n;t<o.length;t++)o[t].cc+=i;e.endCC=o[o.length-1].cc}i(t.startPTS)&&i(t.endPTS)&&(r.setStart(r.startPTS=t.startPTS),r.startDTS=t.startDTS,r.maxStartPTS=t.maxStartPTS,r.endPTS=t.endPTS,r.endDTS=t.endDTS,r.minEndPTS=t.minEndPTS,r.setDuration(t.endPTS-t.startPTS),r.duration&&(a=r),e.PTSKnown=e.alignedSliding=!0),t.hasStreams&&(r.elementaryStreams=t.elementaryStreams),r.loader=t.loader,t.hasStats&&(r.stats=t.stats),t.initSegment&&(r.initSegment=t.initSegment,s=t.initSegment)});const o=e.fragments,l=e.fragmentHint?o.concat(e.fragmentHint):o;if(s&&l.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=o.some(t=>!t),e.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)o.shift();e.startSN=o[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=function(t,e,r){const{dateRanges:i,recentlyRemovedDateranges:s}=e,n=y({},t);s&&s.forEach(t=>{delete n[t]});const a=Object.keys(n).length;if(!a)return i;return Object.keys(i).forEach(t=>{const e=n[t],s=new De(i[t].attr,e);s.isValid?(n[t]=s,e||(s.tagOrder+=a)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${zt(i[t].attr)}"`)}),n}(t.dateRanges,e,r));const i=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime)for(let t=1;t<l.length;t++)null===l[t].programDateTime&&qe(l[t],l[t-1],i);Ve(i,e)}e.endCC=o[o.length-1].cc}if(!e.startCC){var d;const r=nr(t,e.startSN-1);e.startCC=null!=(d=null==r?void 0:r.cc)?d:o[0].cc}!function(t,e,r){if(t&&e){let i=0;for(let s=0,n=t.length;s<=n;s++){const n=t[s],a=e[s+i];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?r(n,a):i--}}}(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats}),a?tr(e,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,r):ir(t,e),o.length&&(e.totalduration=e.edge-o[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const h=e.advancedDateTime;if(e.advanced&&h){const t=e.edge;e.driftStart||(e.driftStartTime=h,e.driftStart=t),e.driftEndTime=h,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;-1===e.requestScheduled&&(e.requestScheduled=t.requestScheduled)}function rr(t,e,r,i,s){return new Error(`${t} ${s.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${r.startSN}\n${r.m3u8}`)}function ir(t,e,r=!0){const i=e.startSN+e.skippedSegments-t.startSN,s=t.fragments,n=i>=0;let a=0;if(n&&i<s.length)a=s[i].start;else if(n&&e.startSN===t.endSN+1)a=t.fragmentEnd;else if(n&&r)a=t.fragmentStart+i*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return;a=t.fragmentStart}!function(t,e){if(e){const r=t.fragments;for(let i=t.skippedSegments;i<r.length;i++)r[i].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}(e,a)}function sr(t,e=1/0){let r=1e3*t.targetduration;if(t.updated){const i=t.fragments,s=4;if(i.length&&r*s>e){const t=1e3*i[i.length-1].duration;t<r&&(r=t)}}else r/=2;return Math.round(r)}function nr(t,e,r){if(!t)return null;let i=t.fragments[e-t.startSN];return i||(i=t.fragmentHint,i&&i.sn===e?i:e<t.startSN&&r&&r.sn===e?r:null)}function ar(t,e,r){return t?or(t.partList,e,r):null}function or(t,e,r){if(t)for(let i=t.length;i--;){const s=t[i];if(s.index===r&&s.fragment.sn===e)return s}return null}function lr(t){t.forEach((t,e)=>{var r;null==(r=t.details)||r.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function dr(t,e){return!(t===e||!e)&&hr(t)!==hr(e)}function hr(t){return t.replace(/\?[^?]*$/,"")}class ur extends L{destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,r){const i=null==e?void 0:e.renditionReports;if(i){let s=-1;for(let r=0;r<i.length;r++){const n=i[r];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){s=r;break}a===t.substring(0,a.length)&&(s=r)}if(-1!==s){const t=i[s],n=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=r&&Yt(r);return new Wt(n,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,r){const{details:i,stats:s}=e,n=self.performance.now(),d=s.loading.first?Math.max(0,n-s.loading.first):0;i.advancedDateTime=Date.now()-d;const h=this.hls.config.timelineOffset;if(h!==i.appliedTimelineOffset){const t=Math.max(h||0,0);i.appliedTimelineOffset=t,i.fragments.forEach(e=>{e.setStart(e.playlistOffset+t)})}if(i.live||null!=r&&r.live){const h="levelInfo"in e?e.levelInfo:e.track;if(i.reloaded(r),r&&i.fragments.length>0){er(r,i,this);const t=i.playlistParsingError;if(t){this.warn(t);const r=this.hls;if(!r.config.ignorePlaylistParsingErrors){var u;const{networkDetails:n}=e;return void r.trigger(l.ERROR,{type:a.NETWORK_ERROR,details:o.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:t,reason:t.message,level:e.level||void 0,parent:null==(u=i.fragments[0])?void 0:u.type,networkDetails:n,stats:s})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=s.loading.start);const c=this.hls.mainForwardBufferInfo,f=c?c.end-c.len:0,g=sr(i,1e3*(i.edge-f));if(i.requestScheduled+g<n?i.requestScheduled=n:i.requestScheduled+=g,this.log(`live playlist ${t} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let m,p,v;if(i.canBlockReload&&i.endSN&&i.advanced){const t=this.hls.config.lowLatencyMode,s=i.lastPartSn,a=i.endSN,o=i.lastPartIndex,l=s===a;-1!==o?l?(p=a+1,v=t?0:o):(p=s,v=t?o+1:i.maxPartIndex):p=a+1;const d=i.age,u=d+i.ageHeader;let c=Math.min(u-i.partTarget,1.5*i.targetduration);if(c>0){if(u>3*i.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,v=void 0;else if(null!=r&&r.tuneInGoal&&u-i.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${c} with playlist age: ${i.age}`),c=0;else{const t=Math.floor(c/i.targetduration);if(p+=t,void 0!==v){v+=Math.round(c%i.targetduration/i.partTarget)}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${c} skip sn ${t} to part ${v}`)}i.tuneInGoal=c}if(m=this.getDeliveryDirectives(i,e.deliveryDirectives,p,v),t||!l)return i.requestScheduled=n,void this.loadingPlaylist(h,m)}else(i.canBlockReload||i.canSkipUntil)&&(m=this.getDeliveryDirectives(i,e.deliveryDirectives,p,v));m&&void 0!==p&&i.canBlockReload&&(i.requestScheduled=s.loading.first+Math.max(g-2*d,g/2)),this.scheduleLoading(h,m,i)}else this.clearTimer()}scheduleLoading(t,e,r){const i=r||t.details;if(!i)return void this.loadingPlaylist(t,e);const s=self.performance.now(),n=i.requestScheduled;if(s>=n)return void this.loadingPlaylist(t,e);const a=n-s;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,r,i){let s=Yt(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(r=e.msn,i=e.part,s=Vt),new Wt(r,i,s)}checkRetry(t){const e=t.details,r=se(t),i=t.errorAction,{action:s,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(s===me||!i.resolved&&s===fe);if(o){var l;if(n>=a.maxNumRetry)return!1;if(r&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=le(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,i.resolved=!0}return o}constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}}var cr="NOT_LOADED",fr="APPENDING",gr="PARTIAL",mr="OK";class pr{_registerListeners(){const{hls:t}=this;t&&(t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.BUFFER_APPENDED,this.onBufferAppended,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this),t.on(l.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.BUFFER_APPENDED,this.onBufferAppended,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this),t.off(l.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const r=this.activePartLists[e];if(r)for(let e=r.length;e--;){const i=r[e];if(!i)break;if(i.start<=t&&t<=i.end&&i.loaded)return i}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,r){const{fragments:i}=this,s=Object.keys(i);for(let n=s.length;n--;){const a=i[s[n]];if((null==a?void 0:a.body.type)===e&&(!r||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,r,i,s){this.timeRanges&&(this.timeRanges[t]=e);const n=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(i=>{const a=this.fragments[i];if(!a)return;if(n>=a.body.sn)return;if(!a.buffered&&(!a.loaded||s))return void(a.body.type===r&&this.removeFragment(a.body));const o=a.range[t];o&&(0!==o.time.length?o.time.some(t=>{const r=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return r&&this.removeFragment(a.body),r}):this.removeFragment(a.body))})}detectPartialFragments(t){const e=this.timeRanges;if(!e||"initSegment"===t.frag.sn)return;const r=t.frag,i=Er(r),s=this.fragments[i];if(!s||s.buffered&&r.gap)return;const n=!r.relurl;Object.keys(e).forEach(i=>{const a=r.elementaryStreams[i];if(!a)return;const o=e[i],l=n||!0===a.partial;s.range[i]=this.getBufferedTimes(r,t.part,l,o)}),s.loaded=null,Object.keys(s.range).length?(this.bufferedEnd(s,r),vr(s)||this.removeParts(r.sn-1,r.type)):this.removeFragment(s.body)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const r=this.activePartLists[e];r&&(this.activePartLists[e]=yr(r,e=>e.fragment.sn>=t))}fragBuffered(t,e){const r=Er(t);let i=this.fragments[r];!i&&e&&(i=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,t))}getBufferedTimes(t,e,r,i){const s={time:[],partial:r},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<i.length;t++){const e=i.start(t)-this.bufferPadding,r=i.end(t)+this.bufferPadding;if(l>=e&&o<=r){s.time.push({startPTS:Math.max(n,i.start(t)),endPTS:Math.min(a,i.end(t))});break}if(n<r&&a>e){const e=Math.max(n,i.start(t)),r=Math.min(a,i.end(t));r>e&&(s.partial=!0,s.time.push({startPTS:e,endPTS:r}))}else if(a<=e)break}return s}getPartialFragment(t){let e,r,i,s=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&vr(d)&&(r=d.body.start-a,i=d.body.end+a,t>=r&&t<=i&&(e=Math.min(t-r,i-t),n<=e&&(s=d.body,n=e)))}),s}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||vr(e))}getState(t){const e=Er(t),r=this.fragments[e];return r?r.buffered?vr(r)?gr:mr:fr:cr}isTimeBuffered(t,e,r){let i,s;for(let n=0;n<r.length;n++){if(i=r.start(n)-this.bufferPadding,s=r.end(n)+this.bufferPadding,t>=i&&e<=s)return!0;if(e<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if("initSegment"===e.frag.sn||e.frag.bitrateTest)return;const r=e.frag,i=e.part?null:e,s=Er(r);this.fragments[s]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:r,part:i,timeRanges:s,type:n}=e;if("initSegment"===r.sn)return;const a=r.type;if(i){let t=this.activePartLists[a];t||(this.activePartLists[a]=t=[]),t.push(i)}this.timeRanges=s;const o=s[n];this.detectEvictedFragments(n,o,a,i)}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Er(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,r=Object.keys(e);if(!t)return r.length>0;for(let i=r.length;i--;){const s=e[r[i]];if((null==s?void 0:s.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,r,i,s){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==r||i&&!o.gap||o.start<e&&o.end>t&&(a.buffered||s)&&this.removeFragment(o)})}removeFragment(t){const e=Er(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const e=t.sn;this.activePartLists[t.type]=yr(r,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}}function vr(t){var e,r,i;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(r=t.range.audio)&&r.partial||null!=(i=t.range.audiovideo)&&i.partial)}function Er(t){return`${t.type}_${t.level}_${t.sn}`}function yr(t,e){return t.filter(t=>{const r=e(t);return r||t.clearElementaryStreamInfo(),r})}class Tr{decrypt(t,e){switch(this.aesMode){case Ce:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case xe:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}constructor(t,e,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=r}}class Sr{uint8ArrayToUint32Array_(t){const e=new DataView(t),r=new Uint32Array(4);for(let t=0;t<4;t++)r[t]=e.getUint32(4*t);return r}initTable(){const t=this.sBox,e=this.invSBox,r=this.subMix,i=r[0],s=r[1],n=r[2],a=r[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],u=o[3],c=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)c[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let r=g^g<<1^g<<2^g<<3^g<<4;r=r>>>8^255&r^99,t[f]=r,e[r]=f;const o=c[f],m=c[o],p=c[m];let v=257*c[r]^16843008*r;i[f]=v<<24|v>>>8,s[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[r]=v<<24|v>>>8,d[r]=v<<16|v>>>16,h[r]=v<<8|v>>>24,u[r]=v,f?(f=o^c[c[c[p^o]]],g^=c[c[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let r=!0,i=0;for(;i<e.length&&r;)r=e[i]===this.key[i],i++;if(r)return;this.key=e;const s=this.keySize=e.length;if(4!==s&&6!==s&&8!==s)throw new Error("Invalid aes key size="+s);const n=this.ksRows=4*(s+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),h=this.sBox,u=this.rcon,c=this.invSubMix,f=c[0],g=c[1],m=c[2],p=c[3];let v,E;for(a=0;a<n;a++)a<s?v=l[a]=e[a]:(E=v,a%s===0?(E=E<<8|E>>>24,E=h[E>>>24]<<24|h[E>>>16&255]<<16|h[E>>>8&255]<<8|h[255&E],E^=u[a/s|0]<<24):s>6&&a%s===4&&(E=h[E>>>24]<<24|h[E>>>16&255]<<16|h[E>>>8&255]<<8|h[255&E]),l[a]=v=(l[a-s]^E)>>>0);for(o=0;o<n;o++)a=n-o,E=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?E:f[h[E>>>24]]^g[h[E>>>16&255]]^m[h[E>>>8&255]]^p[h[255&E]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,r){const i=this.keySize+6,s=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],h=a[3],u=this.uint8ArrayToUint32Array_(r);let c=u[0],f=u[1],g=u[2],m=u[3];const p=new Int32Array(t),v=new Int32Array(p.length);let E,y,T,S,L,R,A,b,D,k,_,I,C,x;const w=this.networkToHostOrderSwap;for(;e<p.length;){for(D=w(p[e]),k=w(p[e+1]),_=w(p[e+2]),I=w(p[e+3]),L=D^s[0],R=I^s[1],A=_^s[2],b=k^s[3],C=4,x=1;x<i;x++)E=o[L>>>24]^l[R>>16&255]^d[A>>8&255]^h[255&b]^s[C],y=o[R>>>24]^l[A>>16&255]^d[b>>8&255]^h[255&L]^s[C+1],T=o[A>>>24]^l[b>>16&255]^d[L>>8&255]^h[255&R]^s[C+2],S=o[b>>>24]^l[L>>16&255]^d[R>>8&255]^h[255&A]^s[C+3],L=E,R=y,A=T,b=S,C+=4;E=n[L>>>24]<<24^n[R>>16&255]<<16^n[A>>8&255]<<8^n[255&b]^s[C],y=n[R>>>24]<<24^n[A>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^s[C+1],T=n[A>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&R]^s[C+2],S=n[b>>>24]<<24^n[L>>16&255]<<16^n[R>>8&255]<<8^n[255&A]^s[C+3],v[e]=w(E^c),v[e+1]=w(S^f),v[e+2]=w(T^g),v[e+3]=w(y^m),c=D,f=k,g=_,m=I,e+=4}return v.buffer}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()}}class Lr{expandKey(){const t=function(t){switch(t){case Ce:return"AES-CBC";case xe:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}constructor(t,e,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=r}}class Rr{destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const r=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,r=e&&new DataView(t.buffer).getUint8(e-1);return r?t.slice(0,e-r):t}(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,r,i){return this.useSoftware?new Promise((s,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,r,i);const o=this.flush();o?s(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,r,i)}softwareDecrypt(t,e,r,i){const{currentIV:s,currentResult:n,remainderData:a}=this;if(i!==Ce||16!==e.byteLength)return _.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Et(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;s&&(r=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Sr),l.expandKey(e);const d=n;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,d||null}webCryptoDecrypt(t,e,r,i){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,r,i));this.key=e,this.fastAesKey=new Lr(this.subtle,e,i)}return this.fastAesKey.expandKey().then(e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Tr(this.subtle,new Uint8Array(r),i).decrypt(t.buffer,e)}).catch(s=>(_.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(t,e,r,i)))}onWebCryptoError(t,e,r,i){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,r,i);const s=this.flush();if(s)return s.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const r=t.length-t.length%16;return r!==t.length&&(e=t.slice(0,r),this.remainderData=t.slice(r)),e}logOnce(t){this.logEnabled&&(_.log(`[decrypter]: ${t}`),this.logEnabled=!1)}constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}}const Ar=Math.pow(2,17);class br{destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const r=t.url;if(!r)return Promise.reject(new _r({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,s=i.fLoader,n=i.loader;return new Promise((l,d)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void d(kr(t));t.gap=!1}const h=this.loader=s?new s(i):new n(i),u=Dr(t);t.loader=h;const c=de(i.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Ar};t.stats=h.stats;const g={onSuccess:(e,r,i,s)=>{this.resetLoader(t,h);let n=e.data;i.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),l({frag:t,part:null,payload:n,networkDetails:s})},onError:(e,i,s,n)=>{this.resetLoader(t,h),d(new _r({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:S({url:r,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:s,stats:n}))},onAbort:(e,r,i)=>{this.resetLoader(t,h),d(new _r({type:a.NETWORK_ERROR,details:o.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:i,stats:e}))},onTimeout:(e,r,i)=>{this.resetLoader(t,h),d(new _r({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:i,stats:e}))}};e&&(g.onProgress=(r,i,s,n)=>e({frag:t,part:null,payload:s,networkDetails:n})),h.load(u,f,g)})}loadPart(t,e,r){this.abort();const i=this.config,s=i.fLoader,n=i.loader;return new Promise((l,d)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void d(kr(t,e));const h=this.loader=s?new s(i):new n(i),u=Dr(t,e);t.loader=h;const c=de(i.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ar};e.stats=h.stats,h.load(u,f,{onSuccess:(i,s,n,a)=>{this.resetLoader(t,h),this.updateStatsFromPart(t,e);const o={frag:t,part:e,payload:i.data,networkDetails:a};r(o),l(o)},onError:(r,i,s,n)=>{this.resetLoader(t,h),d(new _r({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:S({url:u.url,data:void 0},r),error:new Error(`HTTP Error ${r.code} ${r.text}`),networkDetails:s,stats:n}))},onAbort:(r,i,s)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,h),d(new _r({type:a.NETWORK_ERROR,details:o.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:s,stats:r}))},onTimeout:(r,i,s)=>{this.resetLoader(t,h),d(new _r({type:a.NETWORK_ERROR,details:o.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:s,stats:r}))}})})}updateStatsFromPart(t,e){const r=t.stats,i=e.stats,s=i.total;if(r.loaded+=i.loaded,s){const i=Math.round(t.duration/e.duration),n=Math.min(Math.round(r.loaded/s),i),a=(i-n)*Math.round(r.loaded/n);r.total=r.loaded+a}else r.total=Math.max(r.loaded,r.total);const n=r.loading,a=i.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}}function Dr(t,e=null){const r=e||t,s={frag:t,part:e,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;if(i(n)&&i(a)){var o;let e=n,r=a;if("initSegment"===t.sn&&("AES-128"===(l=null==(o=t.decryptdata)?void 0:o.method)||"AES-256"===l)){const t=a-n;t%16&&(r=a+(16-t%16)),0!==n&&(s.resetIV=!0,e=n-16)}s.rangeStart=e,s.rangeEnd=r}var l;return s}function kr(t,e){const r=new Error(`GAP ${t.gap?"tag":"attribute"} found`),i={type:a.MEDIA_ERROR,details:o.FRAG_GAP,fatal:!1,frag:t,error:r,networkDetails:null};return e&&(i.part=e),(e||t).stats.aborted=!0,new _r(i)}class _r extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Ir extends L{destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}constructor(t,e){super(t,e),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}}class Cr{constructor(t,e,r,i=0,s=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=r,this.size=i,this.part=s,this.partial=n}}const xr={length:0,start:()=>0,end:()=>0};class wr{static isBuffered(t,e){if(t){const r=wr.getBuffered(t);for(let t=r.length;t--;)if(e>=r.start(t)&&e<=r.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=wr.getBuffered(t);return wr.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let r=0;r<t.length;r++)e.push({start:t.start(r),end:t.end(r)});return e}static bufferInfo(t,e,r){if(t){const i=wr.bufferedRanges(t);if(i.length)return wr.bufferedInfo(i,e,r)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,r){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let i=-1,s=[];if(r)for(let n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(i=n);const a=s.length;if(a){const e=s[a-1].end;t[n].start-e<r?t[n].end>e&&(s[a-1].end=t[n].end):s.push(t[n])}else s.push(t[n])}else s=t;let n,a=0,o=e,l=e;for(let t=0;t<s.length;t++){const d=s[t].start,h=s[t].end;if(-1===i&&e>=d&&e<=h&&(i=t),e+r>=d&&e<h)o=d,l=h,a=l-e;else if(e+r<d){n=d;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:i}}static getBuffered(t){try{return t.buffered||xr}catch(t){return _.log("failed to get media.buffered",t),xr}}}function Pr(t,e){for(let i=0,s=t.length;i<s;i++){var r;if((null==(r=t[i])?void 0:r.cc)===e)return t[i]}return null}function Or(t,e){const r=t.start+e;t.startPTS=r,t.setStart(r),t.endPTS=r+t.duration}function Fr(t,e){const r=e.fragments;for(let e=0,i=r.length;e<i;e++)Or(r[e],t);e.fragmentHint&&Or(e.fragmentHint,t),e.alignedSliding=!0}function Mr(t,e){t&&(!function(t,e){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const r=Math.min(e.endCC,t.endCC),i=Pr(e.fragments,r),s=Pr(t.fragments,r);if(!i||!s)return;_.log(`Aligning playlist at start of dicontinuity sequence ${r}`);Fr(i.start-s.start,t)}(e,t),e.alignedSliding||function(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const r=t.fragments,i=e.fragments;if(!r.length||!i.length)return;let s,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(s=Pr(i,a),n=Pr(r,a));s&&n||(s=i[Math.floor(i.length/2)],n=Pr(r,s.cc)||r[Math.floor(r.length/2)]);const o=s.programDateTime,l=n.programDateTime;if(!o||!l)return;Fr((l-o)/1e3-(n.start-s.start),t)}(e,t),e.alignedSliding||e.skippedSegments||ir(t,e,!1))}function Nr(t,e,r){Br(t,e,r),t.addEventListener(e,r)}function Br(t,e,r){t.removeEventListener(e,r)}const $r=function(t){let e="";const r=t.length;for(let i=0;i<r;i++)e+=`[${t.start(i).toFixed(3)}-${t.end(i).toFixed(3)}]`;return e},Ur="STOPPED",Gr="IDLE",Vr="KEY_LOADING",Hr="FRAG_LOADING",Kr="FRAG_LOADING_WAITING_RETRY",Yr="PARSING",Wr="PARSED",jr="ENDED",qr="ERROR",Xr="WAITING_LEVEL";class zr extends Ir{registerListeners(){const{hls:t}=this;t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(l.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===Ur)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Ur}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;return-1===e&&t?t:e}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const r=t.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;const s=t.buffered;this.config.maxBufferHole&&s&&s.length>1&&(t=wr.bufferedInfo(s,t.start,0));const n=t.nextStart;if(n&&n>i&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return wr.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const r=this.media=this.mediaBuffer=e.media;Nr(r,"seeking",this.onMediaSeeking),Nr(r,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===Ur&&this.startLoad(i.startPosition)}onMediaDetaching(t,e){const r=!!e.transferMedia,i=this.media;if(null!==i){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Br(i,"seeking",this.onMediaSeeking),Br(i,"ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Ur,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,r){this.startFragRequested=!0,this._loadFragForPlayback(t,e,r)}_loadFragForPlayback(t,e,r){this._doFragLoad(t,e,r,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)}) was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,r=t.frag;this.fragContextChanged(r)?(e===Hr||!this.fragCurrent&&e===Yr)&&(this.fragmentTracker.removeFragment(r),this.state=Gr):("payload"in t&&(this.log(`Loaded ${r.type} sn: ${r.sn} of ${this.playlistLabel()} ${r.level}`),this.hls.trigger(l.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==Ur&&this.state!==qr&&(this.warn(`Frag error: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:r}=this;if(r.getState(t)===fr){const e=t.type,i=this.getFwdBufferInfo(this.mediaBuffer,e),s=Math.max(t.duration,i?i.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(s,t.duration))&&r.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?r.removeAllFragments():r.hasParts(t.type)&&(r.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),r.getState(t)===gr&&r.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,r=null){if(!(t-e))return;const i={startOffset:t,endOffset:e,type:r};this.hls.trigger(l.BUFFER_FLUSHING,i)}_loadInitSegment(t,e){this._doFragLoad(t,e).then(t=>{const e=null==t?void 0:t.frag;if(!e||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return t}).then(t=>{const{hls:e}=this,{frag:r,payload:i}=t,s=r.decryptdata;if(i&&i.byteLength>0&&null!=s&&s.key&&s.iv&&we(s.method)){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(i),s.key.buffer,s.iv.buffer,Pe(s.method)).catch(t=>{throw e.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:r}),t}).then(i=>{const s=self.performance.now();return e.trigger(l.FRAG_DECRYPTED,{frag:r,payload:i,stats:{tstart:n,tdecrypt:s}}),t.payload=i,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)}).catch(e=>{this.state!==Ur&&this.state!==qr&&(this.warn(e),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const r=t.frag.stats;this.state!==Ur&&(this.state=Gr),t.frag.data=new Uint8Array(t.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,e){var r,i;const s=t.tracks;if(s&&!e.encrypted&&(null!=(r=s.audio)&&r.encrypted||null!=(i=s.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,r=new Error("EME not supported (light build)");return this.warn(r.message),!t||t.mediaKeys?!1:(this.hls.trigger(l.ERROR,{type:a.KEY_SYSTEM_ERROR,details:o.KEY_SYSTEM_NO_KEYS,fatal:!0,error:r,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${r?$r(wr.getBuffered(r)):"(detached)"})`),Q(t)){var i;if(t.type!==m){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=Gr)}const e=null==(i=this.levels)?void 0:i[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=Gr}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:r,part:i,partsLoaded:s}=t,n=!s||0===s.length||s.some(t=>!t),a=new Cr(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,r=null,s){var n;this.fragCurrent=t;const a=e.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(!t.encrypted||null!=(n=t.decryptdata)&&n.key)t.encrypted||(o=this.keyLoader.loadClear(t,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));else if(this.log(`Loading key for ${t.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=Vr,this.fragCurrent=t,o=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(l.KEY_LOADED,t),this.state===Vr&&(this.state=Gr),t}),this.hls.trigger(l.KEY_LOADING,{frag:t}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null);const d=this.fragPrevious;if(Q(t)&&(!d||t.sn!==d.sn)){const r=this.shouldLoadParts(e.details,t.end);r!==this.loadingParts&&(this.log(`LL-Part loading ${r?"ON":"OFF"} loading sn ${null==d?void 0:d.sn}->${t.sn}`),this.loadingParts=r)}if(r=Math.max(t.start,r||0),this.loadingParts&&Q(t)){const i=a.partList;if(i&&s){r>a.fragmentEnd&&a.fragmentHint&&(t=a.fragmentHint);const n=this.getNextPart(i,t,r);if(n>-1){const d=i[n];let h;return t=this.fragCurrent=d.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${d.index} (${n}/${i.length-1}) of ${this.fragInfo(t,!1,d)}) cc: ${t.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=Hr,h=o?o.then(r=>!r||this.fragContextChanged(r.frag)?null:this.doFragPartsLoad(t,d,e,s)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,d,e,s).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(l.FRAG_LOADING,{frag:t,part:d,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(i,r))return Promise.resolve(null)}}var h;if(Q(t)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${null==(h=a.partList)?void 0:h.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),i(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Hr;const u=this.config.progressive&&t.type!==m;let c;return c=u&&o?o.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,s)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,u?s:void 0),o]).then(([t])=>(!u&&s&&s(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(l.FRAG_LOADING,{frag:t,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(t,e,r,i){return new Promise((s,n)=>{var a;const o=[],d=null==(a=r.details)?void 0:a.partList,h=e=>{this.fragmentLoader.loadPart(t,e,i).then(i=>{o[e.index]=i;const n=i.part;this.hls.trigger(l.FRAG_LOADED,i);const a=ar(r.details,t.sn,e.index+1)||or(d,t.sn,e.index+1);if(!a)return s({frag:t,part:n,partsLoaded:o});h(a)}).catch(n)};h(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===o.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===a.KEY_SYSTEM_ERROR?(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)):this.hls.trigger(l.ERROR,e)}else this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==Yr)return void(this.fragCurrent||this.state===Ur||this.state===qr||(this.state=Gr));const{frag:r,part:i,level:s}=e,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&r.sn>a.endSN||this.shouldLoadParts(a,r.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(r,i,s,t.partial)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var r;const s=t.partList[0];if(s.fragment.type===m)return!1;if(e>=s.end+((null==(r=t.fragmentHint)?void 0:r.duration)||0)){var i;if((this.hls.hasEnoughToStart?(null==(i=this.media)?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:r}=this,{level:i,sn:s,part:n}=t;if(null==e||!e[i])return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=e[i],o=a.details,l=n>-1?ar(o,s,n):null,d=l?l.fragment:nr(o,s,r);return d?(r&&r!==d&&(d.stats=r.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(t,e,r,i,s){if(this.state!==Yr)return;const{data1:n,data2:a}=t;let o=n;if(a&&(o=Et(n,a)),!o.length)return;const d=this.initPTS[e.cc],h=d?-d.baseTime/d.timescale:void 0,u={type:t.type,frag:e,part:r,chunkMeta:i,offset:h,parent:e.type,data:o};if(this.hls.trigger(l.BUFFER_APPENDING,u),t.dropped&&t.independent&&!r){if(s)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!wr.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const r=e.currentTime,i=wr.bufferInfo(e,r,0),s=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),a=Math.max(Math.min(t.start-n,i.end-n),r+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var r;const s=this.getLoadPosition();if(!i(s))return null;const n=this.lastCurrentTime>s||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,s,e,n)}getFwdBufferInfoAtPos(t,e,r,i){const s=wr.bufferInfo(t,e,i);if(0===s.len&&void 0!==s.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,r);if(n&&(s.nextStart<=n.end||n.gap)){const r=Math.max(Math.min(s.nextStart,n.end)-e,i);return wr.bufferInfo(t,e,r)}}return s}getMaxBufferLength(t){const{config:e}=this;let r;return r=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(r,e.maxMaxBufferLength)}exceedsMaxBuffer(t,e,r){const i=t.nextStart;if(i&&r.start>i){const i=t.buffered;if(i){let s=t.len;const n=t.bufferedIndex;for(let t=i.length-1;t>n;t--)i[t].start<r.start&&(s+=i[t].end-i[t].start);return s>=e}}return!1}reduceMaxBufferLength(t,e){const r=this.config,i=Math.max(Math.min(t-e,r.maxBufferLength),e),s=Math.max(t-3*e,r.maxMaxBufferLength/2,i);return s>=i&&(r.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0)}getAppendedFrag(t,e=f){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,e):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(t,e){const r=e.fragments,i=r.length;if(!i)return null;const{config:s}=this,n=e.fragmentStart,a=s.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const r=s.initialLiveManifestSize;if(i<r)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${r})`),null;if(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(e);const r=this.config.startPosition,i=this.hls.startPosition,s=this.hls.liveSyncPosition,d=(null==(l=o)?void 0:l.start)||0;let h,u;-1!==i&&i>=n?(h=i,u=i===r?"config":"next load start"):null!==s?(h=s,u="live edge"):(h=t,u="buffer pos"),h<d&&(h=d,u="live frag start"),h<n&&(h=n,u="playlist start"),this.startPosition==h&&this.nextLoadPosition==h||(this.log(`Setting startPosition to ${h.toFixed(3)} ${-1===i?"":`(from ${r}) `}based on ${u}. live edge: ${s} live frag start: ${d.toFixed(3)} playlist start: ${n.toFixed(3)} buffer pos: ${t}`),this.startPosition=this.nextLoadPosition=h)}}else t<=n&&(o=r[0]);if(!o){const r=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,r,e)}let d=this.filterReplacedPrimary(o,e);if(!d&&o){const t=o.sn-e.startSN;d=this.filterReplacedPrimary(r[t+1]||null,e)}return this.mapToInitFragWhenRequired(d)}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;const r=this.fragmentTracker.getState(t);return r===mr||r===gr&&!!t.gap}getNextFragmentLoopLoading(t,e,r,i,s){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&r.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==t&&r.len+t.len>=s){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){return this.config,!1}filterReplacedPrimary(t,e){return t?(this.config,t):t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,r){let i=-1,s=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,i>-1&&r<o.start)break;const l=o.loaded;l?i=-1:(s||(o.independent||n)&&o.fragment===e)&&(o.fragment!==e&&this.warn(`Need buffer at ${r} but next unloaded part starts at ${o.start}`),i=a),s=l}return i}loadedEndOfParts(t,e){let r;for(let i=t.length;i--;){if(r=t[i],!r.loaded)return!1;if(e>r.start)return!0}return!1}getInitialLiveFragment(t){const e=t.fragments,r=this.fragPrevious;let s=null;if(r){if(t.hasProgramDateTime&&(s=function(t,e,r){if(null===e||!Array.isArray(t)||!t.length||!i(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;for(let i=0;i<t.length;++i){const s=t[i];if(ie(e,r,s))return s}return null}(e,r.endProgramDateTime,this.config.maxFragLookUpTolerance),s&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`)),!s){const i=r.sn+1;if(i>=t.startSN&&i<=t.endSN){const n=e[i-t.startSN];r.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=function(t,e,r){if(t&&t.startCC<=e&&t.endCC>=e){let i=t.fragments;const{fragmentHint:s}=t;let n;return s&&(i=i.concat(s)),te(i,t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=r?1:t.start>r?-1:0)),n||null}return null}(t,r.cc,r.end),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(s=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return s}getFragmentAtPosition(t,e,r){const{config:i}=this;let{fragPrevious:s}=this,{fragments:n,endSN:a}=r;const{fragmentHint:o}=r,{maxFragLookUpTolerance:l}=i,d=r.partList,h=!!(this.loadingParts&&null!=d&&d.length&&o);let u;if(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),t<e){var c;u=ee(s,n,t,t<this.lastCurrentTime||t>e-l||null!=(c=this.media)&&c.paused||!this.startFragRequested?0:l)}else u=n[n.length-1];if(u){const t=u.sn-r.startSN,e=this.fragmentTracker.getState(u);if((e===mr||e===gr&&u.gap)&&(s=u),s&&u.sn===s.sn&&(!h||d[0].fragment.sn>u.sn||!r.live)){if(u.level===s.level){const e=n[t+1];u=u.sn<a&&this.fragmentTracker.getState(e)!==mr?e:null}}}return u}alignPlaylists(t,e,r){const s=t.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const n=t.fragmentStart,a=!e,o=t.alignedSliding&&i(n);if(a||!o&&!n){Mr(r,t);const i=t.fragmentStart;return this.log(`Live playlist sliding: ${i.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${s}`),i}return n}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let r=this.startPosition;r<e&&(r=-1);const s=this.timelineOffset;if(-1===r){const n=null!==this.startTimeOffset,a=n?this.startTimeOffset:t.startTimeOffset;null!==a&&i(a)?(r=e+a,a<0&&(r+=t.edge),r=Math.min(Math.max(e,r),e+t.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=r):t.live?(r=this.hls.liveSyncPosition||e,this.log(`Setting startPosition to -1 to start at live edge ${r}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+s}this.nextLoadPosition=r+s}getLoadPosition(){var t;const{media:e}=this;let r=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e?r=e.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&Q(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===Kr)||(this.state=Gr)}onFragmentOrKeyLoadError(t,e){var r;if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const i=e.frag;if(!i||i.type!==t||!this.levels)return;var s;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.url} > ${null==(s=this.fragCurrent)?void 0:s.url}`);const n=e.details===o.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=e.errorAction;if(!a)return void(this.state=qr);const{action:l,flags:d,retryCount:h=0,retryConfig:u}=a,c=!!u,f=c&&l===me,g=c&&!a.resolved&&d===ve,m=null==(r=this.hls.latestLevelDetails)?void 0:r.live;if(!f&&g&&Q(i)&&!i.endList&&m&&!ae(e))this.resetFragmentErrors(t),this.treatAsGap(i),a.resolved=!0;else if((f||g)&&h<u.maxNumRetry){var p;const r=ue(null==(p=e.response)?void 0:p.code),s=le(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+s,this.state=Kr,a.resolved=!0,r)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${s}ms`)}else if(u){if(this.resetFragmentErrors(t),!(h<u.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${h})`);n||l===ge||(a.resolved=!0)}else this.state=l===fe?Xr:qr;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,r=e===1/0;(!e||t>=e||r&&!ue(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Gr)}reduceLengthAndFlushBuffer(t){if(this.state===Yr||this.state===Wr){const e=t.frag,r=t.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len,(null==e?void 0:e.duration)||10);const n=!s;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${r} buffer`),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===g&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Ur&&(this.state=Gr)}afterBufferFlushed(t,e,r){if(!t)return;const i=wr.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,r),this.state===jr&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Ur&&(this.state=Gr)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,e=t?t.details:null;null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,r,i){const s=r.details;if(!s)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce((e,n)=>{const a=t.elementaryStreams[n];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${o})`),e||!1;const d=i?0:tr(s,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS,this);return this.hls.trigger(l.LEVEL_PTS_UPDATED,{details:s,level:r,drift:d,type:n,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e},!1)){var n;const e=null===(null==(n=this.transmuxer)?void 0:n.error);if((0===r.fragmentError||e&&(r.fragmentError<2||t.endList))&&this.treatAsGap(t,r),e){const e=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Wr,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)})`),this.hls.trigger(l.FRAG_PARSED,{frag:t,part:e})}playlistLabel(){return this.playlistType===f?"level":"track"}fragInfo(t,e=!0,r){var i,s;return`${this.playlistLabel()} ${t.level} (${r?"part":"frag"}:[${(null!=(i=e&&!r?t.startPTS:(r||t).start)?i:NaN).toFixed(3)}-${(null!=(s=e&&!r?t.endPTS:(r||t).end)?s:NaN).toFixed(3)}]${r&&"main"===t.type?"INDEPENDENT="+(r.independent?"YES":"NO"):""}`}treatAsGap(t,e){e&&e.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}constructor(t,e,r,s,n){super(s,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Ur,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:e,media:r,mediaBuffer:s,state:n}=this,a=r?r.currentTime:0,o=wr.bufferInfo(s||r,a,t.maxBufferHole),l=!o.len;if(this.log(`Media seeking to ${i(a)?a.toFixed(3):a}, state: ${n}, ${l?"out of":"in"} buffer`),this.state===jr)this.resetLoadingState();else if(e){const r=t.maxFragLookUpTolerance,i=e.start-r,s=e.start+e.duration+r;if(l||s<o.start||i>o.end){const t=a>s;(a<i||t)&&(t&&e.loader&&(this.log(`Cancelling fragment load for seek (sn: ${e.sn})`),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(r){this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0);if(a>this.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts){const t=Math.max(o.end,a),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${a.toFixed(2)} with buffer @${t.toFixed(2)}`),this.loadingParts=e)}}this.hls.hasEnoughToStart||(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${a} for seek without enough to start`),this.nextLoadPosition=a,l&&(this.startPosition=a)),l&&this.state===Gr&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=t,this.fragmentLoader=new br(t.config),this.keyLoader=r,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Rr(t.config)}}class Qr{destroy(){this.tracks=this.queues=null}append(t,e,r){if(null===this.queues||null===this.tracks)return;const i=this.queues[e];i.push(t),1!==i.length||r||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const r={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const r={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(r)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const r=null==(e=t[0])?void 0:e.label;"async-blocker"!==r&&"async-blocker-prepend"!==r||(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(null===this.queues)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const i=e[0];try{i.execute()}catch(e){var r;if(i.onError(e),null===this.queues||null===this.tracks)return;const s=null==(r=this.tracks[t])?void 0:r.buffer;null!=s&&s.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,r;return null!=(e=this.queues)&&e[t]||null!=(r=this.tracks)&&r[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const r=null==(e=this.tracks)?void 0:e[t],i=null==r?void 0:r.buffer;return i?`SourceBuffer${i.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}}const Zr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Jr="HlsJsTrackRemovedError";class ti extends Error{constructor(t){super(t),this.name=Jr}}function ei(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function ri(t){return"audio"===t?1:0}class ii{setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(l.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(l.BUFFER_CODECS,this.onBufferCodecs,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(l.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(l.BUFFER_CODECS,this.onBufferCodecs,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const r=this.hls.levels[e.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const r=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,r.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&i(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,r=this.getMaxLevel(t.length-1);r!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${r}: ${t[r].height}p@${t[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=r,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const r=e.filter((e,r)=>this.isLevelAllowed(e)&&r<=t);return this.clientRect=null,ii.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,r){if(null==t||!t.length)return-1;const i=(t,e)=>!e||(t.width!==e.width||t.height!==e.height);let s=t.length-1;const n=Math.max(e,r);for(let e=0;e<t.length;e+=1){const r=t[e];if((r.width>=n||r.height>=n)&&i(r,t[e+1])){s=e;break}}return s}constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}}function si(t,e,r,i){t&&Object.keys(e).forEach(s=>{const n=t.filter(t=>t.groupId===s).map(t=>{const n=y({},t);return n.details=void 0,n.attrs=new Re(n.attrs),n.url=n.attrs.URI=ni(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),n.groupId=n.attrs["GROUP-ID"]=e[s],n.attrs["PATHWAY-ID"]=i,n});t.push(...n)})}function ni(t,e,r,i){const{HOST:s,PARAMS:n,[r]:a}=i;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return s&&!o&&(l.host=s),n&&Object.keys(n).sort().forEach(t=>{t&&l.searchParams.set(t,n[t])}),l.href}var ai,oi={exports:{}};var li=(ai||(ai=1,function(t){var e=Object.prototype.hasOwnProperty,r="~";function i(){}function s(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function n(t,e,i,n,a){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new s(i,n||t,a),l=r?r+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0===--t._eventsCount?t._events=new i:delete t._events[e]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var t,i,s=[];if(0===this._eventsCount)return s;for(i in t=this._events)e.call(t,i)&&s.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(t)):s},o.prototype.listeners=function(t){var e=r?r+t:t,i=this._events[e];if(!i)return[];if(i.fn)return[i.fn];for(var s=0,n=i.length,a=new Array(n);s<n;s++)a[s]=i[s].fn;return a},o.prototype.listenerCount=function(t){var e=r?r+t:t,i=this._events[e];return i?i.fn?1:i.length:0},o.prototype.emit=function(t,e,i,s,n,a){var o=r?r+t:t;if(!this._events[o])return!1;var l,d,h=this._events[o],u=arguments.length;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),u){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,i),!0;case 4:return h.fn.call(h.context,e,i,s),!0;case 5:return h.fn.call(h.context,e,i,s,n),!0;case 6:return h.fn.call(h.context,e,i,s,n,a),!0}for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var c,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(t,h[d].fn,void 0,!0),u){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,e);break;case 3:h[d].fn.call(h[d].context,e,i);break;case 4:h[d].fn.call(h[d].context,e,i,s);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];h[d].fn.apply(h[d].context,l)}}return!0},o.prototype.on=function(t,e,r){return n(this,t,e,r,!1)},o.prototype.once=function(t,e,r){return n(this,t,e,r,!0)},o.prototype.removeListener=function(t,e,i,s){var n=r?r+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||s&&!o.once||i&&o.context!==i||a(this,n);else{for(var l=0,d=[],h=o.length;l<h;l++)(o[l].fn!==e||s&&!o[l].once||i&&o[l].context!==i)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=r?r+t:t,this._events[e]&&a(this,e)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,t.exports=o}(oi)),oi.exports),di=I(li);class hi{push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let r;return t.length?(r=1===t.length?t[0]:function(t,e){const r=new Uint8Array(e);let i=0;for(let e=0;e<t.length;e++){const s=t[e];r.set(s,i),i+=s.length}return r}(t,e),this.reset(),r):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}constructor(){this.chunks=[],this.dataLength=0}}function ui(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function ci(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function fi(t,e){let r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3],r}function gi(t,e){const r=e;let i=0;for(;ci(t,e);){i+=10;i+=fi(t,e+6),ui(t,e+10)&&(i+=10),e+=i}if(i>0)return t.subarray(r,r+i)}function mi(t,e){return 255===t[e]&&240==(246&t[e+1])}function pi(t,e){return 1&t[e+1]?7:9}function vi(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Ei(t,e){return e+1<t.length&&mi(t,e)}function yi(t,e){if(Ei(t,e)){const r=pi(t,e);if(e+r>=t.length)return!1;const i=vi(t,e);if(i<=r)return!1;const s=e+i;return s===t.length||Ei(t,s)}return!1}function Ti(t,e,r,i,s){if(!t.samplerate){const n=function(t,e,r,i){const s=e[r+2],n=s>>2&15;if(n>12){const e=new Error(`invalid ADTS sampling index:${n}`);return void t.emit(l.ERROR,l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const d=1+(s>>6&3),h=e[r+3]>>6&3|(1&s)<<2,u="mp4a.40."+d,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n];let f=n;5!==d&&29!==d||(f-=3);const g=[d<<3|(14&f)>>1,(1&f)<<7|h<<3];return _.log(`manifest codec:${i}, parsed codec:${u}, channels:${h}, rate:${c} (ADTS object type:${d} sampling index:${n})`),{config:g,samplerate:c,channelCount:h,codec:u,parsedCodec:u,manifestCodec:i}}(e,r,i,s);if(!n)return;y(t,n)}}function Si(t){return 9216e4/t}function Li(t,e,r,i,s){const n=i+s*Si(t.samplerate),a=function(t,e){const r=pi(t,e);if(e+r<=t.length){const i=vi(t,e)-r;if(i>0)return{headerLength:r,frameLength:i}}}(e,r);let o;if(a){const{frameLength:i,headerLength:s}=a,l=s+i,d=Math.max(0,r+l-e.length);d?(o=new Uint8Array(l-s),o.set(e.subarray(r+s,e.length),0)):o=e.subarray(r+s,r+l);const h={unit:o,pts:n};return d||t.samples.push(h),{sample:h,length:l,missing:d}}const l=e.length-r;o=new Uint8Array(l),o.set(e.subarray(r,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}function Ri(t,e){return ci(t,e)&&fi(t,e+6)+10<=t.length-e}function Ai(t,e=0,r=1/0){return function(t,e,r,i){const s=function(t){return t instanceof ArrayBuffer?t:t.buffer}(t);let n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);const a=(u=t,u&&u.buffer instanceof ArrayBuffer&&void 0!==u.byteLength&&void 0!==u.byteOffset?t.byteOffset:0),o=(a+t.byteLength)/n,l=(a+e)/n,d=Math.floor(Math.max(0,Math.min(l,o))),h=Math.floor(Math.min(d+Math.max(r,0),o));var u;return new i(s,d,h-d)}(t,e,r,Uint8Array)}function bi(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const r=t.data.subarray(1).indexOf(0);if(-1===r)return;const i=F(Ai(t.data,1,r)),s=t.data[2+r],n=t.data.subarray(3+r).indexOf(0);if(-1===n)return;const a=F(Ai(t.data,3+r,n));let o;return o="--\x3e"===i?F(Ai(t.data,4+r+n)):function(t){return t instanceof ArrayBuffer?t:0==t.byteOffset&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer}(t.data.subarray(4+r+n)),e.mimeType=i,e.pictureType=s,e.description=a,e.data=o,e}function Di(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=F(t.data,!0),r=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:r.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const r=F(t.data.subarray(e),!0);e+=r.length+1;const i=F(t.data.subarray(e));return{key:t.type,info:r,data:i}}const e=F(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?bi(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const r=F(t.data.subarray(e),!0);e+=r.length+1;const i=F(t.data.subarray(e));return{key:t.type,info:r,data:i}}const e=F(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function ki(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),r=fi(t,4);return{type:e,size:r,data:t.subarray(10,10+r)}}function _i(t){let e=0;const r=[];for(;ci(t,e);){const i=fi(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const s=e+i;for(;e+10<s;){const i=ki(t.subarray(e)),s=Di(i);s&&r.push(s),e+=i.size+10}ui(t,e)&&(e+=10)}return r}function Ii(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function Ci(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),r=1&e[3];let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,r&&(i+=47721858.84),Math.round(i)}}function xi(t){const e=_i(t);for(let t=0;t<e.length;t++){const r=e[t];if(Ii(r))return Ci(r)}}let wi=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function Pi(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Oi{resetInitSegment(t,e,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,r){}demux(t,e){this.cachedData&&(t=Et(this.cachedData,t),this.cachedData=null);let r,s=gi(t,0),n=s?s.length:0;const a=this._audioTrack,o=this._id3Track,l=s?xi(s):void 0,d=t.length;for((null===this.basePTS||0===this.frameIndex&&i(l))&&(this.basePTS=Fi(l,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:wi.audioId3,duration:Number.POSITIVE_INFINITY});n<d;){if(this.canParse(t,n)){const e=this.appendFrame(a,t,n);e?(this.frameIndex++,this.lastPTS=e.sample.pts,n+=e.length,r=n):n=d}else Ri(t,n)?(s=gi(t,n),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:wi.audioId3,duration:Number.POSITIVE_INFINITY}),n+=s.length,r=n):n++;if(n===d&&r!==d){const e=t.slice(r);this.cachedData?this.cachedData=Et(this.cachedData,e):this.cachedData=e}}return{audioTrack:a,videoTrack:Pi(),id3Track:o,textTrack:Pi()}}demuxSampleAes(t,e,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:Pi(),id3Track:this._id3Track,textTrack:Pi()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}}const Fi=(t,e,r)=>{if(i(t))return 90*t;return 9e4*e+(r?9e4*r.baseTime/r.timescale:0)};let Mi=null;const Ni=[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],Bi=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],$i=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Ui=[0,1,1,4];function Gi(t,e,r,i,s){if(r+24>e.length)return;const n=Vi(e,r);if(n&&r+n.frameLength<=e.length){const a=i+s*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(r,r+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Vi(t,e){const r=t[e+1]>>3&3,i=t[e+1]>>1&3,s=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==r&&0!==s&&15!==s&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Ni[14*(3===r?3-i:3===i?3:4)+s-1],d=Bi[3*(3===r?0:2===r?1:2)+n],h=3===o?1:2,u=$i[r][i],c=Ui[i],f=8*u*c,g=Math.floor(u*l/d+a)*c;if(null===Mi){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Mi=t?parseInt(t[1]):0}return!!Mi&&Mi<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function Hi(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function Ki(t,e){return e+1<t.length&&Hi(t,e)}function Yi(t,e){if(e+1<t.length&&Hi(t,e)){const r=4,i=Vi(t,e);let s=r;null!=i&&i.frameLength&&(s=i.frameLength);const n=e+s;return n===t.length||Ki(t,n)}return!1}const Wi=/\/emsg[-/]ID3/i;function ji(t,e){return i(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}class qi{decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,Ce)}decryptAacSample(t,e,r){const i=t[e].unit;if(i.length<=16)return;const s=i.subarray(16,i.length-i.length%16),n=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(n).then(s=>{const n=new Uint8Array(s);i.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,r)}).catch(r)}decryptAacSamples(t,e,r){for(;;e++){if(e>=t.length)return void r();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e);let i=0;for(let e=32;e<t.length-16;e+=160,i+=16)r.set(t.subarray(e,e+16),i);return r}getAvcDecryptedUnit(t,e){const r=new Uint8Array(e);let i=0;for(let e=32;e<t.length-16;e+=160,i+=16)t.set(r.subarray(i,i+16),e);return t}decryptAvcSample(t,e,r,i,s){const n=Rt(s.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{s.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,r+1,i)}).catch(i)}decryptAvcSamples(t,e,r,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,r=0){if(e>=t.length)return void i();const s=t[e].units;for(;!(r>=s.length);r++){const n=s[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,r,i,n),this.decrypter.isSync())))return}}}constructor(t,e,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Rr(e,{removePKCS7Padding:!1})}}class Xi{createVideoSample(t,e,r){return{key:t,frame:!1,pts:e,dts:r,units:[],length:0}}getLastNalUnit(t){var e;let r,i=this.VideoSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){const t=i.units;r=t[t.length-1]}return r}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const r=e.samples,i=r.length;if(!i)return void e.dropped++;{const e=r[i-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,r){const i=e.byteLength;let s=t.naluState||0;const n=s,a=[];let o,l,d,h=0,u=-1,c=0;for(-1===s&&(u=0,c=this.getNALuType(e,0),s=0,h=1);h<i;)if(o=e[h++],s)if(1!==s)if(o)if(1===o){if(l=h-s-1,u>=0){const t={data:e.subarray(u,l),type:c};a.push(t)}else{const r=this.getLastNalUnit(t.samples);r&&(n&&h<=4-n&&r.state&&(r.data=r.data.subarray(0,r.data.byteLength-n)),l>0&&(r.data=Et(r.data,e.subarray(0,l)),r.state=0))}h<i?(d=this.getNALuType(e,h),u=h,c=d,s=0):s=-1}else s=0;else s=3;else s=o?0:2;else s=o?0:1;if(u>=0&&s>=0){const t={data:e.subarray(u,i),type:c,state:s};a.push(t)}if(0===a.length){const r=this.getLastNalUnit(t.samples);r&&(r.data=Et(r.data,e))}return t.naluState=s,a}constructor(){this.VideoSample=null}}class zi{loadWord(){const t=this.data,e=this.bytesAvailable,r=t.byteLength-e,i=new Uint8Array(4),s=Math.min(4,e);if(0===s)throw new Error("no bytes available");i.set(t.subarray(r,r+s)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const r=this.word>>>32-e;if(t>32&&_.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?r<<e|this.readBits(e):r}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}}class Qi extends Xi{parsePES(t,e,r,i){const s=this.parseNALu(t,r.data,i);let n,a=this.VideoSample,o=!1;r.data=null,a&&s.length&&!t.audFound&&(this.pushAccessUnit(a,t),a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(i=>{var s,l;switch(i.type){case 1:{let e=!1;n=!0;const s=i.data;if(o&&s.length>4){const t=this.readSliceType(s);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var d;if(e)null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.frame=!0,a.key=e;break}case 5:n=!0,null!=(s=a)&&s.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,Lt(i.data,1,r.pts,e.samples);break;case 7:{var h,u;n=!0,o=!0;const e=i.data,r=this.readSPS(e);if(!t.sps||t.width!==r.width||t.height!==r.height||(null==(h=t.pixelRatio)?void 0:h[0])!==r.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==r.pixelRatio[1]){t.width=r.width,t.height=r.height,t.pixelRatio=r.pixelRatio,t.sps=[e];const i=e.subarray(1,4);let s="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),s+=e}t.codec=s}break}case 8:n=!0,t.pps=[i.data];break;case 9:n=!0,t.audFound=!0,null!=(l=a)&&l.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:n=!0;break;default:n=!1}if(a&&n){a.units.push(i)}}),i&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new zi(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let r,i=8,s=8;for(let n=0;n<t;n++)0!==s&&(r=e.readEG(),s=(i+r+256)%256),i=0===s?i:s}readSPS(t){const e=new zi(t);let r,i,s,n=0,a=0,o=0,l=0;const d=e.readUByte.bind(e),h=e.readBits.bind(e),u=e.readUEG.bind(e),c=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);d();const v=d();if(h(5),f(3),d(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=u();if(3===t&&f(1),m(),m(),f(1),c())for(i=3!==t?8:12,s=0;s<i;s++)c()&&p(s<6?16:64,e)}m();const E=u();if(0===E)u();else if(1===E)for(f(1),g(),g(),r=u(),s=0;s<r;s++)g();m(),f(1);const y=u(),T=u(),S=h(1);0===S&&f(1),f(1),c()&&(n=u(),a=u(),o=u(),l=u());let L=[1,1];if(c()&&c()){switch(d()){case 1:L=[1,1];break;case 2:L=[12,11];break;case 3:L=[10,11];break;case 4:L=[16,11];break;case 5:L=[40,33];break;case 6:L=[24,11];break;case 7:L=[20,11];break;case 8:L=[32,11];break;case 9:L=[80,33];break;case 10:L=[18,11];break;case 11:L=[15,11];break;case 12:L=[64,33];break;case 13:L=[160,99];break;case 14:L=[4,3];break;case 15:L=[3,2];break;case 16:L=[2,1];break;case 255:L=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(y+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:L}}}const Zi=188;class Ji{static probe(t,e){const r=Ji.syncOffset(t);return r>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),-1!==r}static syncOffset(t){const e=t.length;let r=Math.min(940,e-Zi)+1,i=0;for(;i<r;){let s=!1,n=-1,a=0;for(let o=i;o<e;o+=Zi){if(71!==t[o]||e-o!==Zi&&71!==t[o+Zi]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(r=Math.min(n+18612,t.length-Zi)+1)),s||(s=0===ts(t,o)),s&&a>1&&(0===n&&a>2||o+Zi>r))return n}i++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:it[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,r,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ji.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=Ji.createTrack("audio",i),this._id3Track=Ji.createTrack("id3"),this._txtTrack=Ji.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:r}=this;t&&(t.pesData=null),e&&(e.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,r=!1,i=!1){let s;r||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let d=n.pid,h=n.pesData,u=a.pid,c=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,E=t.length;if(this.remainderData&&(E=(t=Et(this.remainderData,t)).length,this.remainderData=null),E<Zi&&!i)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const y=Math.max(0,Ji.syncOffset(t));E-=(E-y)%Zi,E<t.byteLength&&!i&&(this.remainderData=new Uint8Array(t.buffer,E,t.buffer.byteLength-E));let T=0;for(let e=y;e<E;e+=Zi)if(71===t[e]){const i=!!(64&t[e+1]),E=ts(t,e);let T;if((48&t[e+3])>>4>1){if(T=e+5+t[e+4],T===e+Zi)continue}else T=e+4;switch(E){case d:i&&(h&&(s=ns(h,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,l,s,!1)),h={data:[],size:0}),h&&(h.data.push(t.subarray(T,e+Zi)),h.size+=e+Zi-T);break;case u:if(i){if(f&&(s=ns(f,this.logger)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,s);break;case"mp3":this.parseMPEGPES(a,s)}f={data:[],size:0}}f&&(f.data.push(t.subarray(T,e+Zi)),f.size+=e+Zi-T);break;case c:i&&(g&&(s=ns(g,this.logger))&&this.parseID3PES(o,s),g={data:[],size:0}),g&&(g.data.push(t.subarray(T,e+Zi)),g.size+=e+Zi-T);break;case 0:i&&(T+=t[T]+1),v=this._pmtId=es(t,T);break;case v:{i&&(T+=t[T]+1);const s=rs(t,T,this.typeSupported,r,this.observer,this.logger);d=s.videoPid,d>0&&(n.pid=d,n.segmentCodec=s.segmentVideoCodec),u=s.audioPid,u>0&&(a.pid=u,a.segmentCodec=s.segmentAudioCodec),c=s.id3Pid,c>0&&(o.pid=c),null===m||p||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${m}'. Backtracking to sync byte @${y} to parse all TS packets.`),m=null,e=y-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=E}}else T++;T>0&&is(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=h,a.pesData=f,o.pesData=g;const S={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return i&&this.extractRemainingSamples(S),S}flush(){const{remainderData:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:r,id3Track:i,textTrack:s}=t,n=r.pesData,a=e.pesData,o=i.pesData;let l;if(n&&(l=ns(n,this.logger))?(this.readyVideoParser(r.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(r,s,l,!0),r.pesData=null)):r.pesData=n,a&&(l=ns(a,this.logger))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l)}e.pesData=null}else null!=a&&a.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=ns(o,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=o}demuxSampleAes(t,e,r){const i=this.demux(t,r,!0,!this.config.progressive),s=this.sampleAes=new qi(this.observer,this.config,e);return this.decrypt(i,s)}readyVideoParser(t){null===this.videoParser&&"avc"===t&&(this.videoParser=new Qi)}decrypt(t,e){return new Promise(r=>{const{audioTrack:i,videoTrack:s}=t;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,()=>{s.samples?e.decryptAvcSamples(s.samples,0,0,()=>{r(t)}):r(t)}):s.samples&&e.decryptAvcSamples(s.samples,0,0,()=>{r(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,e){let r=0;const i=this.aacOverFlow;let s,n,a,o=e.data;if(i){this.aacOverFlow=null;const e=i.missing,s=i.sample.unit.byteLength;if(-1===e)o=Et(i.sample.unit,o);else{const n=s-e;i.sample.unit.set(o.subarray(0,e),n),t.samples.push(i.sample),r=i.missing}}for(s=r,n=o.length;s<n-1&&!Ei(o,s);s++);if(s!==r){let t;const e=s<n-1;if(t=e?`AAC PES did not start with ADTS header,offset:${s}`:"No ADTS header found in AAC PES",is(this.observer,new Error(t),e,this.logger),!e)return}if(Ti(t,this.observer,o,s,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!i)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Si(t.samplerate);a=i.sample.pts+e}}let l,d=0;for(;s<n;){if(l=Li(t,o,s,a,d),s+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;s<n-1&&!Ei(o,s);s++);}}parseMPEGPES(t,e){const r=e.data,i=r.length;let s=0,n=0;const a=e.pts;if(void 0!==a)for(;n<i;)if(Ki(r,n)){const e=Gi(t,r,n,a,s);if(!e)break;n+=e.length,s++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const r=y({},e,{type:this._videoTrack?wi.emsg:wi.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}constructor(t,e,r,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=r,this.logger=i,this.videoParser=null}}function ts(t,e){return((31&t[e+1])<<8)+t[e+2]}function es(t,e){return(31&t[e+10])<<8|t[e+11]}function rs(t,e,r,i,s,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<o;){const o=ts(t,e),l=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!i){ss("ADTS AAC",n);break}case 15:-1===a.audioPid&&(a.audioPid=o);break;case 21:-1===a.id3Pid&&(a.id3Pid=o);break;case 219:if(!i){ss("H.264",n);break}case 27:-1===a.videoPid&&(a.videoPid=o);break;case 3:case 4:r.mpeg||r.mp3?-1===a.audioPid&&(a.audioPid=o,a.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!i){ss("AC-3",n);break}case 129:n.warn("AC-3 in M2TS support not included in build");break;case 6:if(-1===a.audioPid&&l>0){let r=e+5,i=l;for(;i>2;){if(106===t[r])n.warn("AC-3 in M2TS support not included in build");const e=t[r+1]+2;r+=e,i-=e}}break;case 194:case 135:return is(s,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:return is(s,new Error("Unsupported HEVC in M2TS found"),void 0,n),a}e+=l+5}return a}function is(t,e,r,i){i.warn(`parsing error: ${e.message}`),t.emit(l.ERROR,l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:e,reason:e.message})}function ss(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function ns(t,e){let r,i,s,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Et(l[0],l[1]),l.splice(1,1);r=l[0];if(1===(r[0]<<16)+(r[1]<<8)+r[2]){if(i=(r[4]<<8)+r[5],i&&i>t.size-6)return null;const d=r[7];192&d&&(n=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&d?(a=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),s=r[8];let h=s+9;if(t.size<=h)return null;t.size-=h;const u=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){r=l[t];let e=r.byteLength;if(h){if(h>e){h-=e;continue}r=r.subarray(h),e-=h,h=0}u.set(r,o),o+=e}return i&&(i-=s+3),{data:u,pts:n,dts:a,len:i}}return null}class as{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const os=Math.pow(2,32)-1;class ls{static init(){let t;for(t in ls.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},ls.types)ls.types.hasOwnProperty(t)&&(ls.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);ls.HDLR_TYPES={video:e,audio:r};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);ls.STTS=ls.STSC=ls.STCO=s,ls.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),ls.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),ls.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),ls.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);ls.FTYP=ls.box(ls.types.ftyp,n,o,n,a),ls.DINF=ls.box(ls.types.dinf,ls.box(ls.types.dref,i))}static box(t,...e){let r=8,i=e.length;const s=i;for(;i--;)r+=e[i].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(t,4),i=0,r=8;i<s;i++)n.set(e[i],r),r+=e[i].byteLength;return n}static hdlr(t){return ls.box(ls.types.hdlr,ls.HDLR_TYPES[t])}static mdat(t){return ls.box(ls.types.mdat,t)}static mdhd(t,e){e*=t;const r=Math.floor(e/(os+1)),i=Math.floor(e%(os+1));return ls.box(ls.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,i>>24,i>>16&255,i>>8&255,255&i,85,196,0,0]))}static mdia(t){return ls.box(ls.types.mdia,ls.mdhd(t.timescale||0,t.duration||0),ls.hdlr(t.type),ls.minf(t))}static mfhd(t){return ls.box(ls.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?ls.box(ls.types.minf,ls.box(ls.types.smhd,ls.SMHD),ls.DINF,ls.stbl(t)):ls.box(ls.types.minf,ls.box(ls.types.vmhd,ls.VMHD),ls.DINF,ls.stbl(t))}static moof(t,e,r){return ls.box(ls.types.moof,ls.mfhd(t),ls.traf(r,e))}static moov(t){let e=t.length;const r=[];for(;e--;)r[e]=ls.trak(t[e]);return ls.box.apply(null,[ls.types.moov,ls.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(ls.mvex(t)))}static mvex(t){let e=t.length;const r=[];for(;e--;)r[e]=ls.trex(t[e]);return ls.box.apply(null,[ls.types.mvex,...r])}static mvhd(t,e){e*=t;const r=Math.floor(e/(os+1)),i=Math.floor(e%(os+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,i>>24,i>>16&255,i>>8&255,255&i,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return ls.box(ls.types.mvhd,s)}static sdtp(t){const e=t.samples||[],r=new Uint8Array(4+e.length);let i,s;for(i=0;i<e.length;i++)s=e[i].flags,r[i+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return ls.box(ls.types.sdtp,r)}static stbl(t){return ls.box(ls.types.stbl,ls.stsd(t),ls.box(ls.types.stts,ls.STTS),ls.box(ls.types.stsc,ls.STSC),ls.box(ls.types.stsz,ls.STSZ),ls.box(ls.types.stco,ls.STCO))}static avc1(t){let e,r,i,s=[],n=[];for(e=0;e<t.sps.length;e++)r=t.sps[e],i=r.byteLength,s.push(i>>>8&255),s.push(255&i),s=s.concat(Array.prototype.slice.call(r));for(e=0;e<t.pps.length;e++)r=t.pps[e],i=r.byteLength,n.push(i>>>8&255),n.push(255&i),n=n.concat(Array.prototype.slice.call(r));const a=ls.box(ls.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return ls.box(ls.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,ls.box(ls.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),ls.box(ls.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))}static esds(t){const e=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return ls.box(ls.types.mp4a,ls.audioStsd(t),ls.box(ls.types.esds,ls.esds(t)))}static mp3(t){return ls.box(ls.types[".mp3"],ls.audioStsd(t))}static ac3(t){return ls.box(ls.types["ac-3"],ls.audioStsd(t),ls.box(ls.types.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return ls.box(ls.types.stsd,ls.STSD,ls.mp4a(t));if("mp3"===e&&"mp3"===t.codec)return ls.box(ls.types.stsd,ls.STSD,ls.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return ls.box(ls.types.stsd,ls.STSD,ls.avc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,r=(t.duration||0)*(t.timescale||0),i=t.width||0,s=t.height||0,n=Math.floor(r/(os+1)),a=Math.floor(r%(os+1));return ls.box(ls.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,255&i,0,0,s>>8&255,255&s,0,0]))}static traf(t,e){const r=ls.sdtp(t),i=t.id,s=Math.floor(e/(os+1)),n=Math.floor(e%(os+1));return ls.box(ls.types.traf,ls.box(ls.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,255&i])),ls.box(ls.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,n>>24,n>>16&255,n>>8&255,255&n])),ls.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,ls.box(ls.types.trak,ls.tkhd(t),ls.mdia(t))}static trex(t){const e=t.id;return ls.box(ls.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const r=t.samples||[],i=r.length,s=12+16*i,n=new Uint8Array(s);let a,o,l,d,h,u;for(e+=8+s,n.set(["video"===t.type?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,255&i,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<i;a++)o=r[a],l=o.duration,d=o.size,h=o.flags,u=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,61440&h.degradPrio,15&h.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return ls.box(ls.types.trun,n)}static initSegment(t){ls.types||ls.init();const e=ls.moov(t);return Et(ls.FTYP,e)}static hvc1(t){return new Uint8Array}}ls.types=void 0,ls.HDLR_TYPES=void 0,ls.STTS=void 0,ls.STSC=void 0,ls.STCO=void 0,ls.STSZ=void 0,ls.VMHD=void 0,ls.SMHD=void 0,ls.STSD=void 0,ls.FTYP=void 0,ls.DINF=void 0;function ds(t,e=!1){return function(t,e,r=1,i=!1){const s=t*e*r;return i?Math.round(s):s}(t,1e3,1/9e4,e)}function hs(t){const{baseTime:e,timescale:r,trackId:i}=t;return`${e/r} (${e}/${r}) trackId: ${i}`}let us,cs=null,fs=null;function gs(t,e,r,i){return{duration:e,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}class ms extends L{destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?hs(e):e} > ${t?hs(t):t}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const r=t[0].pts,i=t.reduce((t,i)=>{let s=i.pts,n=s-t;return n<-4294967296&&(e=!0,s=ps(s,r),n=s-t),n>0?t:s},r);return e&&this.debug("PTS rollover detected"),i}remux(t,e,r,i,s,n,a,o){let l,d,h,u,c,f,m=s,p=s;const v=t.pid>-1,E=e.pid>-1,y=e.samples.length,T=t.samples.length>0,S=a&&y>0||y>1;if((!v||T)&&(!E||S)||this.ISGenerated||a){if(this.ISGenerated){var L,R,A,b;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(L=e.pixelRatio)?void 0:L[0])!==(null==(R=t.pixelRatio)?void 0:R[0])||(null==(A=e.pixelRatio)?void 0:A[1])!==(null==(b=t.pixelRatio)?void 0:b[1]))||!t&&S||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,e,s,n));const r=this.isVideoContiguous;let i,a=-1;if(S&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!r&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){this.warn(`Dropped ${a} out of ${y} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,p+=(e.samples[0].pts-t)/e.inputTimeScale,i=p}else-1===a&&(this.warn(`No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(T&&S){const r=this.getVideoStartPts(e.samples),i=(ps(t.samples[0].pts,r)-r)/e.inputTimeScale;m+=Math.max(0,i),p+=Math.max(0,-i)}if(T){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,e,s,n)),d=this.remuxAudio(t,m,this.isAudioContiguous,n,E||S||o===g?p:void 0),S){const i=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,e,s,n)),l=this.remuxVideo(e,p,r,i)}}else S&&(l=this.remuxVideo(e,p,r,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(c=vs(r,s,this._initPTS,this._initDTS)),i.samples.length&&(u=Es(i,s,this._initPTS))),{audio:d,video:l,initSegment:h,independent:f,text:u,id3:c}}computeInitPts(t,e,r,i){const s=Math.round(r*e);let n=ps(t,s);if(n<s+e)for(this.log(`Adjusting PTS for rollover in timeline near ${(s-n)/e} ${i}`);n<s+e;)n+=8589934592;return n-s}generateIS(t,e,r,i){const s=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let d,h,u,c=!l||i,f="audio/mp4",g=-1;if(c&&(d=h=1/0),t.config&&s.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):ls.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(g=t.id,u=t.inputTimeScale,l&&u===l.timescale?c=!1:d=h=this.computeInitPts(s[0].pts,u,r,"audio"))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:ls.initSegment([e]),metadata:{width:e.width,height:e.height}},c)if(g=e.id,u=e.inputTimeScale,l&&u===l.timescale)c=!1;else{const t=this.getVideoStartPts(n),e=ps(n[0].dts,t),i=this.computeInitPts(e,u,r,"video"),s=this.computeInitPts(t,u,r,"video");h=Math.min(h,i),d=Math.min(d,s)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,c?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${r} ${d/u} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${d/u} (${d}/${u}) trackId: ${g}`),this._initPTS={baseTime:d,timescale:u,trackId:g},this._initDTS={baseTime:h,timescale:u,trackId:g}):d=u=void 0,{tracks:o,initPTS:d,timescale:u,trackId:g}}remuxVideo(t,e,r,i){const s=t.inputTimeScale,n=t.samples,d=[],h=n.length,u=this._initPTS,c=u.baseTime*s/u.timescale;let f,g,m=this.nextVideoTs,p=8,v=this.videoSampleDuration,E=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,S=!1;if(!r||null===m){const t=c+e*s,i=n[0].pts-ps(n[0].dts,n[0].pts);cs&&null!==m&&Math.abs(t-i-(m+c))<15e3?r=!0:m=t-i-c}const L=m+c;for(let t=0;t<h;t++){const e=n[t];e.pts=ps(e.pts,L),e.dts=ps(e.dts,L),e.dts<n[t>0?t-1:t].dts&&(S=!0)}S&&n.sort(function(t,e){const r=t.dts-e.dts,i=t.pts-e.pts;return r||i}),f=n[0].dts,g=n[n.length-1].dts;const R=g-f,A=R?Math.round(R/(h-1)):v||t.inputTimeScale/30;if(r){const r=f-L,i=r>A,s=r<-1;if((i||s)&&(i?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${ds(r,!0)} ms (${r}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${ds(-r,!0)} ms (${r}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!s||L>=n[0].pts||cs)){f=L;const t=n[0].pts-r;if(i)n[0].dts=f,n[0].pts=t;else{let e=!0;for(let i=0;i<n.length&&!(n[i].dts>t&&e);i++){const t=n[i].pts;if(n[i].dts-=r,n[i].pts-=r,i<n.length-1){const r=n[i+1].pts;e=r<=n[i].pts==r<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${ds(t,!0)}/${ds(f,!0)}, delta: ${ds(r,!0)} ms`)}}f=Math.max(0,f);let b=0,D=0,k=f;for(let t=0;t<h;t++){const e=n[t],r=e.units,i=r.length;let s=0;for(let t=0;t<i;t++)s+=r[t].data.length;D+=s,b+=i,e.length=s,e.dts<k?(e.dts=k,k+=A/4|0||1):k=e.dts,E=Math.min(e.pts,E),T=Math.max(e.pts,T)}g=n[h-1].dts;const _=D+4*b+8;let I;try{I=new Uint8Array(_)}catch(t){return void this.observer.emit(l.ERROR,l.ERROR,{type:a.MUX_ERROR,details:o.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:_,reason:`fail allocating video mdat ${_}`})}const C=new DataView(I.buffer);C.setUint32(0,_),I.set(ls.types.mdat,4);let x=!1,w=Number.POSITIVE_INFINITY,P=Number.POSITIVE_INFINITY,O=Number.NEGATIVE_INFINITY,F=Number.NEGATIVE_INFINITY;for(let t=0;t<h;t++){const e=n[t],r=e.units;let a,o=0;for(let t=0,e=r.length;t<e;t++){const e=r[t],i=e.data,s=e.data.byteLength;C.setUint32(p,s),p+=4,I.set(i,p),p+=s,o+=4+s}if(t<h-1)v=n[t+1].dts-e.dts,a=n[t+1].pts-e.pts;else{const r=this.config,o=t>0?e.dts-n[t-1].dts:A;if(a=t>0?e.pts-n[t-1].pts:A,r.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(r.maxBufferHole*s),n=(i?E+i*s:this.nextAudioTs+c)-e.pts;n>t?(v=n-o,v<0?v=o:x=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${v/90} ms for the last video frame.`)):v=o}else v=o}const l=Math.round(e.pts-e.dts);w=Math.min(w,v),O=Math.max(O,v),P=Math.min(P,a),F=Math.max(F,a),d.push(gs(e.key,v,o,l))}if(d.length)if(cs){if(cs<70){const t=d[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(fs&&F-P<O-w&&A/O<.025&&0===d[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=f;for(let e=0,r=d.length;e<r;e++){const i=t+d[e].duration,s=t+d[e].cts;if(e<r-1){const t=i+d[e+1].cts;d[e].duration=t-s}else d[e].duration=e?d[e-1].duration:A;d[e].cts=0,t=i}}v=x||!v?A:v;const M=g+v;this.nextVideoTs=m=M-c,this.videoSampleDuration=v,this.isVideoContiguous=!0;const N={data1:ls.moof(t.sequenceNumber++,f,y(t,{samples:d})),data2:I,startPTS:(E-c)/s,endPTS:(T+v-c)/s,startDTS:(f-c)/s,endDTS:m/s,type:"video",hasAudio:!1,hasVideo:!0,nb:d.length,dropped:t.dropped};return t.samples=[],t.dropped=0,N}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,r,i,s){const n=t.inputTimeScale,d=n/(t.samplerate?t.samplerate:n),h=this.getSamplesPerFrame(t),u=h*d,c=this._initPTS,f="mp3"===t.segmentCodec&&this.typeSupported.mpeg,g=[],m=void 0!==s;let p=t.samples,v=f?0:8,E=this.nextAudioTs||-1;const T=c.baseTime*n/c.timescale,S=T+e*n;if(this.isAudioContiguous=r=r||p.length&&E>0&&(i&&Math.abs(S-(E+T))<9e3||Math.abs(ps(p[0].pts,S)-(E+T))<20*u),p.forEach(function(t){t.pts=ps(t.pts,S)}),!r||E<0){const t=p.length;if(p=p.filter(t=>t.pts>=0),t!==p.length&&this.warn(`Removed ${p.length-t} of ${t} samples (initPTS ${T} / ${n})`),!p.length)return;E=0===s?0:i&&!m?Math.max(0,S-T):p[0].pts-T}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let r=0,i=E+T;r<p.length;r++){const s=p[r],a=s.pts,o=a-i,l=Math.abs(1e3*o/n);if(o<=-e*u&&m)0===r&&(this.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*o/n)} ms.`),this.nextAudioTs=E=a-T,i=a);else if(o>=e*u&&l<1e4&&m){let e=Math.round(o/u);for(i=a-e*u;i<0&&e&&u;)e--,i+=u;0===r&&(this.nextAudioTs=E=i-T),this.warn(`Injecting ${e} audio frames @ ${((i-T)/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){let e=as.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=s.unit.subarray()),p.splice(r,0,{unit:e,pts:i}),i+=u,r++}}s.pts=i,i+=u}}let L,R=null,A=null,b=0,D=p.length;for(;D--;)b+=p[D].unit.byteLength;for(let e=0,i=p.length;e<i;e++){const i=p[e],s=i.unit;let n=i.pts;if(null!==A){g[e-1].duration=Math.round((n-A)/d)}else{if(r&&"aac"===t.segmentCodec&&(n=E+T),R=n,!(b>0))return;b+=v;try{L=new Uint8Array(b)}catch(t){return void this.observer.emit(l.ERROR,l.ERROR,{type:a.MUX_ERROR,details:o.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:b,reason:`fail allocating audio mdat ${b}`})}if(!f){new DataView(L.buffer).setUint32(0,b),L.set(ls.types.mdat,4)}}L.set(s,v);const u=s.byteLength;v+=u,g.push(gs(!0,h,u,0)),A=n}const k=g.length;if(!k)return;const _=g[g.length-1];E=A-T,this.nextAudioTs=E+d*_.duration;const I=f?new Uint8Array(0):ls.moof(t.sequenceNumber++,R/d,y({},t,{samples:g}));t.samples=[];const C=(R-T)/n,x=this.nextAudioTs/n,w={data1:I,data2:L,startPTS:C,endPTS:x,startDTS:C,endDTS:x,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,w}constructor(t,e,r,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=r,this.ISGenerated=!1,null===cs){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);cs=t?parseInt(t[1]):0}if(null===fs){const t=navigator.userAgent.match(/Safari\/(\d+)/i);fs=t?parseInt(t[1]):0}}}function ps(t,e){let r;if(null===e)return t;for(r=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=r;return t}function vs(t,e,r,i){const s=t.samples.length;if(!s)return;const n=t.inputTimeScale;for(let a=0;a<s;a++){const s=t.samples[a];s.pts=ps(s.pts-r.baseTime*n/r.timescale,e*n)/n,s.dts=ps(s.dts-i.baseTime*n/i.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Es(t,e,r){const i=t.samples.length;if(!i)return;const s=t.inputTimeScale;for(let n=0;n<i;n++){const i=t.samples[n];i.pts=ps(i.pts-r.baseTime*s/r.timescale,e*s)/s}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}function ys(t,e,r=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(r?t.duration:0))/t.timescale:e}function Ts(t,e,r){const i=t.codec;if(i&&i.length>4)return i;if(e===j){if("ec-3"===i||"ac-3"===i||"alac"===i)return i;if("fLaC"===i||"Opus"===i){return Ot(i,!1)}return r.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"}return r.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1"}try{us=self.performance.now.bind(self.performance)}catch(t){us=Date.now}const Ss=[{demux:class{resetTimeStamp(){}resetInitSegment(t,e,r,i){const s=this.videoTrack=Pi("video",1),n=this.audioTrack=Pi("audio",1),a=this.txtTrack=Pi("text",1);if(this.id3Track=Pi("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=ut(t);if(o.video){const{id:t,timescale:e,codec:r,supplemental:i}=o.video;s.id=t,s.timescale=a.timescale=e,s.codec=r,s.supplemental=i}if(o.audio){const{id:t,timescale:e,codec:r}=o.audio;n.id=t,n.timescale=e,n.codec=r}a.id=it.text,s.sampleDuration=0,s.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let r=0;r<e;){const i=at(t,r);if(i>8&&109===t[r+4]&&111===t[r+5]&&111===t[r+6]&&102===t[r+7])return!0;r=i>1?r+i:e}return!1}(t)}demux(t,e){this.timeOffset=e;let r=t;const i=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Et(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},r=dt(t,["moof"]);if(r.length<2)return e.remainder=t,e;const i=r[r.length-1];return e.valid=t.slice(0,i.byteOffset-8),e.remainder=t.slice(i.byteOffset-8),e}(r);this.remainderData=e.remainder,i.samples=e.valid||new Uint8Array}else i.samples=r;const n=this.extractID3Track(i,e);return s.samples=yt(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,r=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(e,this.timeOffset);return r.samples=yt(t,e),{videoTrack:e,audioTrack:Pi(),id3Track:i,textTrack:Pi()}}extractID3Track(t,e){const r=this.id3Track;if(t.samples.length){const i=dt(t.samples,["emsg"]);i&&i.forEach(t=>{const i=function(t){const e=t[0];let r="",i="",n=0,a=0,o=0,l=0,d=0,h=0;if(0===e){for(;"\0"!==st(t.subarray(h,h+1));)r+=st(t.subarray(h,h+1)),h+=1;for(r+=st(t.subarray(h,h+1)),h+=1;"\0"!==st(t.subarray(h,h+1));)i+=st(t.subarray(h,h+1)),h+=1;i+=st(t.subarray(h,h+1)),h+=1,n=at(t,12),a=at(t,16),l=at(t,20),d=at(t,24),h=28}else if(1===e){h+=4,n=at(t,h),h+=4;const e=at(t,h);h+=4;const a=at(t,h);for(h+=4,o=2**32*e+a,s(o)||(o=Number.MAX_SAFE_INTEGER,_.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=at(t,h),h+=4,d=at(t,h),h+=4;"\0"!==st(t.subarray(h,h+1));)r+=st(t.subarray(h,h+1)),h+=1;for(r+=st(t.subarray(h,h+1)),h+=1;"\0"!==st(t.subarray(h,h+1));)i+=st(t.subarray(h,h+1)),h+=1;i+=st(t.subarray(h,h+1)),h+=1}return{schemeIdUri:r,value:i,timeScale:n,presentationTime:o,presentationTimeDelta:a,eventDuration:l,id:d,payload:t.subarray(h,t.byteLength)}}(t);if(Wi.test(i.schemeIdUri)){const t=ji(i,e);let s=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);const n=i.payload;r.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:wi.emsg,duration:s})}else if(this.config.enableEmsgKLVMetadata&&i.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const t=ji(i,e);r.samples.push({data:i.payload,len:i.payload.byteLength,dts:t,pts:t,type:wi.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(t,e,r){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}constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}},remux:class extends L{destroy(){}resetTimeStamp(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,r,i){this.audioCodec=e,this.videoCodec=r,this.generateInitSegment(t,i),this.emitInitSegment=!0}generateInitSegment(t,e){let{audioCodec:r,videoCodec:i}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:s,video:n}=this.initData=ut(t);if(e)!function(t,e){if(!t||!e)return;const r=e.keyId;r&&e.isCommonEncryption&&vt(t,(t,e)=>{const i=t.subarray(8,24);i.some(t=>0!==t)||(_.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${M(i)} -> ${M(r)}`),t.set(r,8))})}(t,e);else{const t=s||n;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}s&&(r=Ts(s,j,this)),n&&(i=Ts(n,q,this));const a={};s&&n?a.audiovideo={container:"video/mp4",codec:r+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:s?a.audio={container:"audio/mp4",codec:r,encrypted:s.encrypted,initSegment:t,id:"audio"}:n?a.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(t,e,r,s,n,a){var o,l;let{initPTS:d,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:s,id3:r,initSegment:void 0};i(h)||(h=this.lastEndTime=n||0);const c=e.samples;if(!c.length)return u;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if(null!=(o=g)&&o.length||(this.generateInitSegment(c),g=this.initData),null==(l=g)||!l.length)return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=function(t,e,r){const s={},n=dt(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=dt(a,["tfhd"])[0],l=at(o,4),d=e[l];if(!d)continue;s[l]||(s[l]={start:NaN,duration:0,sampleCount:0,timescale:d.timescale,type:d.type});const h=s[l],u=dt(a,["tfdt"])[0];if(u){const t=u[0];let e=at(u,4);1===t&&(e===et?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(e*=et+1,e+=at(u,8))),i(e)&&(!i(h.start)||e<h.start)&&(h.start=e)}const c=d.default,f=at(o,0)|(null==c?void 0:c.flags);let g=(null==c?void 0:c.duration)||0;8&f&&(g=at(o,2&f?12:8));const m=dt(a,["trun"]);let p=h.start||0,v=0,E=g;for(let t=0;t<m.length;t++){const e=m[t],r=at(e,4),i=h.sampleCount;h.sampleCount+=r;const s=1&e[3],n=4&e[3],a=1&e[2],o=2&e[2],l=4&e[2],d=8&e[2];let u=8,c=r;for(s&&(u+=4),n&&r&&(1&e[u+1]||void 0!==h.keyFrameIndex||(h.keyFrameIndex=i),u+=4,a?(E=at(e,u),u+=4):E=g,o&&(u+=4),d&&(u+=4),p+=E,v+=E,c--);c--;)a?(E=at(e,u),u+=4):E=g,o&&(u+=4),l&&(1&e[u+1]||void 0===h.keyFrameIndex&&(h.keyFrameIndex=h.sampleCount-(c+1),h.keyFrameStart=p),u+=4),d&&(u+=4),p+=E,v+=E;!v&&g&&(v+=g*r)}h.duration+=v}if(!Object.keys(s).some(t=>s[t].duration)){let e=1/0,r=0;const n=dt(t,["sidx"]);for(let t=0;t<n.length;t++){const i=ht(n[t]);if(null!=i&&i.references){e=Math.min(e,i.earliestPresentationTime/i.timescale);const t=i.references.reduce((t,e)=>t+e.info.duration||0,0);r=Math.max(r,t+i.earliestPresentationTime/i.timescale)}}r&&i(r)&&Object.keys(s).forEach(t=>{s[t].duration||(s[t].duration=r*s[t].timescale-s[t].start)})}return s}(c,g,this),p=g.audio?m[g.audio.id]:null,v=g.video?m[g.video.id]:null,E=ys(v,1/0),y=ys(p,1/0),T=ys(v,0,!0),S=ys(p,0,!0);let L=n,R=0;const A=p&&(!v||!d&&y<E||d&&d.trackId===g.audio.id),b=A?p:v;if(b){const t=b.timescale,e=b.start-n*t,r=A?g.audio.id:g.video.id;L=b.start/t,R=A?S-y:T-E,!a&&d||!function(t,e,r,i){if(null===t)return!0;const s=Math.max(i,1),n=e-t.baseTime/t.timescale;return Math.abs(n-r)>s}(d,L,n,R)&&t===d.timescale||(d&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${n} ${e/t} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${L-n} (${e}/${t}) trackId: ${r}`),d=null,f.initPTS=e,f.timescale=t,f.trackId=r)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${n}`);d?(f.initPTS=d.baseTime,f.timescale=d.timescale,f.trackId=d.trackId):(f.timescale&&void 0!==f.trackId&&void 0!==f.initPTS||(this.warn("Could not set initPTS"),f.initPTS=L,f.timescale=1,f.trackId=-1),this.initPTS=d={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const D=L-d.baseTime/d.timescale,k=D+R;R>0?this.lastEndTime=k:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const _=!!g.audio,I=!!g.video;let C="";_&&(C+="audio"),I&&(C+="video");const x={data1:c,startPTS:D,startDTS:D,endPTS:k,endDTS:k,type:C,hasAudio:_,hasVideo:I,nb:1,dropped:0,encrypted:!!g.audio&&g.audio.encrypted||!!g.video&&g.video.encrypted};u.audio=_&&!I?x:void 0,u.video=I?x:void 0;const w=null==v?void 0:v.sampleCount;if(w){const t=v.keyFrameIndex,e=-1!==t;x.nb=w,x.dropped=0===t||this.isVideoContiguous?0:e?t:w,x.independent=e,x.firstKeyFrame=t,e&&v.keyFrameStart&&(x.firstKeyFramePTS=(v.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(u.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),x.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${w} dropped: ${x.dropped} start: ${x.firstKeyFramePTS||"NA"}`)}return u.initSegment=f,u.id3=vs(r,n,d,d),s.samples.length&&(u.text=Es(s,n,d)),u}constructor(t,e,r,i){super("passthrough-remuxer",i),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}}},{demux:Ji,remux:ms},{demux:class extends Oi{resetInitSegment(t,e,r,i){super.resetInitSegment(t,e,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const r=gi(t,0);let i=(null==r?void 0:r.length)||0;if(Yi(t,i))return!1;for(let r=t.length;i<r;i++)if(yi(t,i))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&mi(t,e)&&vi(t,e)<=t.length-e}(t,e)}appendFrame(t,e,r){Ti(t,this.observer,e,r,t.manifestCodec);const i=Li(t,e,r,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}},remux:ms},{demux:class extends Oi{resetInitSegment(t,e,r,i){super.resetInitSegment(t,e,r,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=gi(t,0);let r=(null==e?void 0:e.length)||0;if(e&&11===t[r]&&119===t[r+1]&&void 0!==xi(e)&&((t,e)=>{let r=0,i=5;e+=i;const s=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=t[e];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,s[0]=(a[0]&n[0])>>l,r=r?r<<o|s[0]:s[0],e+=1,i-=o}return r})(t,r)<=16)return!1;for(let e=t.length;r<e;r++)if(Yi(t,r))return _.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return Hi(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,r){if(null!==this.basePTS)return Gi(t,e,r,this.basePTS,this.frameIndex)}},remux:ms}];class Ls{configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,r,i){const s=r.transmuxing;s.executeStart=us();let n=new Uint8Array(t);const{currentTransmuxState:d,transmuxConfig:h}=this;i&&(this.currentTransmuxState=i);const{contiguous:u,discontinuity:c,trackSwitch:f,accurateTimeOffset:g,timeOffset:m,initSegmentChange:p}=i||d,{audioCodec:v,videoCodec:E,defaultInitPts:y,duration:T,initSegmentData:S}=h,L=function(t,e){let r=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(r=e);return r}(n,e);if(L&&we(L.method)){const t=this.getDecrypter(),e=Pe(L.method);if(!t.isSync())return this.asyncResult=!0,this.decryptionPromise=t.webCryptoDecrypt(n,L.key.buffer,L.iv.buffer,e).then(t=>{const e=this.push(t,null,r);return this.decryptionPromise=null,e}),this.decryptionPromise;{let i=t.softwareDecrypt(n,L.key.buffer,L.iv.buffer,e);if(r.part>-1){const e=t.flush();i=e?e.buffer:e}if(!i)return s.executeEnd=us(),Rs(r);n=new Uint8Array(i)}}const R=this.needsProbing(c,f);if(R){const t=this.configureTransmuxer(n);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(l.ERROR,l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),s.executeEnd=us(),Rs(r)}(c||f||p||R)&&this.resetInitSegment(S,v,E,T,e),(c||p||R)&&this.resetInitialTimestamp(y),u||this.resetContiguity();const A=this.transmux(n,L,m,g,r);this.asyncResult=As(A);const b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,s.executeEnd=us(),A}flush(t){const e=t.transmuxing;e.executeStart=us();const{decrypter:r,currentTransmuxState:i,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(t));const n=[],{timeOffset:a}=i;if(r){const e=r.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=us();const r=[Rs(t)];return this.asyncResult?Promise.resolve(r):r}const d=o.flush(a);return As(d)?(this.asyncResult=!0,d.then(e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,d,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,r){const{audioTrack:i,videoTrack:s,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===f?"level":"track"} ${r.level}`);const d=this.remuxer.remux(i,s,n,a,l,o,!0,this.id);t.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=us()}resetInitialTimestamp(t){const{demuxer:e,remuxer:r}=this;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,r,i,s){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,r,i),a.resetInitSegment(t,e,r,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,r,i,s){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,r,i,s):this.transmuxUnencrypted(t,r,i,s),n}transmuxUnencrypted(t,e,r,i){const{audioTrack:s,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,n,a,o,e,r,!1,this.id),chunkMeta:i}}transmuxSampleAes(t,e,r,i,s){return this.demuxer.demuxSampleAes(t,e,r).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,r,i,!1,this.id),chunkMeta:s}))}configureTransmuxer(t){const{config:e,observer:r,typeSupported:i}=this;let s;for(let e=0,r=Ss.length;e<r;e++){var n;if(null!=(n=Ss[e].demux)&&n.probe(t,this.logger)){s=Ss[e];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=s.remux,d=s.demux;o&&o instanceof l||(this.remuxer=new l(r,e,i,this.logger)),a&&a instanceof d||(this.demuxer=new d(r,e,i,this.logger),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Rr(this.config)),t}constructor(t,e,r,i,s,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=r,this.id=s,this.logger=n}}const Rs=t=>({remuxResult:{},chunkMeta:t});function As(t){return"then"in t&&t.then instanceof Function}class bs{constructor(t,e,r,i,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=r,this.duration=i,this.defaultInitPts=s||null}}class Ds{constructor(t,e,r,i,s,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=r,this.trackSwitch=i,this.timeOffset=s,this.initSegmentChange=n}}const ks=/(\d+)-(\d+)\/(\d+)/;class _s{destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,r){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const n=function(t,e){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(y({},t.headers))};t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return r}(t,this.controller.signal),a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=r,this.request=this.fetchSetup(t,n),self.clearTimeout(this.requestTimeout),e.timeout=l&&i(l)?l:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,t,this.response))},e.timeout);(As(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(r=>{var n;this.response=this.loader=r;const o=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,t,this.response))},d-(o-s.loading.start)),!r.ok){const{status:t,statusText:e}=r;throw new Cs(e||"fetch, bad network response",t,r)}s.loading.first=o,s.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=ks.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(i(t))return t}const r=t.get("Content-Length");if(r)return parseInt(r)}(r.headers)||s.total;const l=null==(n=this.callbacks)?void 0:n.onProgress;return l&&i(e.highWaterMark)?this.loadProgressively(r,s,t,e.highWaterMark,l):a?r.arrayBuffer():"json"===t.responseType?r.json():r.text()}).then(r=>{var n,a;const l=this.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const d=r[o];d&&(s.loaded=s.total=d);const h={url:l.url,data:r,code:l.status},u=null==(n=this.callbacks)?void 0:n.onProgress;u&&!i(e.highWaterMark)&&u(s,t,r,l),null==(a=this.callbacks)||a.onSuccess(h,s,t,l)}).catch(e=>{var r;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const i=e&&e.code||0,n=e?e.message:null;null==(r=this.callbacks)||r.onError({code:i,text:n},t,e?e.details:null,s)})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,r,i=0,s){const n=new hi,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&s(e,r,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<i||n.dataLength?(n.push(l),n.dataLength>=i&&s(e,r,n.flush().buffer,t)):s(e,r,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Is,this.controller=new self.AbortController,this.stats=new W}}function Is(t,e){return new self.Request(t.url,e)}class Cs extends Error{constructor(t,e,r){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=r}}const xs=/^age:\s*[\d.]+\s*$/im;class ws{destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then(()=>{if(this.loader===r&&!this.stats.aborted)return s(r,e.url)}).catch(t=>{if(this.loader===r&&!this.stats.aborted)return r.open("GET",e.url,!0),s(r,e.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,e,t)}).catch(t=>{var s;null==(s=this.callbacks)||s.onError({code:r.status,text:t.message},e,r,i)}):this.openAndSendXhr(r,e,t)}openAndSendXhr(t,e,r){t.readyState||t.open("GET",e.url,!0);const s=e.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=r.loadPolicy;if(s)for(const e in s)t.setRequestHeader(e,s[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),r.timeout=n&&i(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:r}=this;if(!t||!e)return;const i=e.readyState,s=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const i=e.status,l="text"===e.responseType?e.responseText:null;if(i>=200&&i<300){const s=null!=l?l:e.response;if(null!=s){var n,a;r.loading.end=Math.max(self.performance.now(),r.loading.first);const o="arraybuffer"===e.responseType?s.byteLength:s.length;r.loaded=r.total=o,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(r,t,s,e);const d={url:e.responseURL,data:s,code:i};return void(null==(a=this.callbacks)||a.onSuccess(d,r,t,e))}}const d=s.loadPolicy.errorRetry;var o;if(he(d,r.retry,!1,{url:t.url,data:void 0,code:i}))this.retry(d);else _.error(`${i} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:i,text:e.statusText},t,e,r)}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(he(t,this.stats.retry,!0))this.retry(t);else{var e;_.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:r}=this;this.retryDelay=le(t,r.retry),r.retry++,_.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${r.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&xs.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new W,this.retryDelay=0}}const Ps={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Os=S(S({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:ws,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends L{resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new v(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.FRAG_LOADING,this.onFragLoading,this),t.on(l.FRAG_LOADED,this.onFragLoaded,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this),t.on(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(l.LEVEL_LOADED,this.onLevelLoaded,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(l.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.FRAG_LOADING,this.onFragLoading,this),t.off(l.FRAG_LOADED,this.onFragLoaded,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this),t.off(l.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(l.LEVEL_LOADED,this.onLevelLoaded,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(l.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(l.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const r=e.frag;if(!this.ignoreFragment(r)){var i;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(i=e.part)?i:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case o.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:r,partCurrent:i}=this;if(t&&r&&t.sn===r.sn&&t.level===r.level){const e=performance.now(),r=i?i.stats:t.stats,s=e-r.loading.start,n=r.loading.first?r.loading.first-r.loading.start:-1;if(r.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(t,n),r.loaded)}else this.bwEstimator.sampleTTFB(s)}break}}}getTimeToLoadFrag(t,e,r,i){return t+r/e+(i?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const r=this.hls.config,{loading:s}=e.stats,n=s.end-s.first;i(n)&&(this.lastLevelLoadSec=n/1e3),e.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,{frag:e,part:r}){const i=r?r.stats:e.stats;if(e.type===f&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=r?r.duration:e.duration,s=this.hls.levels[e.level],n=(s.loaded?s.loaded.bytes:0)+i.loaded,a=(s.loaded?s.loaded.duration:0)+t;s.loaded={bytes:n,duration:a},s.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:i,frag:e,part:r,id:e.type};this.onFragBuffered(l.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:r,part:i}=e,s=null!=i&&i.stats.loaded?i.stats:r.stats;if(s.aborted)return;if(this.ignoreFragment(r))return;const n=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,s.loaded),s.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==f||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,r=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,s=this.findBestLevel(r,e,t,0,i,1,1);if(s>-1)return s;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const i=e&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,i)&&e[t].loadError<=e[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:i,config:s,minAutoLevel:n}=r,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=s.abrBandWidthFactor,h=s.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,i,l,0,d,h);if(t>=0)return this.rebufferNotice=-1,t}let u=a?Math.min(a,s.maxStarvationDelay):s.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){u=(a?Math.min(a,s.maxLoadingDelay):s.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),d=h=1}}const c=this.findBestLevel(o,n,i,l,u,d,h);if(this.rebufferNotice!==c&&(this.rebufferNotice=c,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${c}`)),c>-1)return c;const f=r.levels[n],g=r.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:r.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const r=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,i=t.mainForwardBufferInfo;return(i?i.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,r,s,n,a,o){var l;const d=s+n,h=this.lastLoadedFragLevel,u=-1===h?this.hls.firstLevel:h,{fragCurrent:c,partCurrent:f}=this,{levels:g,allAudioTracks:m,loadLevel:p,config:v}=this.hls;if(1===g.length)return 0;const E=g[u],y=!(null==(l=this.hls.latestLevelDetails)||!l.live),T=-1===p||-1===h;let S,L="SDR",R=(null==E?void 0:E.frameRate)||0;const{audioPreference:A,videoPreference:b}=v;this.audioTracksByGroup||(this.audioTracksByGroup=Zt(m));let D=-1;if(T){if(-1!==this.firstSelection)return this.firstSelection;const s=this.codecTiers||(this.codecTiers=function(t,e,r,i){return t.slice(r,i+1).reduce((t,e,r)=>{if(!e.codecSet)return t;const i=e.audioGroups;let s=t[e.codecSet];s||(t[e.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),s.minBitrate=Math.min(s.minBitrate,e.bitrate);const n=Math.min(e.height,e.width);return s.minHeight=Math.min(s.minHeight,n),s.minFramerate=Math.min(s.minFramerate,e.frameRate),s.minIndex=Math.min(s.minIndex,r),s.maxScore=Math.max(s.maxScore,e.score),s.fragmentError+=e.fragmentError,s.videoRanges[e.videoRange]=(s.videoRanges[e.videoRange]||0)+1,t},{})}(g,0,e,r)),n=function(t,e,r,s,n){const a=Object.keys(t),o=null==s?void 0:s.channels,l=null==s?void 0:s.audioCodec,d=null==n?void 0:n.videoCodec,h=o&&2===parseInt(o);let u=!1,c=!1,f=1/0,g=1/0,m=1/0,p=1/0,v=0,E=[];const{preferHDR:y,allowedVideoRanges:T}=Xt(e,n);for(let e=a.length;e--;){const r=t[a[e]];u||(u=r.channels[2]>0),f=Math.min(f,r.minHeight),g=Math.min(g,r.minFramerate),m=Math.min(m,r.minBitrate),T.filter(t=>r.videoRanges[t]>0).length>0&&(c=!0)}f=i(f)?f:0,g=i(g)?g:0;const S=Math.max(1080,f),L=Math.max(30,g);m=i(m)?m:r,r=Math.max(m,r),c||(e=void 0);const R=a.length>1;return{codecSet:a.reduce((e,i)=>{const s=t[i];if(i===e)return e;if(E=c?T.filter(t=>s.videoRanges[t]>0):[],R){if(s.minBitrate>r)return Qt(i,`min bitrate of ${s.minBitrate} > current estimate of ${r}`),e;if(!s.hasDefaultAudio)return Qt(i,"no renditions with default or auto-select sound found"),e;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Qt(i,`audio codec preference "${l}" not found`),e;if(o&&!h){if(!s.channels[o])return Qt(i,`no renditions with ${o} channel sound found (channels options: ${Object.keys(s.channels)})`),e}else if((!l||h)&&u&&0===s.channels[2])return Qt(i,"no renditions with stereo sound found"),e;if(s.minHeight>S)return Qt(i,`min resolution of ${s.minHeight} > maximum of ${S}`),e;if(s.minFramerate>L)return Qt(i,`min framerate of ${s.minFramerate} > maximum of ${L}`),e;if(!E.some(t=>s.videoRanges[t]>0))return Qt(i,`no variants with VIDEO-RANGE of ${zt(E)} found`),e;if(d&&i.indexOf(d.substring(0,4))%5!=0)return Qt(i,`video codec preference "${d}" not found`),e;if(s.maxScore<v)return Qt(i,`max score of ${s.maxScore} < selected max of ${v}`),e}return e&&(xt(i)>=xt(e)||s.fragmentError>t[e].fragmentError)?e:(p=s.minIndex,v=s.maxScore,i)},void 0),videoRanges:E,preferHDR:y,minFramerate:g,minBitrate:m,minIndex:p}}(s,L,t,A,b),{codecSet:a,videoRanges:o,minFramerate:l,minBitrate:d,minIndex:h,preferHDR:u}=n;D=h,S=a,L=u?o[o.length-1]:o[0],R=l,t=Math.max(t,d),this.log(`picked start tier ${zt(n)}`)}else S=null==E?void 0:E.codecSet,L=null==E?void 0:E.videoRange;const k=f?f.duration:c?c.duration:0,_=this.bwEstimator.getEstimateTTFB()/1e3,I=[];for(let l=r;l>=e;l--){var C;const e=g[l],c=l>u;if(!e)continue;if((S&&e.codecSet!==S||L&&e.videoRange!==L||c&&R>e.frameRate||!c&&R>0&&R<e.frameRate||null!=(C=e.supportedResult)&&null!=(C=C.decodingInfoResults)&&C.some(t=>!1===t.smooth))&&(!T||l!==D)){I.push(l);continue}const m=e.details,v=(f?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||k;let E;E=c?o*t:a*t;const A=k&&s>=2*k&&0===n?e.averageBitrate:e.maxBitrate,b=this.getTimeToLoadFrag(_,E,A*v,void 0===m);if(E>=A&&(l===h||0===e.loadError&&0===e.fragmentError)&&(b<=_||!i(b)||y&&!this.bitrateTestDelay||b<d)){const t=this.forcedAutoLevel;return l===p||-1!==t&&t===p||(I.length&&this.trace(`Skipped level(s) ${I.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${g[I[0]].codecs}" ${g[I[0]].videoRange}; not compatible with "${S}" ${L}`),this.info(`switch candidate:${u}->${l} adjustedbw(${Math.round(E)})-bitrate=${Math.round(E-A)} ttfb:${_.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${b.toFixed(1)} firstSelection:${T} codecSet:${e.codecSet} videoRange:${e.videoRange} hls.loadLevel:${p}`)),T&&(this.firstSelection=l),l}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:r}=this.hls;return Math.min(Math.max(t,r),e)}constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var e;const{fragCurrent:r,partCurrent:s,hls:n}=this,{autoLevelEnabled:a,media:o}=n;if(!r||!o)return;const d=performance.now(),h=s?s.stats:r.stats,u=s?s.duration:r.duration,c=d-h.loading.start,f=n.minAutoLevel,g=r.level,m=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!a)return;const p=m>-1&&m!==g,v=!!t||p;if(!v&&(o.paused||!o.playbackRate||!o.readyState))return;const E=n.mainForwardBufferInfo;if(!v&&null===E)return;const y=this.bwEstimator.getEstimateTTFB(),T=Math.abs(o.playbackRate);if(c<=Math.max(y,u/(2*T)*1e3))return;const S=E?E.len/T:0,L=h.loading.first?h.loading.first-h.loading.start:-1,R=h.loaded&&L>-1,A=this.getBwEstimate(),b=n.levels,D=b[g],k=Math.max(h.loaded,Math.round(u*(r.bitrate||D.averageBitrate)/8));let _=R?c-L:c;_<1&&R&&(_=Math.min(c,8*h.loaded/A));const I=R?1e3*h.loaded/_:0,C=y/1e3,x=I?(k-h.loaded)/I:8*k/A+C;if(x<=S)return;const w=I?8*I:A,P=!0===(null==(e=(null==t?void 0:t.details)||this.hls.latestLevelDetails)?void 0:e.live),O=this.hls.config.abrBandWidthUpFactor;let F,M=Number.POSITIVE_INFINITY;for(F=g-1;F>f;F--){const t=b[F].maxBitrate,e=!b[F].details||P;if(M=this.getTimeToLoadFrag(C,w,u*t,e),M<Math.min(S,u+C))break}if(M>=x)return;if(M>10*u)return;R?this.bwEstimator.sample(c-Math.min(y,L),h.loaded):this.bwEstimator.sampleTTFB(c);const N=b[F].maxBitrate;this.getBwEstimate()*O>N&&this.resetEstimator(N);const B=this.findBestLevel(N,f,F,0,S,1,1);B>-1&&(F=B),this.warn(`Fragment ${r.sn}${s?" part "+s.index:""} of level ${g} is loading too slowly;\n      Fragment duration: ${r.duration.toFixed(3)}\n      Time to underbuffer: ${S.toFixed(3)} s\n      Estimated load time for current fragment: ${x.toFixed(3)} s\n      Estimated load time for down switch fragment: ${M.toFixed(3)} s\n      TTFB estimate: ${0|L} ms\n      Current BW estimate: ${i(A)?0|A:"Unknown"} bps\n      New BW estimate: ${0|this.getBwEstimate()} bps\n      Switching to level ${F} @ ${0|N} bps`),n.nextLoadLevel=n.nextAutoLevel=F,this.clearTimer();const $=()=>{if(this.clearTimer(),this.fragCurrent===r&&this.hls.loadLevel===F&&F>0){const t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${F>0?"and switching down":""}\n      Fragment duration: ${r.duration.toFixed(3)} s\n      Time to underbuffer: ${t.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,F>f){let e=this.findBestLevel(this.hls.levels[f].bitrate,f,F,0,t,1,1);-1===e&&(e=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=e,this.resetEstimator(this.hls.levels[e].bitrate)}}};p||x>2*M?$():this.timer=self.setInterval($,1e3*M),n.trigger(l.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:s,stats:h})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}},bufferController:class extends L{hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:t}=this;t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.BUFFER_RESET,this.onBufferReset,this),t.on(l.BUFFER_APPENDING,this.onBufferAppending,this),t.on(l.BUFFER_CODECS,this.onBufferCodecs,this),t.on(l.BUFFER_EOS,this.onBufferEos,this),t.on(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(l.FRAG_PARSED,this.onFragParsed,this),t.on(l.FRAG_CHANGED,this.onFragChanged,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.BUFFER_RESET,this.onBufferReset,this),t.off(l.BUFFER_APPENDING,this.onBufferAppending,this),t.off(l.BUFFER_CODECS,this.onBufferCodecs,this),t.off(l.BUFFER_EOS,this.onBufferEos,this),t.off(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(l.FRAG_PARSED,this.onFragParsed,this),t.off(l.FRAG_CHANGED,this.onFragChanged,this),t.off(l.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const r={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===e?y(r,i.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(r[e]=y({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,tracks:r}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){var r;let i=2;(e.audio&&!e.video||!e.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(t,e){const r=this.media=e.media;this.transferData=this.overrides=void 0;const i=O(this.appendSource);if(i){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const s=this.mediaSource=e.mediaSource||new i;if(this.assignMediaSource(s),t)this._objectUrl=r.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(s);if(this.appendSource)try{r.removeAttribute("src");const e=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||e&&s instanceof e,ei(r),function(t,e){const r=self.document.createElement("source");r.type="video/mp4",r.src=e,t.appendChild(r)}(r,t),r.load()}catch(e){r.src=t}else r.src=t}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var e,r;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(r=t.constructor)?void 0:r.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const r=this.tracks,i=e.tracks,s=i?Object.keys(i):null,n=s?s.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&s&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${zt(r,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${zt(i,(t,e)=>"initSegment"===t?void 0:e)}}`),!function(t,e){const r=Object.keys(t),i=Object.keys(e),s=r.length,n=i.length;return!s||!n||s===n&&!r.some(t=>-1===i.indexOf(t))}(i,r)){e.mediaSource=null,e.tracks=void 0;const s=t.currentTime,n=this.details,a=Math.max(s,(null==n?void 0:n.fragments[0].start)||0);return a-s>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${s} -> ${a}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(r)}") start time: ${a} currentTime: ${s}`),this.onMediaDetaching(l.MEDIA_DETACHING,{}),this.onMediaAttaching(l.MEDIA_ATTACHING,e),void(t.currentTime=a))}this.transferData=void 0,s.forEach(t=>{const e=t,r=i[e];if(r){const t=r.buffer;if(t){const i=this.fragmentTracker,s=r.id;if(i.hasFragments(s)||i.hasParts(s)){const r=wr.getBuffered(t);i.detectEvictedFragments(e,r,s,null,!0)}const n=ri(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,r)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const r=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:s,_objectUrl:n}=this;if(s){if(this.log("media source "+(r?"transferring":"detaching")),r)this.sourceBuffers.forEach(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===s.readyState;try{const e=s.sourceBuffers;for(let r=e.length;r--;)t&&e[r].abort(),s.removeSourceBuffer(e[r]);t&&s.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),r||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&ei(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(l.MEDIA_DETACHED,e)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const r=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[ri(t)]=[null,null];const e=this.tracks[t];e&&(e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Qr(this.tracks)}onBufferCodecs(t,e){var r;const i=this.tracks,s=Object.keys(e);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(i.audio||i.video)||i.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&s.some(t=>!i[t]);n||a?this.warn(`Unsupported transition between "${Object.keys(i)}" and "${s}" SourceBuffers`):(s.forEach(t=>{var r,s;const n=e[t],{id:a,codec:o,levelCodec:l,container:d,metadata:h,supplemental:u}=n;let c=i[t];const f=null==(r=this.transferData)||null==(r=r.tracks)?void 0:r[t],g=null!=f&&f.buffer?f:c,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;c||(c=i[t]={buffer:void 0,listeners:[],codec:o,supplemental:u,container:d,levelCodec:l,metadata:h,id:a});const v=Ft(m,p),E=null==v?void 0:v.replace(Zr,"$1");let y=Ft(o,l);const T=null==(s=y)?void 0:s.replace(Zr,"$1");y&&v&&E!==T&&("audio"===t.slice(0,5)&&(y=Ot(y,this.appendSource)),this.log(`switching codec ${m} to ${y}`),y!==(c.pendingCodec||c.codec)&&(c.pendingCodec=y),c.container=d,this.appendChangeType(t,d,y))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(r=e.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{const r=this.tracks[e];return t[e]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t},{})}appendChangeType(t,e,r){const i=`${e};codecs=${r}`,s={label:`change-type=${i}`,execute:()=>{const s=this.tracks[t];if(s){const n=s.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${i}`),n.changeType(i),s.codec=r,s.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(s,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const r=t.start,i=r+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(r,f))?void 0:e.gap))return;const s={label:"block-audio",execute:()=>{var t;const e=this.tracks.video;(this.lastVideoAppendEnd>i||null!=e&&e.buffer&&wr.isBuffered(e.buffer,i)||!0===(null==(t=this.fragmentTracker.getAppendedFrag(i,f))?void 0:t.gap))&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.blockedAudioAppend={op:s,frag:t},this.append(s,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:e}=this;t&&e&&(this.blockedAudioAppend=null,e.unblockAudio(t.op))}onBufferAppending(t,e){const{tracks:r}=this,{data:s,type:n,parent:d,frag:h,part:u,chunkMeta:c,offset:g}=e,m=c.buffering[n],{sn:p,cc:v}=h,E=self.performance.now();m.start=E;const y=h.stats.buffering,T=u?u.stats.buffering:null;0===y.start&&(y.start=E),T&&0===T.start&&(T.start=E);const S=r.audio;let L=!1;"audio"===n&&"audio/mpeg"===(null==S?void 0:S.container)&&(L=!this.lastMpegAudioChunk||1===c.id||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const R=r.video,A=null==R?void 0:R.buffer;if(A&&"initSegment"!==p){const t=u||h,e=this.blockedAudioAppend;if("audio"!==n||"main"===d||this.blockedAudioAppend||R.ending||R.ended){if("video"===n){const r=t.end;if(e){const t=e.frag.start;(r>t||r<this.lastVideoAppendEnd||wr.isBuffered(A,t))&&this.unblockAudio()}this.lastVideoAppendEnd=r}}else{const e=t.start+.05*t.duration,r=A.buffered,i=this.currentOp("video");r.length||i?!i&&!wr.isBuffered(A,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}}const b=(u||h).start,D={label:`append-${n}`,execute:()=>{var t;m.executeStart=self.performance.now();const e=null==(t=this.tracks[n])?void 0:t.buffer;e&&(L?this.updateTimestampOffset(e,b,.1,n,p,v):void 0!==g&&i(g)&&this.updateTimestampOffset(e,g,1e-6,n,p,v)),this.appendExecutor(s,n)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();m.executeEnd=m.end=t,0===y.first&&(y.first=t),T&&0===T.first&&(T.first=t);const e={};this.sourceBuffers.forEach(([t,r])=>{t&&(e[t]=wr.getBuffered(r))}),this.appendErrors[n]=0,"audio"===n||"video"===n?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(l.BUFFER_APPENDED,{type:n,frag:h,part:u,chunkMeta:c,parent:h.type,timeRanges:e})},onError:t=>{var e;const r={type:a.MEDIA_ERROR,parent:h.type,details:o.BUFFER_APPEND_ERROR,sourceBufferName:n,frag:h,part:u,chunkMeta:c,error:t,err:t,fatal:!1},i=null==(e=this.media)?void 0:e.error;if(t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t)r.details=o.BUFFER_FULL_ERROR;else if(t.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!i)r.errorAction=Te(!0);else if(t.name===Jr&&0===this.sourceBufferCount)r.errorAction=Te(!0);else{const t=++this.appendErrors[n];this.warn(`Failed ${t}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${n}" sourceBuffer (${i||"no media error"})`),(t>=this.hls.config.appendErrorMaxRetry||i)&&(r.fatal=!0)}this.hls.trigger(l.ERROR,r)}};this.log(`queuing "${n}" append sn: ${p}${u?" p: "+u.index:""} of ${h.type===f?"level":"track"} ${h.level} cc: ${v}`),this.append(D,n,this.isPending(this.tracks[n]))}getFlushOp(t,e,r){return this.log(`queuing "${t}" remove ${e}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(l.BUFFER_FLUSHED,{type:t})},onError:i=>{this.warn(`Failed to remove ${e}-${r} from "${t}" SourceBuffer`,i)}}}onBufferFlushing(t,e){const{type:r,startOffset:i,endOffset:s}=e;r?this.append(this.getFlushOp(r,i,s),r):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,i,s),t)})}onFragParsed(t,e){const{frag:r,part:i}=e,s=[],n=i?i.elementaryStreams:r.elementaryStreams;n[X]?s.push("audiovideo"):(n[j]&&s.push("audio"),n[q]&&s.push("video"));0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(()=>{const t=self.performance.now();r.stats.buffering.end=t,i&&(i.stats.buffering.end=t);const e=i?i.stats:r.stats;this.hls.trigger(l.FRAG_BUFFERED,{frag:r,part:i,stats:e,id:r.type})},s).catch(t=>{this.warn(`Fragment buffered callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var r;this.sourceBuffers.forEach(([t])=>{if(t){const r=this.tracks[t];e.type&&e.type!==t||(r.ending=!0,r.ended||(r.ended=!0,this.log(`${t} buffer reached EOS`)))}});const i=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(l.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger(l.BUFFERED_TO_END,void 0)):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,e){if(e.details===o.BUFFER_APPEND_ERROR&&e.frag){var r;const t=null==(r=e.errorAction)?void 0:r.nextAutoLevel;i(t)&&t!==e.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:e,media:r}=this;if(!r||null===e)return;if(!this.sourceBufferCount)return;const s=t.config,n=r.currentTime,a=e.levelTargetDuration,o=e.live&&null!==s.liveBackBufferLength?s.liveBackBufferLength:s.backBufferLength;if(i(o)&&o>=0){const t=Math.max(o,a),e=Math.floor(n/a)*a-t;this.flushBackBuffer(n,a,e)}const l=s.frontBufferFlushThreshold;if(i(l)&&l>0){const t=Math.max(s.maxBufferLength,l),e=Math.max(t,a),r=Math.floor(n/a)*a+e;this.flushFrontBuffer(n,a,r)}}flushBackBuffer(t,e,r){this.sourceBuffers.forEach(([t,e])=>{if(e){const s=wr.getBuffered(e);if(s.length>0&&r>s.start(0)){var i;this.hls.trigger(l.BACK_BUFFER_REACHED,{bufferEnd:r});const e=this.tracks[t];if(null!=(i=this.details)&&i.live)this.hls.trigger(l.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=e&&e.ended)return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(l.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:t})}}})}flushFrontBuffer(t,e,r){this.sourceBuffers.forEach(([e,i])=>{if(i){const s=wr.getBuffered(i),n=s.length;if(n<2)return;const a=s.start(n-1),o=s.end(n-1);if(r>a||t>=a&&t<=o)return;this.hls.trigger(l.BUFFER_FLUSHING,{startOffset:a,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:e,mediaSource:r}=this;if(!e||!this.media||"open"!==(null==r?void 0:r.readyState))return null;const s=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&r.setLiveSeekableRange){const t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,s)}}return{duration:1/0}}const n=null==(t=this.overrides)?void 0:t.duration;if(n)return i(n)?{duration:n}:null;const a=this.media.duration;return s>(i(r.duration)?r.duration:0)&&s>a||!i(a)?{duration:s}:null}updateMediaSource({duration:t,start:e,end:r}){const s=this.mediaSource;this.media&&s&&"open"===s.readyState&&(s.duration!==t&&(i(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),s.duration=t),void 0!==e&&void 0!==r&&(this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${e}-${r}.`),s.setLiveSeekableRange(e,r)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${zt(r)}`),this.tracksReady){var i;const t=null==(i=this.transferData)?void 0:i.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,r])=>{if(e){const i=this.tracks[e];t[e]={buffer:r,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(l.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const s in t){const n=s,d=t[n];if(this.isPending(d)){const t=this.getTrackCodec(d,n),s=`${d.container};codecs=${t}`;d.codec=t,this.log(`creating sourceBuffer(${s})${this.currentOp(n)?" Queued":""} ${zt(d)}`);try{const t=r.addSourceBuffer(s),i=ri(n),a=[n,t];e[i]=a,d.buffer=t}catch(t){var i;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(n),null==(i=this.operationQueue)||i.removeBlockers(),delete this.tracks[n],void this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:n,mimeType:s,parent:d.id})}this.trackSourceBuffer(n,d)}}this.bufferCreated()}getTrackCodec(t,e){const r=t.supplemental;let i=t.codec;r&&("video"===e||"audiovideo"===e)&&kt(r,"video")&&(i=function(t,e){const r=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)Dt(e[t],"video")||r.push(e[t])}return e&&r.push(e),r.join(",")}(i,r));const s=Ft(i,t.levelCodec);return s?"audio"===e.slice(0,5)?Ot(s,this.appendSource):s:""}trackSourceBuffer(t,e){const r=e.buffer;if(!r)return;const i=this.getTrackCodec(e,t);this.tracks[t]={buffer:r,codec:i,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const r=e.removedRanges;null!=r&&r.length&&this.hls.trigger(l.BUFFER_FLUSHED,{type:t})})}get mediaSrc(){var t,e;const r=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==r?void 0:r.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const r=this.currentOp(t);r&&(r.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,e){var r;const i=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(r=this.mediaSource)?void 0:r.readyState}`);this.error(`${i}`,e),this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:!1});const s=this.currentOp(t);s&&s.onError(i)}updateTimestampOffset(t,e,r,i,s,n){const a=e-t.timestampOffset;Math.abs(a)>=r&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${e} (sn: ${s} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,e,r){const{media:s,mediaSource:n}=this,a=this.tracks[t],o=null==a?void 0:a.buffer;if(!s||!n||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void this.shiftAndExecuteNext(t);const l=i(s.duration)?s.duration:1/0,d=i(n.duration)?n.duration:1/0,h=Math.max(0,e),u=Math.min(r,l,d);u>h&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${h},${u}] from the ${t} SourceBuffer`),o.remove(h,u)):this.shiftAndExecuteNext(t)}appendExecutor(t,e){const r=this.tracks[e],i=null==r?void 0:r.buffer;if(!i)throw new ti(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,i.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:r}=this,i=e.map(t=>this.appendBlocker(t));return e.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(e=>{r===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const r=null==(e=this.tracks[t])?void 0:e.buffer;r&&!r.updating&&this.shiftAndExecuteNext(t)})}append(t,e,r){this.operationQueue&&this.operationQueue.append(t,e,r)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,r){const i=this.tracks[t];if(!i)return;const s=i.buffer;if(!s)return;const n=r.bind(this,t);i.listeners.push({event:e,listener:n}),s.addEventListener(e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const r=e.buffer;r&&(e.listeners.forEach(t=>{r.removeEventListener(t.event,t.listener)}),e.listeners.length=0)}constructor(t,e){var r;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:r}=this;t&&this.log("Media source opened"),e&&r&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(l.MEDIA_ATTACHED,{media:e,mediaSource:r}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(r=O(t.config.preferManagedMediaSource),"undefined"!=typeof self&&r===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}},capLevelController:ii,errorController:class extends L{registerListeners(){const t=this.hls;t.on(l.ERROR,this.onError,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(l.ERROR,this.onError,this),t.off(l.ERROR,this.onErrorOut,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===f?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,r=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===r?e.loadLevel:r}variantHasKey(t,e){if(t){var r;if(null!=(r=t.details)&&r.hasKey(e))return!0;const i=t.audioGroups;if(i){return this.hls.allAudioTracks.filter(t=>i.indexOf(t.groupId)>=0).some(t=>{var r;return null==(r=t.details)?void 0:r.hasKey(e)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var r;if(e.fatal)return;const i=this.hls,s=e.context;switch(e.details){case o.FRAG_LOAD_ERROR:case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_ERROR:case o.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case o.FRAG_PARSING_ERROR:if(null!=(r=e.frag)&&r.gap)return void(e.errorAction=Te());case o.FRAG_GAP:case o.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=fe);case o.LEVEL_EMPTY_ERROR:case o.LEVEL_PARSING_ERROR:{var n;const t=e.parent===f?e.level:i.loadLevel;e.details===o.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(n=n.levelDetails)&&n.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case o.LEVEL_LOAD_ERROR:case o.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==s?void 0:s.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.level)));case o.AUDIO_TRACK_LOAD_ERROR:case o.AUDIO_TRACK_LOAD_TIMEOUT:case o.SUBTITLE_LOAD_ERROR:case o.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const t=i.loadLevelObj;if(t&&(s.type===u&&t.hasAudioGroup(s.groupId)||s.type===c&&t.hasSubtitleGroup(s.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.loadLevel),e.errorAction.action=fe,void(e.errorAction.flags=ve)}return;case o.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:fe,flags:Ee});case o.KEY_SYSTEM_SESSION_UPDATE_FAILED:case o.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case o.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:fe,flags:ye});case o.BUFFER_ADD_CODEC_ERROR:case o.REMUX_ALLOC_ERROR:case o.BUFFER_APPEND_ERROR:var l;if(!e.errorAction)e.errorAction=this.getLevelSwitchAction(e,null!=(l=e.level)?l:i.loadLevel);return;case o.INTERNAL_EXCEPTION:case o.BUFFER_APPENDING_ERROR:case o.BUFFER_FULL_ERROR:case o.LEVEL_SWITCH_ERROR:case o.BUFFER_STALLED_ERROR:case o.BUFFER_SEEK_OVER_HOLE:case o.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=Te())}e.type===a.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=Te())}getPlaylistRetryOrSwitchAction(t,e){const r=oe(this.hls.config.playlistLoadPolicy,t),i=this.playlistError++;if(he(r,i,se(t),t.response))return{action:me,flags:pe,retryConfig:r,retryCount:i};const s=this.getLevelSwitchAction(t,e);return r&&(s.retryConfig=r,s.retryCount=i),s}getFragRetryOrSwitchAction(t){const e=this.hls,r=this.getVariantLevelIndex(t.frag),i=e.levels[r],{fragLoadPolicy:s,keyLoadPolicy:n}=e.config,a=oe(ne(t)?n:s,t),l=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(i&&(t.details!==o.FRAG_GAP&&i.fragmentError++,!ae(t))){if(he(a,l,se(t),t.response))return{action:me,flags:pe,retryConfig:a,retryCount:l}}const d=this.getLevelSwitchAction(t,r);return a&&(d.retryConfig=a,d.retryCount=l),d}getLevelSwitchAction(t,e){const r=this.hls;null==e&&(e=r.loadLevel);const i=this.hls.levels[e];if(i){var s,n;const e=t.details;i.loadError++,e===o.BUFFER_APPEND_ERROR&&i.fragmentError++;let d=-1;const{levels:h,loadLevel:p,minAutoLevel:v,maxAutoLevel:E}=r;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);const y=null==(s=t.frag)?void 0:s.type,T=(y===g&&e===o.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===o.BUFFER_ADD_CODEC_ERROR||e===o.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:t})=>i.audioCodec!==t),S="video"===t.sourceBufferName&&(e===o.BUFFER_ADD_CODEC_ERROR||e===o.BUFFER_APPEND_ERROR)&&h.some(({codecSet:t,audioCodec:e})=>i.codecSet!==t&&i.audioCodec===e),{type:L,groupId:R}=null!=(n=t.context)?n:{};for(let r=h.length;r--;){const s=(r+p)%h.length;if(s!==p&&s>=v&&s<=E&&0===h[s].loadError){var a,l;const r=h[s];if(e===o.FRAG_GAP&&y===f&&t.frag){const e=h[s].details;if(e){const r=ee(t.frag,e.fragments,t.frag.start);if(null!=r&&r.gap)continue}}else{if(L===u&&r.hasAudioGroup(R)||L===c&&r.hasSubtitleGroup(R))continue;if(y===g&&null!=(a=i.audioGroups)&&a.some(t=>r.hasAudioGroup(t))||y===m&&null!=(l=i.subtitleGroups)&&l.some(t=>r.hasSubtitleGroup(t))||T&&i.audioCodec===r.audioCodec||S&&i.codecSet===r.codecSet||!T&&i.codecSet!==r.codecSet)continue}d=s;break}}if(d>-1&&r.loadLevel!==d)return t.levelRetry=!0,this.playlistError=0,{action:fe,flags:pe,nextAutoLevel:d}}return{action:fe,flags:ve}}onErrorOut(t,e){var r;switch(null==(r=e.errorAction)?void 0:r.action){case ce:break;case fe:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===o.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,r=t.errorAction;if(!r)return;const{flags:i}=r,s=r.nextAutoLevel;switch(i){case pe:this.switchLevel(t,s);break;case Ee:{const i=this.getVariantLevelIndex(t.frag),s=e.levels[i],n=null==s?void 0:s.attrs["HDCP-LEVEL"];if(r.hdcpLevel=n,"NONE"===n)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(n){e.maxHdcpLevel=Ut[Ut.indexOf(n)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);break}}case ye:{const e=t.decryptdata;if(e){const i=this.hls.levels,s=i.length;for(let r=s;r--;){var n,a;if(this.variantHasKey(i[r],e))this.log(`Banned key found in level ${r} (${i[r].bitrate}bps) or audio group "${null==(n=i[r].audioGroups)?void 0:n.join(",")}" (${null==(a=t.frag)?void 0:a.type} fragment) ${M(e.keyId||[])}`),i[r].fragmentError++,i[r].loadError++,this.log(`Removing level ${r} with key error (${t.error})`),this.hls.removeLevel(r)}const o=t.frag;if(this.hls.levels.length<s)r.resolved=!0;else if(o&&o.type!==f){const t=o.decryptdata;t&&!e.matches(t)&&(r.resolved=!0)}}break}}r.resolved||this.switchLevel(t,s)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===o.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=$t(t.mimeType),r=this.hls.levels;for(let i=r.length;i--;)r[i][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${i} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(i))}}constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}},fpsController:class{setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(l.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(l.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const r=this.hls.config;if(r.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,r){const i=performance.now();if(e){if(this.lastTime){const t=i-this.lastTime,s=r-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*s/t,o=this.hls;if(o.trigger(l.FPS_DROP,{currentDropped:s,currentDecoded:n,totalDroppedFrames:r}),a>0&&s>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(l.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:null,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!1,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!1,preserveManualLevelOnError:!1,certLoadPolicy:{default:Ps},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:Ps},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:P,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:class extends L{registerListeners(){const t=this.hls;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter(e=>e!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:r}=e;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:r}=e;if((null==r?void 0:r.action)===fe&&r.flags===ve){const t=this.levels;let i=this._pathwayPriority,s=this.pathwayId;if(e.context){const{groupId:r,pathwayId:i,type:n}=e.context;r&&t?s=this.getPathwayForGroupId(r,n,s):i&&(s=i)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!i&&t&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==s),e.details!==o.BUFFER_APPEND_ERROR||e.fatal?r.resolved||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${s} levels: ${t?t.length:t} priorities: ${zt(i)} penalized: ${zt(this.penalizedPathways)}`):r.resolved=!0}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const r=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),e=this.getLevelsForPathway(r),this.pathwayId=r}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach(t=>{i-r[t]>3e5&&delete r[t]});for(let i=0;i<t.length;i++){const s=t[i];if(s in r)continue;if(s===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(s),e.length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,lr(e),this.hls.trigger(l.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,r){const i=this.getLevelsForPathway(r).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(e===u&&i[r].hasAudioGroup(t)||e===c&&i[r].hasSubtitleGroup(t))return i[r].pathwayId;return r}clonePathways(t){const e=this.levels;if(!e)return;const r={},i={};t.forEach(t=>{const{ID:s,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===s))return;const o=this.getLevelsForPathway(n).map(t=>{const e=new Re(t.attrs);e["PATHWAY-ID"]=s;const n=e.AUDIO&&`${e.AUDIO}_clone_${s}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${s}`;n&&(r[e.AUDIO]=n,e.AUDIO=n),o&&(i[e.SUBTITLES]=o,e.SUBTITLES=o);const l=ni(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new jt({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)d.addGroupId("audio",`${t.audioGroups[e]}_clone_${s}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)d.addGroupId("text",`${t.subtitleGroups[e]}_clone_${s}`);return d});e.push(...o),si(this.audioTracks,r,a,s),si(this.subtitleTracks,i,a,s)})}loadSteeringManifest(t){const e=this.hls.config,r=e.loader;let i;this.loader&&this.loader.destroy(),this.loader=new r(e);try{i=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==i.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+t)}const s={responseType:"json",url:i.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},d={onSuccess:(t,e,r,s)=>{this.log(`Loaded steering manifest: "${i}"`);const n=t.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":d}=n;if(a)try{this.uri=new self.URL(a,i).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||r.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:i.toString()};this.hls.trigger(l.STEERING_MANIFEST_LOADED,h),d&&this.updatePathwayPriority(d)},onError:(t,e,r,i)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let s=1e3*this.timeToLoad;if(429===t.code){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(s=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,s)},onTimeout:(t,e,r)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(s,o,d)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const r=null==(e=this.hls)?void 0:e.media;!r||r.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}constructor(t){super("content-steering",t.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}},interstitialsController:void 0});function Fs(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Fs):Object.keys(t).reduce((e,r)=>(e[r]=Fs(t[r]),e),{}):t}function Ms(t,e){const r=t.loader;if(r!==_s&&r!==ws)e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=_s,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Ns extends Ir{registerListeners(){const{hls:t}=this;t&&(t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const r=this.media=e.media;Nr(r,"playing",this.onMediaPlaying),Nr(r,"waiting",this.onMediaWaiting),Nr(r,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:r}=this;r&&(Br(r,"playing",this.onMediaPlaying),Br(r,"waiting",this.onMediaWaiting),Br(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.media.currentTime;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){var r,i;const s=null==(r=this.hls)?void 0:r.config;if(!s)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,d=!this.seeking&&a,h=n.paused&&!a||n.ended||0===n.playbackRate;if(this.seeking=a,t!==e)return e&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!h&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(d||o)return void(o&&this.stallResolved(t));if(h)return this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(l.MEDIA_ENDED,{stalled:!1})));if(!wr.getBuffered(n).length)return void(this.nudgeRetry=0);const u=wr.bufferInfo(n,t,0),c=u.nextStart||0,f=this.fragmentTracker;if(a&&f&&this.hls){const e=Bs(this.hls.inFlightFragments,t),r=u.len>2,i=!c||e||c-t>2&&!f.getPartialFragment(t);if(r||i)return;this.moved=!1}const g=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&f){if(!(u.len>0)&&!c)return;const e=Math.max(c,u.start||0)-t,r=!(null==g||!g.live)?2*g.targetduration:2,i=Us(t,f);if(e>0&&(e<=r||i))return void(n.paused||this._trySkipBufferHole(i))}const m=s.detectStallWithCurrentTimeMs,p=self.performance.now(),v=this.waiting;let E=this.stalled;if(null===E){if(!(v>0&&p-v<m))return void(this.stalled=p);E=this.stalled=v}const y=p-E;if(!a&&(y>=m||v)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==g||!g.live)&&Math.abs(t-((null==g?void 0:g.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(l.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(u),!this.media||!this.hls)return}const S=wr.bufferInfo(n,t,s.maxBufferHole);this._tryFixBufferStall(S,y,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(l.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var r;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&i&&i.length>1&&t>i.end(0)){const r=wr.bufferedInfo(wr.timeRangesToArray(this.buffered.audio),t,0);if(r.len>1&&e>=r.start){const r=wr.timeRangesToArray(i),s=wr.bufferedInfo(r,e,0).bufferedIndex;if(s>-1&&s<r.length-1){const e=wr.bufferedInfo(r,t,0).bufferedIndex,i=r[s].end,n=r[s+1].start;if((-1===e||e>s)&&n-i<1&&t-i<2){const r=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${i} -> ${n} buffered index: ${e}`);this.warn(r.message),this.media.currentTime+=1e-6;let s=Us(t,this.fragmentTracker);s&&"fragment"in s?s=s.fragment:s||(s=void 0);const d=wr.bufferInfo(this.media,t,0);this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:r,reason:r.message,frag:s,buffer:d.len,bufferInfo:d})}}}}}_tryFixBufferStall(t,e,r){var i,s;const{fragmentTracker:n,media:a}=this,o=null==(i=this.hls)?void 0:i.config;if(!a||!n||!o)return;const l=null==(s=this.hls)?void 0:s.latestLevelDetails,d=Us(r,n);if(d||null!=l&&l.live&&r<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const h=t.buffered,u=this.adjacentTraversal(t,r);(h&&h.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-r<o.maxBufferHole||u))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const r=this.fragmentTracker,i=t.nextStart;if(r&&i){const t=r.getFragAtPos(e,f),s=r.getFragAtPos(i,f);if(t&&s)return s.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:r,stallReported:i,stalled:s}=this;if(!i&&null!==s&&r&&e){this.stallReported=!0;const i=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${zt(t)})`);this.warn(i.message),e.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len,bufferInfo:t,stalled:{start:s}})}}_trySkipBufferHole(t){var e;const{fragmentTracker:r,media:i}=this,s=null==(e=this.hls)?void 0:e.config;if(!i||!r||!s)return 0;const n=i.currentTime,d=wr.bufferInfo(i,n,0),h=n<d.start?d.start:d.nextStart;if(h&&this.hls){const e=d.len<=s.maxBufferHole,c=d.len>0&&d.len<1&&i.readyState<3,g=h-n;if(g>0&&(e||c)){if(g>s.maxBufferHole){let e=!1;if(0===n){const t=r.getAppendedFrag(0,f);t&&h<t.end&&(e=!0)}if(!e&&t){var u;if(null==(u=this.hls.loadLevelObj)||!u.details)return 0;if(Bs(this.hls.inFlightFragments,h))return 0;let e=!1,i=t.end;for(;i<h;){const t=Us(i,r);if(!t){e=!0;break}i+=t.duration}if(e)return 0}}const e=Math.max(h+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${e}`),this.moved=!0,i.currentTime=e,null==t||!t.gap){const r=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${e}`),i={type:a.MEDIA_ERROR,details:o.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:r,reason:r.message,buffer:d.len,bufferInfo:d};t&&("fragment"in t?i.part=t:i.frag=t),this.hls.trigger(l.ERROR,i)}return e}}return 0}_tryNudgeBuffer(t){const{hls:e,media:r,nudgeRetry:i}=this,s=null==e?void 0:e.config;if(!r||!s)return 0;const n=r.currentTime;if(this.nudgeRetry++,i<s.nudgeMaxRetry){const d=n+(i+1)*s.nudgeOffset,h=new Error(`Nudging 'currentTime' from ${n} to ${d}`);this.warn(h.message),r.currentTime=d,e.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_NUDGE_ON_STALL,error:h,fatal:!1,buffer:t.len,bufferInfo:t})}else{const r=new Error(`Playhead still not moving while enough data buffered @${n} after ${s.nudgeMaxRetry} nudges`);this.error(r.message),e.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.BUFFER_STALLED_ERROR,error:r,fatal:!0,buffer:t.len,bufferInfo:t})}}constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(l.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.registerListeners()}}function Bs(t,e){const r=$s(t.main);if(r&&r.start<=e)return r;const i=$s(t.audio);return i&&i.start<=e?i:null}function $s(t){if(!t)return null;switch(t.state){case Gr:case Ur:case jr:case qr:return null}return t.frag}function Us(t,e){return e.getAppendedFrag(t,f)||e.getPartialFragment(t)}function Gs(t,e){let r;try{r=new Event("addtrack")}catch(t){r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function Vs(t,e,r,i){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&t.cues.length>0){const s=function(t,e,r){const i=[],s=function(t,e){if(e<=t[0].startTime)return 0;const r=t.length-1;if(e>t[r].endTime)return-1;let i,s=0,n=r;for(;s<=n;)if(i=Math.floor((n+s)/2),e<t[i].startTime)n=i-1;else{if(!(e>t[i].startTime&&s<r))return i;s=i+1}return t[s].startTime-e<e-t[n].startTime?s:n}(t,e);if(s>-1)for(let n=s,a=t.length;n<a;n++){const s=t[n];if(s.startTime>=e&&s.endTime<=r)i.push(s);else if(s.startTime>r)return i}return i}(t.cues,e,r);for(let e=0;e<s.length;e++)i&&!i(s[e])||t.removeCue(s[e])}"disabled"===s&&(t.mode=s)}function Hs(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Ks(t,e,r,i,s){let n=new t(e,r,"");try{n.value=i,s&&(n.type=s)}catch(a){n=new t(e,r,zt(s?S({type:s},i):i))}return n}const Ys=(()=>{const t=Hs();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Ws{destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(l.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(l.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(l.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){var r;this.media=e.media,!1===(null==(r=e.overrides)?void 0:r.cueRemoval)&&(this.removeCues=!1)}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.removeCues&&function(t,e){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues)for(let r=t.cues.length;r--;)e&&t.cues[r].removeEventListener("enter",e),t.removeCue(t.cues[r]);"disabled"===r&&(t.mode=r)}(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const r=t[e];if("metadata"===r.kind&&"id3"===r.label)return Gs(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:i}=this.hls.config;if(!r&&!i)return;const{samples:s}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Hs();if(n)for(let t=0;t<s.length;t++){const e=s[t].type;if(e===wi.emsg&&!r||!i)continue;const a=_i(s[t].data),o=s[t].pts;let l=o+s[t].duration;l>Ys&&(l=Ys);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const r=a[t];if(!Ii(r)){this.updateId3CueEnds(o,e);const t=Ks(n,o,l,r,e);t&&this.id3Track.addCue(t)}}}}updateId3CueEnds(t,e){var r;const i=null==(r=this.id3Track)?void 0:r.cues;if(i)for(let r=i.length;r--;){const s=i[r];s.type===e&&s.startTime<t&&s.endTime===Ys&&(s.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:r,type:i}){const{id3Track:s,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(s&&(a||o)){let t;t="audio"===i?t=>t.type===wi.audioId3&&o:"video"===i?t=>t.type===wi.emsg&&a:t=>t.type===wi.audioId3&&o||t.type===wi.emsg&&a,Vs(s,e,r,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:s,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=Hs();if(!t.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:d}=t,h=Object.keys(d);let u=this.dateRangeCuesAppended;var c;if(l&&e)if(null!=(c=l.cues)&&c.length){const t=Object.keys(u).filter(t=>!h.includes(t));for(let e=t.length;e--;){var f;const r=t[e],i=null==(f=u[r])?void 0:f.cues;delete u[r],i&&Object.keys(i).forEach(t=>{const e=i[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{l.removeCue(e)}catch(t){}}})}}else u=this.dateRangeCuesAppended={};const g=t.fragments[t.fragments.length-1];if(0!==h.length&&i(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<h.length;t++){const e=h[t],r=d[e],i=r.startTime,s=u[e],n=(null==s?void 0:s.cues)||{};let a=(null==s?void 0:s.durationKnown)||!1,l=Ys;const{duration:c,endDate:f}=r;if(f&&null!==c)l=i+c,a=!0;else if(r.endOnNext&&!a){const t=h.reduce((t,e)=>{if(e!==r.id){const i=d[e];if(i.class===r.class&&i.startDate>r.startDate&&(!t||r.startDate<t.startDate))return i}return t},null);t&&(l=t.startTime,a=!0)}const g=Object.keys(r.attr);for(let t=0;t<g.length;t++){const d=g[t];if(!Ae(d))continue;const h=n[d];if(h)!a||null!=s&&s.durationKnown?Math.abs(h.startTime-i)>.01&&(h.startTime=i,h.endTime=l):h.endTime=l;else if(o){let t=r.attr[d];be(d)&&(t=N(t));const s=Ks(o,i,l,{key:d,data:t},wi.dateRange);s&&(s.id=e,this.id3Track.addCue(s),n[d]=s)}}u[e]={cues:n,dateRange:r,durationKnown:a}}}}constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(l.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}}class js{get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;const e=this.levelDetails;return e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||null===this.hls)return null;const{holdBack:e,partHoldBack:r,targetduration:i}=t,{liveSyncDuration:s,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&r||e;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==s?s:n*i);const d=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,d)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e)return null;const r=this.levelDetails;if(null===r)return null;const i=r.edge,s=t-e-this.edgeStalled,n=i-r.totalduration,a=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,s),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const r=t.buffered.length;return(r?t.buffered.end(r-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(l.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(l.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(l.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(l.ERROR,this.onError,this))}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,e){var r;e.details===o.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,e){var r,i;t.playbackRate!==e&&(null==(r=this.hls)||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(i=this.targetLatency)?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,e=this.levelDetails;if(!t||!e)return;this.currentTime=t.currentTime;const r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:s}=this.config;if(!i||1===s||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=r-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,s)),r=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20,i=Math.min(e,Math.max(1,r));this.changeMediaPlaybackRate(t,i)}else 1!==t.playbackRate&&0!==t.playbackRate&&this.changeMediaPlaybackRate(t,1)},this.hls=t,this.config=t.config,this.registerListeners()}}class qs extends ur{_registerListeners(){const{hls:t}=this;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(l.LEVEL_LOADED,this.onLevelLoaded,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this),t.on(l.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(l.LEVEL_LOADED,this.onLevelLoaded,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this),t.off(l.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const r=this.hls.config.preferManagedMediaSource,i=[],s={},n={};let a=!1,o=!1,l=!1;e.levels.forEach(t=>{const e=t.attrs;let{audioCodec:d,videoCodec:h}=t;d&&(t.audioCodec=d=Ot(d,r)||void 0),h&&(h=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const r=e[t].split(".");r.length>2&&"avc1"===r[0]&&(e[t]=`avc1.${parseInt(r[1]).toString(16)}${("000"+parseInt(r[2]).toString(16)).slice(-4)}`)}return e.join(",")}(h));const{width:u,height:c,unknownCodecs:f}=t,g=(null==f?void 0:f.length)||0;if(a||(a=!(!u||!c)),o||(o=!!h),l||(l=!!d),g||d&&!this.isAudioSupported(d)||h&&!this.isVideoSupported(h))return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);const{CODECS:m,"FRAME-RATE":p,"HDCP-LEVEL":v,"PATHWAY-ID":E,RESOLUTION:y,"VIDEO-RANGE":T}=e,S=`${`${E||"."}-`}${t.bitrate}-${y}-${p}-${m}-${T}-${v}`;if(s[S])if(s[S].uri===t.url||t.attrs["PATHWAY-ID"])s[S].addGroupId("audio",e.AUDIO),s[S].addGroupId("text",e.SUBTITLES);else{const e=n[S]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const r=this.createLevel(t);s[S]=r,i.push(r)}else{const e=this.createLevel(t);s[S]=e,n[S]=1,i.push(e)}}),this.filterAndSortMediaOptions(i,e,a,o,l)}createLevel(t){const e=new jt(t),r=t.supplemental;if(null!=r&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(t.message),e.supportedResult=w.getUnsupportedResult(t,[])}return e}isAudioSupported(t){return kt(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return kt(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,e,r,i,s){var n;let d=[],h=[],u=t;const c=(null==(n=e.stats)?void 0:n.parsing)||{};if((r||i)&&s&&(u=u.filter(({videoCodec:t,videoRange:e,width:r,height:i})=>{return(!!t||!(!r||!i))&&(!!(s=e)&&Gt.indexOf(s)>-1);var s})),0===u.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",r=t;e.levels.length&&(r=`one or more CODECS in variant not supported: ${zt(e.levels.map(t=>t.attrs.CODECS).filter((t,e,r)=>r.indexOf(t)===e))}`,this.warn(r),t+=` (${r})`);const i=new Error(t);this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:i,reason:r})}}),void(c.end=performance.now());e.audioTracks&&(d=e.audioTracks.filter(t=>!t.audioCodec||this.isAudioSupported(t.audioCodec)),Xs(d)),e.subtitles&&(h=e.subtitles,Xs(h));const f=u.slice(0);u.sort((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return Gt.indexOf(t.videoRange)-Gt.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const r=Ct(t.videoCodec),i=Ct(e.videoCodec);if(r!==i)return i-r}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const r=xt(t.codecSet),i=xt(e.codecSet);if(r!==i)return i-r}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let g=f[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==f.length))for(let t=0;t<f.length;t++)if(f[t].pathwayId===u[0].pathwayId){g=f[t];break}this._levels=u;for(let t=0;t<u.length;t++)if(u[t]===g){var m;this._firstLevel=t;const e=g.bitrate,r=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${e}`),void 0===(null==(m=this.hls.userConfig)?void 0:m.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>r&&r===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const p=s&&!i,v=this.hls.config,E=!(!v.audioStreamController||!v.audioTrackController),y={levels:u,audioTracks:d,subtitleTracks:h,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:s,video:i,altAudio:E&&!p&&d.some(t=>!!t.url)};c.end=performance.now(),this.hls.trigger(l.MANIFEST_PARSED,y)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const r=new Error("invalid level idx"),i=t<0;if(this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:r,reason:r.message}),i)return;t=Math.min(t,e.length-1)}const r=this.currentLevelIndex,i=this.currentLevel,s=i?i.attrs["PATHWAY-ID"]:void 0,n=e[t],d=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,r===t&&i&&s===d)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${d?" with Pathway "+d:""} from level ${r}${s?" with Pathway "+s:""}`);const h={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(l.LEVEL_SWITCHING,h);const u=n.details;if(!u||u.live){const t=this.switchParams(n.uri,null==i?void 0:i.details,u);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),r=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=r}}onError(t,e){!e.fatal&&e.context&&e.context.type===h&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===f){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const r=this._levels[e.level];null!=r&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(t,e){var r;const{level:i,details:s}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${i}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(s.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(i,e,t)}else null!=(r=e.deliveryDirectives)&&r.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const r=this.getUrlWithDirectives(t.uri,e),i=this.currentLevelIndex,s=t.attrs["PATHWAY-ID"],n=t.details,a=null==n?void 0:n.age;this.log(`Loading level index ${i}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${s?" Pathway "+s:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(l.LEVEL_LOADING,{url:r,level:i,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const r=this._levels.filter((e,r)=>r!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach(t=>t.level=-1)),!1));lr(r),this._levels=r,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=r.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(l.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(l.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}}function Xs(t){const e={};t.forEach(t=>{const r=t.groupId||"";t.id=e[r]=e[r]||0,e[r]++})}const zs="1.6.16",Qs={};let Zs=0;class Js{reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=Zs++;const e=this.hls.config,r=Bt(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:zt(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=Qs[t||zs];if(e&&1===e.clientCount--){const{worker:r,objectURL:i}=e;delete Qs[t||zs],i&&self.URL.revokeObjectURL(i),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 t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,r,i,s,n,a,o,l,d){var h,u;l.transmuxing.start=self.performance.now();const{instanceNo:c,transmuxer:g}=this,m=n?n.start:s.start,p=s.decryptdata,v=this.frag,E=!(v&&s.cc===v.cc),y=!(v&&l.level===v.level),T=v?l.sn-v.sn:-1,S=this.part?l.part-this.part.index:-1,L=0===T&&l.id>1&&l.id===(null==v?void 0:v.stats.chunkCount),R=!y&&(1===T||0===T&&(1===S||L&&S<=0)),A=self.performance.now();(y||T||0===s.stats.parsing.start)&&(s.stats.parsing.start=A),!n||!S&&R||(n.stats.parsing.start=A);const b=!(v&&(null==(h=s.initSegment)?void 0:h.url)===(null==(u=v.initSegment)?void 0:u.url)),D=new Ds(E,R,o,y,m,b);if(!R||E||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===f?"level":"track"}: ${l.level} id: ${l.id}\n        discontinuity: ${E}\n        trackSwitch: ${y}\n        contiguous: ${R}\n        accurateTimeOffset: ${o}\n        timeOffset: ${m}\n        initSegmentChange: ${b}`);const t=new bs(r,i,e,a,d);this.configureTransmuxer(t)}if(this.frag=s,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:c,cmd:"demux",data:t,decryptdata:p,chunkMeta:l,state:D},t instanceof ArrayBuffer?[t]:[]);else if(g){const e=g.push(t,p,l,D);As(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(r){const e=r.flush(t);As(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,r){this.hls&&(this.error=t,this.hls.trigger(l.ERROR,{type:a.MEDIA_ERROR,details:o.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:r}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):r&&r.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}constructor(t,e,r,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Zs++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=t=>{const e=t.data,r=this.hls;if(r&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var i;const t=null==(i=this.workerContext)?void 0:i.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":r.logger[e.data.logType]&&r.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,r.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message}  (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const s=t.config;this.hls=t,this.id=e,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=r,this.onFlush=i;const n=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===l.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new di,this.observer.on(l.FRAG_DECRYPTED,n),this.observer.on(l.ERROR,n);const d=Bt(s.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const r=this.hls.logger;if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(r.log(`loading Web Worker ${s.workerPath} for "${e}"`),this.workerContext=function(t){const e=Qs[t];if(e)return e.clientCount++,e;const r=new self.URL(t,self.location.href).href,i={worker:new self.Worker(r),scriptURL:r,clientCount:1};return Qs[t]=i,i}(s.workerPath)):(r.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Qs[zs];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),r=self.URL.createObjectURL(e),i={worker:new self.Worker(r),objectURL:r,clientCount:1};return Qs[zs]=i,i}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:d,id:e,config:zt(s)})}catch(i){r.warn(`Error setting up "${e}" Web Worker, fallback to inline`,i),this.terminateWorker(),this.error=null,this.transmuxer=new Ls(this.observer,d,s,"",e,t.logger)}return}}this.transmuxer=new Ls(this.observer,d,s,"",e,t.logger)}}function tn(){return self.SourceBuffer||self.WebKitSourceBuffer}function en(){if(!O())return!1;const t=tn();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class rn extends zr{registerListeners(){super.registerListeners();const{hls:t}=this;t.on(l.MANIFEST_PARSED,this.onManifestParsed,this),t.on(l.LEVEL_LOADING,this.onLevelLoading,this),t.on(l.LEVEL_LOADED,this.onLevelLoaded,this),t.on(l.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(l.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(l.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(l.BUFFER_CREATED,this.onBufferCreated,this),t.on(l.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(l.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(l.MANIFEST_PARSED,this.onManifestParsed,this),t.off(l.LEVEL_LOADED,this.onLevelLoaded,this),t.off(l.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(l.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(l.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(l.BUFFER_CREATED,this.onBufferCreated,this),t.off(l.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(l.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:r,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=i.startLevel;-1===t&&(i.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=i.firstAutoLevel),i.nextLoadLevel=t,this.level=i.loadLevel,this._hasEnoughToStart=!!e}r>0&&-1===t&&!e&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r),this.state=Gr,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=Ur}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Xr:{const{levels:t,level:e}=this,r=null==t?void 0:t[e],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=Gr;break}if(this.hls.nextLoadLevel!==this.level){this.state=Gr;break}break}case Kr:this.checkRetryDate()}this.state===Gr&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:r,media:i}=this;if(null===e||!i&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const s=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==r||!r[s])return;const n=r[s],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return 2===this.altAudio&&(t.type="video"),this.hls.trigger(l.BUFFER_EOS,t),void(this.state=jr)}if(!this.buffering)return;t.loadLevel!==s&&-1===t.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=t.nextLoadLevel=s;const d=n.details;if(!d||this.state===Xr||this.waitForLive(n))return this.level=s,this.state=Xr,void(this.startFragRequested=!1);const h=a.len,u=this.getMaxBufferLength(n.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const c=this.backtrackFragment?this.backtrackFragment.start:a.end;let g=this.getNextFragment(c,d);if(this.couldBacktrack&&!this.fragPrevious&&g&&Q(g)&&this.fragmentTracker.getState(g)!==mr){var m;const t=(null!=(m=this.backtrackFragment)?m:g).sn-d.startSN,e=d.fragments[t-1];e&&g.cc===e.cc&&(g=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,c)){if(!g.gap){const t=this.audioOnly&&!this.altAudio?j:q,e=(t===q?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,f)}g=this.getNextFragmentLoopLoading(g,d,a,f,u)}g&&(this.exceedsMaxBuffer(a,u,g)||(!g.initSegment||g.initSegment.data||this.bitrateTest||(g=g.initSegment),this.loadFragment(g,n,c)))}loadFragment(t,e,r){const i=this.fragmentTracker.getState(t);i===cr||i===gr?Q(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,r):this._loadInitSegment(t,e):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,f)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),0!==this.altAudio){var t;((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let r;const i=this.getAppendedFrag(e.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const s=this.getLevelDetails();if(null!=s&&s.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*s.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],i=this.fragLastKbps;r=i&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*i)+1:0}else r=0;const n=this.getBufferedFrag(e.currentTime+r);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,r=t.duration,i=Math.max(n.end,e+Math.min(Math.max(r-this.config.maxFragLookUpTolerance,r*(this.couldBacktrack?.5:.125)),r*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(i,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Vr:case Hr:case Kr:case Yr:case Wr:this.state=Gr}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,2===this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const r=e.media;Nr(r,"playing",this.onMediaPlaying),Nr(r,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:r}=this;r&&(Br(r,"playing",this.onMediaPlaying),Br(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(l.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(t,e){let r=!1,i=!1;for(let t=0;t<e.levels.length;t++){const s=e.levels[t].audioCodec;s&&(r=r||-1!==s.indexOf("mp4a.40.2"),i=i||-1!==s.indexOf("mp4a.40.5"))}this.audioCodecSwitch=r&&i&&!function(){var t;const e=tn();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:r}=this;if(!r||this.state!==Gr)return;const i=e.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=Xr)}onLevelLoaded(t,e){var r;const{levels:i,startFragRequested:s}=this,n=e.level,a=e.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const d=e.levelInfo,h=this.fragCurrent;!h||this.state!==Hr&&this.state!==Kr||h.level!==e.level&&h.loader&&this.abortCurrentFrag();let u=0;if(a.live||null!=(r=d.details)&&r.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,d.details,null==(c=this.levelLastLoaded)?void 0:c.details)}if(d.details=a,this.levelLastLoaded=d,s||this.setStartPosition(a,u),this.hls.trigger(l.LEVEL_UPDATED,{details:a,level:n}),this.state===Xr){if(this.waitForCdnTuneIn(a))return;this.state=Gr}s&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:r}=this;if(!r)return;const i=this.hls.liveSyncPosition,s=this.getLoadPosition(),n=t.fragmentStart,a=t.edge,o=s>=n-e.maxFragLookUpTolerance&&s<=a;if(null!==i&&r.duration>i&&(s<i||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&r.readyState<4||s<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),r.readyState))if(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var l;const t=wr.bufferInfo(r,i,0);if(null==(l=t.buffered)||!l.length)return void(r.currentTime=i);if(t.start<=s)return void(r.currentTime=i);const{nextStart:e}=wr.bufferedInfo(t.buffered,s,0);e&&(r.currentTime=e)}else r.currentTime=i}}_handleFragmentLoadProgress(t){var e;const r=t.frag,{part:i,payload:s}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const a=n[r.level];if(!a)return void this.warn(`Level ${r.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),void this.fragmentTracker.removeFragment(r);const l=a.videoCodec,d=o.PTSKnown||!o.live,h=null==(e=r.initSegment)?void 0:e.data,u=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new Js(this.hls,f,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,m=-1!==g,p=new Cr(r.level,r.sn,r.stats.chunkCount,s.byteLength,g,m),v=this.initPTS[r.cc];c.push(s,h,u,l,r,i,o.totalduration,d,p,v)}onAudioTrackSwitching(t,e){const r=this.hls,i=0!==this.altAudio;if(Jt(e.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i)return this.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once(l.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(l.AUDIO_TRACK_SWITCHED,e)}),void r.trigger(l.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});r.trigger(l.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const r=Jt(e.url,this.hls);if(r){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=r?2:0,this.tick()}onBufferCreated(t,e){const r=e.tracks;let i,s,n=!1;for(const t in r){const e=r[t];if("main"===e.id){if(s=t,i=e,"video"===t){const e=r[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:r,part:i}=e,s=r.type===f;if(s){if(this.fragContextChanged(r))return this.warn(`Fragment ${r.sn}${i?" p: "+i.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Wr&&(this.state=Gr));const t=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*t.total/(t.buffering.end-t.loading.first)),Q(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}const n=this.media;n&&(!this._hasEnoughToStart&&wr.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var r;if(e.fatal)this.state=qr;else switch(e.details){case o.FRAG_GAP:case o.FRAG_PARSING_ERROR:case o.FRAG_DECRYPT_ERROR:case o.FRAG_LOAD_ERROR:case o.FRAG_LOAD_TIMEOUT:case o.KEY_LOAD_ERROR:case o.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(f,e);break;case o.LEVEL_LOAD_ERROR:case o.LEVEL_LOAD_TIMEOUT:case o.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Xr||(null==(r=e.context)?void 0:r.type)!==h||(this.state=Gr);break;case o.BUFFER_ADD_CODEC_ERROR:case o.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case o.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case o.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=Gr,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==j||!this.altAudio){const t=(e===q?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e,f),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let r=this.startPosition;if(r>=0&&e<r){if(t.seeking)return void this.log(`could not seek to ${r}, already seeking at ${e}`);const i=this.timelineOffset;i&&r&&(r+=i);const s=this.getLevelDetails(),n=wr.getBuffered(t),a=n.length?n.start(0):0,o=a-r,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==s?void 0:s.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),r+=o,this.startPosition=r),e<r&&(this.log(`seek to target start position ${r} from current time ${e} buffer start ${a}`),t.currentTime=r)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(t=>{const{hls:r}=this,i=null==t?void 0:t.frag;if(!i||this.fragContextChanged(i))return;e.fragmentError=0,this.state=Gr,this.startFragRequested=!1,this.bitrateTest=!1;const s=i.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(l.FRAG_LOADED,t),i.bitrateTest=!1}).catch(e=>{this.state!==Ur&&this.state!==qr&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const e=this.playlistType,{hls:r}=this,{remuxResult:s,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:d,level:h}=a,{video:u,text:c,id3:f,initSegment:g}=s,{details:m}=h,p=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Yr,g){const t=g.tracks;if(t){const i=o.initSegment||o;if(this.unhandledEncryptionError(g,o))return;this._bufferInitSegment(h,t,i,n),r.trigger(l.FRAG_PARSING_INIT_SEGMENT,{frag:i,id:e,tracks:t})}const s=g.initPTS,a=g.timescale,d=this.initPTS[o.cc];if(i(s)&&(!d||d.baseTime!==s||d.timescale!==a)){const t=g.trackId;this.initPTS[o.cc]={baseTime:s,timescale:a,trackId:t},r.trigger(l.INIT_PTS_FOUND,{frag:o,id:e,initPTS:s,timescale:a,trackId:t})}}if(u&&m){p&&"audiovideo"===u.type&&this.logMuxedErr(o);const t=m.fragments[o.sn-1-m.startSN],e=o.sn===m.startSN,r=!t||o.cc>t.cc;if(!1!==s.independent){const{startPTS:t,endPTS:i,startDTS:s,endDTS:a}=u;if(d)d.elementaryStreams[u.type]={startPTS:t,endPTS:i,startDTS:s,endDTS:a};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!r&&(this.couldBacktrack=!0),u.dropped&&u.independent){const s=this.getMainFwdBufferInfo(),n=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=u.firstKeyFramePTS?u.firstKeyFramePTS:t;if(!e&&n<l-this.config.maxBufferHole&&!r)return void this.backtrack(o);r&&(o.gap=!0),o.setElementaryStreamInfo(u.type,o.start,i,o.start,a,!0)}else e&&t-(m.appliedTimelineOffset||0)>2&&(o.gap=!0);o.setElementaryStreamInfo(u.type,t,i,s,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,d,n,e||r)}else{if(!e&&!r)return void this.backtrack(o);o.gap=!0}}if(p){const{startPTS:t,endPTS:e,startDTS:r,endDTS:i}=p;d&&(d.elementaryStreams[j]={startPTS:t,endPTS:e,startDTS:r,endDTS:i}),o.setElementaryStreamInfo(j,t,e,r,i),this.bufferFragmentData(p,o,d,n)}if(m&&null!=f&&f.samples.length){const t={id:e,frag:o,details:m,samples:f.samples};r.trigger(l.FRAG_PARSING_METADATA,t)}if(m&&c){const t={id:e,frag:o,details:m,samples:c.samples};r.trigger(l.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${Q(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,r,i){if(this.state!==Yr)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(r));const{audio:s,video:n,audiovideo:a}=e;if(s){const r=t.audioCodec;let i=Ft(s.codec,r);"mp4a"===i&&(i="mp4a.40.5");const n=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){i&&(i=-1!==i.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=s.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&-1===n.indexOf("firefox")&&(i="mp4a.40.5")}i&&-1!==i.indexOf("mp4a.40.5")&&-1!==n.indexOf("android")&&"audio/mpeg"!==s.container&&(i="mp4a.40.2",this.log(`Android: force audio codec to ${i}`)),r&&r!==i&&this.log(`Swapping manifest audio codec "${r}" for "${i}"`),s.levelCodec=i,s.id=f,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${i||""}/${r||""}/${s.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=f;const r=n.codec;if(4===(null==r?void 0:r.length))switch(r){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${r}]${n.codec!==r?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio);const o=Object.keys(e);if(o.length){if(this.hls.trigger(l.BUFFER_CODECS,e),!this.hls)return;o.forEach(t=>{const s=e[t].initSegment;null!=s&&s.byteLength&&this.hls.trigger(l.BUFFER_APPENDING,{type:t,data:s,frag:r,part:null,chunkMeta:i,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,f)}get maxBufferLength(){const{levels:t,level:e}=this,r=null==t?void 0:t[e];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=Gr}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const r=t.currentTime;if(wr.isBuffered(t,r)?e=this.getAppendedFrag(r):wr.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,r=e.level;t&&e.sn===t.sn&&t.level===r||(this.fragPlaying=e,this.hls.trigger(l.FRAG_CHANGED,{frag:e}),t&&t.level===r||this.hls.trigger(l.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return i(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){var t;const e=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(i(e)){const t=this.getLevelDetails(),r=this.currentFrag||(t?ee(null,t.fragments,e):null);if(r){const t=r.programDateTime;if(null!==t){const i=t+1e3*(e-r.start);return new Date(i)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}constructor(t,e,r){super(t,e,r,"stream-controller",f),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const t=this.media,e=t?t.currentTime:null;if(null===e||!i(e))return;if(this.log(`Media seeked to ${e.toFixed(3)}`),!this.getBufferedFrag(e))return;const r=this.getFwdBufferInfoAtPos(t,e,f,0);null!==r&&0!==r.len?this.tick():this.warn(`Main forward buffer length at ${e} on "seeked" event ${r?r.len:"empty"})`)},this.registerListeners()}}class sn extends L{abort(t){for(const r in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[r].loader;if(i){var e;if(t&&t!==(null==(e=i.context)?void 0:e.frag.type))return;i.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const e=this.keyIdToKeyInfo[t].loader;e&&e.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,e=o.KEY_LOAD_ERROR,r,i,s){return new _r({type:a.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:s,error:r,networkDetails:i})}loadClear(t,e,r){return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(e=>this.loadInternal(t,e)):this.loadInternal(t)}loadInternal(t,e){var r,i;const s=t.decryptdata;if(!s){const r=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,r))}const n=s.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=nn(s);let l=this.keyIdToKeyInfo[a];if(null!=(r=l)&&r.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:t,keyInfo:l});if(this.emeController&&null!=(i=l)&&i.keyLoadPromise){switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(e=>{const{keyInfo:r}=e;return s.key=r.decryptdata.key,{frag:t,keyInfo:r}})}}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${s.keyId?" keyId: "+M(s.keyId):""} URI: ${s.uri} from ${t.type} ${t.level}`),l=this.keyIdToKeyInfo[a]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(l,t):this.loadKeyEME(l,t);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,t);default:return Promise.reject(this.createKeyLoadError(t,o.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(t,e){const r={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var i;if(!t.decryptdata.keyId&&null!=(i=e.initSegment)&&i.data){const r=function(t){const e=[];return vt(t,t=>e.push(t.subarray(8,24))),e}(e.initSegment.data);if(r.length){let e=r[0];e.some(t=>0!==t)?(this.log(`Using keyId found in init segment ${M(e)}`),Fe.setKeyIdForUri(t.decryptdata.uri,e)):(e=Fe.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${M(e)}`)),t.decryptdata.keyId=e}}if(!t.decryptdata.keyId&&!Q(e))return Promise.resolve(r);const s=this.emeController.loadKey(r);return(t.keyLoadPromise=s.then(e=>(t.mediaKeySessionContext=e,r))).catch(r=>{throw t.keyLoadPromise=null,"data"in r&&(r.data.frag=e),r})}return Promise.resolve(r)}loadKeyHTTP(t,e){const r=this.config,i=new(0,r.loader)(r);return e.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((s,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},l=r.keyLoadPolicy.default,d={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(t,e,r,i)=>{const{frag:a,keyInfo:l}=r,d=nn(l.decryptdata);if(!a.decryptdata||l!==this.keyIdToKeyInfo[d])return n(this.createKeyLoadError(a,o.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),i));l.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,l.loader=null,s({frag:a,keyInfo:l})},onError:(t,r,i,s)=>{this.resetLoader(r),n(this.createKeyLoadError(e,o.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),i,S({url:a.url,data:void 0},t)))},onTimeout:(t,r,i)=>{this.resetLoader(r),n(this.createKeyLoadError(e,o.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),i))},onAbort:(t,r,i)=>{this.resetLoader(r),n(this.createKeyLoadError(e,o.INTERNAL_ABORTED,new Error("key loading aborted"),i))}};i.load(a,d,h)})}resetLoader(t){const{frag:e,keyInfo:r,url:i}=t,s=r.loader;e.keyLoader===s&&(e.keyLoader=null,r.loader=null);const n=nn(r.decryptdata)||i;delete this.keyIdToKeyInfo[n],s&&s.destroy()}constructor(t,e){super("key-loader",e),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}}function nn(t){return t.uri}function an(t){const{type:e}=t;switch(e){case u:return g;case c:return m;default:return f}}function on(t,e){let r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}class ln{startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(l.MANIFEST_LOADING,this.onManifestLoading,this),t.on(l.LEVEL_LOADING,this.onLevelLoading,this),t.on(l.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(l.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(l.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(l.MANIFEST_LOADING,this.onManifestLoading,this),t.off(l.LEVEL_LOADING,this.onLevelLoading,this),t.off(l.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(l.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(l.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,r=e.pLoader,i=e.loader,s=new(r||i)(e);return this.loaders[t.type]=s,s}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:r}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:d,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:r,level:i,pathwayId:s,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:r,level:i,pathwayId:s,responseType:"text",type:h,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:r,groupId:i,url:s,deliveryDirectives:n,track:a}=e;this.load({id:r,groupId:i,level:null,responseType:"text",type:u,url:s,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:r,groupId:i,url:s,deliveryDirectives:n,track:a}=e;this.load({id:r,groupId:i,level:null,responseType:"text",type:c,url:s,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const r=this.loaders[h];if(r){const t=r.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(r.abort(),delete this.loaders[h])}}load(t){var e;const r=this.hls.config;let s,n=this.getInternalLoader(t);if(n){const e=this.hls.logger,r=n.context;if(r&&r.levelOrTrack===t.levelOrTrack&&(r.url===t.url||r.deliveryDirectives&&!t.deliveryDirectives))return void(r.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${r.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),n.abort()}if(s=t.type===d?r.manifestLoadPolicy.default:y({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),i(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===h&&null!==t.level?e=this.hls.levels[t.level].details:t.type===u&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===c&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,r=e.targetduration;if(t&&r){const e=1e3*Math.max(3*t,.8*r);s=y({},s,{maxTimeToFirstByteMs:Math.min(e,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,s.maxTimeToFirstByteMs)})}}}const a=s.errorRetry||s.timeoutRetry||{},o={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,r,i)=>{const s=this.getInternalLoader(r);this.resetInternalLoader(r.type);const n=t.data;e.parsing.start=performance.now(),Ge.isMediaPlaylist(n)||r.type!==d?this.handleTrackOrLevelPlaylist(t,e,r,i||null,s):this.handleMasterPlaylist(t,e,r,i)},onError:(t,e,r,i)=>{this.handleNetworkError(e,r,!1,t,i)},onTimeout:(t,e,r)=>{this.handleNetworkError(e,r,!0,void 0,t)}};n.load(t,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:r}=this.hls;(t||r)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,r,i){const s=this.hls,n=t.data,a=on(t,r),o=Ge.parseMasterPlaylist(n,a);if(o.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,r,o.playlistParsingError,i,e);const{contentSteering:d,levels:h,sessionData:u,sessionKeys:c,startTimeOffset:f,variableList:g}=o;this.variableList=g,h.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:r}=this.hls.config;let{audioCodec:i,videoCodec:s}=t;for(let n=e.length;n--;){const a=e[n];kt(a,"audio",r)?(t.audioCodec=i=i?`${i},${a}`:a,bt.audio[i.substring(0,4)]=2,e.splice(n,1)):kt(a,"video",r)&&(t.videoCodec=s=s?`${s},${a}`:a,bt.video[s.substring(0,4)]=2,e.splice(n,1))}}});const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=Ge.parseMasterPlaylistMedia(n,a,o);if(m.length){m.some(t=>!t.url)||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Re({}),bitrate:0,url:""}))}s.trigger(l.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:p,captions:v,contentSteering:d,url:a,stats:e,networkDetails:i,sessionData:u,sessionKeys:c,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,e,r,s,n){const a=this.hls,{id:o,level:h,type:u}=r,c=on(t,r),f=i(h)?h:i(o)?o:0,g=an(r),m=Ge.parseLevelPlaylist(t.data,c,f,g,0,this.variableList);if(u===d){const t={attrs:new Re({}),bitrate:0,details:m,name:"",url:c};m.requestScheduled=e.loading.start+sr(m,0),a.trigger(l.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:c,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),r.levelDetails=m,this.handlePlaylistLoaded(m,t,e,r,s,n)}handleManifestParsingError(t,e,r,i,s){this.hls.trigger(l.ERROR,{type:a.NETWORK_ERROR,details:o.MANIFEST_PARSING_ERROR,fatal:e.type===d,url:t.url,err:r,error:r,reason:r.message,response:t,context:e,networkDetails:i,stats:s})}handleNetworkError(t,e,r=!1,i,s){let n=`A network ${r?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===h?n+=`: ${t.level} id: ${t.id}`:t.type!==u&&t.type!==c||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const f=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let g=o.UNKNOWN,m=!1;const p=this.getInternalLoader(t);switch(t.type){case d:g=r?o.MANIFEST_LOAD_TIMEOUT:o.MANIFEST_LOAD_ERROR,m=!0;break;case h:g=r?o.LEVEL_LOAD_TIMEOUT:o.LEVEL_LOAD_ERROR,m=!1;break;case u:g=r?o.AUDIO_TRACK_LOAD_TIMEOUT:o.AUDIO_TRACK_LOAD_ERROR,m=!1;break;case c:g=r?o.SUBTITLE_TRACK_LOAD_TIMEOUT:o.SUBTITLE_LOAD_ERROR,m=!1}p&&this.resetInternalLoader(t.type);const v={type:a.NETWORK_ERROR,details:g,fatal:m,url:t.url,loader:p,context:t,error:f,networkDetails:e,stats:s};if(i){const r=(null==e?void 0:e.url)||t.url;v.response=S({url:r,data:void 0},i)}this.hls.trigger(l.ERROR,v)}handlePlaylistLoaded(t,e,r,i,s,n){const g=this.hls,{type:m,level:p,levelOrTrack:v,id:E,groupId:y,deliveryDirectives:T}=i,S=on(e,i),L=an(i);let R="number"==typeof i.level&&L===f?p:void 0;const A=t.playlistParsingError;if(A){if(this.hls.logger.warn(`${A} ${t.url}`),!g.config.ignorePlaylistParsingErrors)return void g.trigger(l.ERROR,{type:a.NETWORK_ERROR,details:o.LEVEL_PARSING_ERROR,fatal:!1,url:S,error:A,reason:A.message,response:e,context:i,level:R,parent:L,networkDetails:s,stats:r});t.playlistParsingError=null}if(!t.fragments.length){const n=t.playlistParsingError=new Error("No Segments found in Playlist");return void g.trigger(l.ERROR,{type:a.NETWORK_ERROR,details:o.LEVEL_EMPTY_ERROR,fatal:!1,url:S,error:n,reason:n.message,response:e,context:i,level:R,parent:L,networkDetails:s,stats:r})}switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),m){case d:case h:if(R)if(v){if(v!==g.levels[R]){const t=g.levels.indexOf(v);t>-1&&(R=t)}}else R=0;g.trigger(l.LEVEL_LOADED,{details:t,levelInfo:v||g.levels[0],level:R||0,id:E||0,stats:r,networkDetails:s,deliveryDirectives:T,withoutMultiVariant:m===d});break;case u:g.trigger(l.AUDIO_TRACK_LOADED,{details:t,track:v,id:E||0,groupId:y||"",stats:r,networkDetails:s,deliveryDirectives:T});break;case c:g.trigger(l.SUBTITLE_TRACK_LOADED,{details:t,track:v,id:E||0,groupId:y||"",stats:r,networkDetails:s,deliveryDirectives:T})}}constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}}const dn={supported:!1,smooth:!1,powerEfficient:!1},hn={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function un(t,e,r,i={}){const s=t.videoCodec;if(!s&&!t.audioCodec||!r)return Promise.resolve(hn);const n=[],a=function(t){var e;const r=null==(e=t.videoCodec)?void 0:e.split(","),i=fn(t),s=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return r?r.map(t=>{const e={contentType:It(Nt(t),"video"),width:s,height:n,bitrate:i,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,r){var i;const s=null==(i=t.audioCodec)?void 0:i.split(","),n=fn(t);if(s&&t.audioGroups)return t.audioGroups.reduce((t,i)=>{var a;const o=i?null==(a=e.groups[i])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===i){const i=parseFloat(e.channels||"");s.forEach(e=>{const s={contentType:It(e,"audio"),bitrate:r?cn(e,n):n};i&&(s.channels=""+i),t.push(s)})}return t},t):t},[]);return[]}(t,e,o>0),d=l.length;for(let t=o||1*d||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),d){e.audio=l[t%d];const r=e.audio.bitrate;e.video&&r&&(e.video.bitrate-=r)}n.push(e)}if(s){const t=navigator.userAgent;if(s.split(",").some(t=>Tt(t))&&At())return Promise.resolve(function(t,e){return{supported:!1,configurations:e,decodingInfoResults:[dn],error:t}}(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),n))}return Promise.all(n.map(t=>{const e=function(t){let e="";const{audio:r,video:i}=t;if(i){e+=`${$t(i.contentType)}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(r){e+=`${i?"_":""}${$t(r.contentType)}_c${r.channels}`}return e}(t);return i[e]||(i[e]=r.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:n,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t}))}function cn(t,e){if(e<=1)return 1;let r=128e3;return"ec-3"===t?r=768e3:"ac-3"===t&&(r=64e4),Math.min(e/2,r)}function fn(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}class gn{static get version(){return zs}static isMSESupported(){return en()}static isSupported(){return function(){if(!en())return!1;const t=O();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(It(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(It(e,"audio"))))}()}static getMediaSource(){return O()}static get Events(){return l}static get MetadataSchema(){return wi}static get ErrorTypes(){return a}static get ErrorDetails(){return o}static get DefaultConfig(){return gn.defaultConfig?gn.defaultConfig:Os}static set DefaultConfig(t){gn.defaultConfig=t}createController(t,e){if(t){const r=new t(this);return e&&e.push(r),r}return null}on(t,e,r=this){this._emitter.on(t,e,r)}once(t,e,r=this){this._emitter.once(t,e,r)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,r=this,i){this._emitter.off(t,e,r,i)}listeners(t){return this._emitter.listeners(t)}emit(t,e,r){return this._emitter.emit(t,e,r)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const r=t===l.ERROR;this.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.INTERNAL_EXCEPTION,fatal:r,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(l.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(l.ERROR,{type:a.OTHER_ERROR,details:o.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,r=e?t.media:t,i=e?t:{media:r};this._media=r,this.trigger(l.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(l.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(l.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const e=this.media,r=this._url,i=this._url=Y.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),e&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(l.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r<this.networkControllers.length&&(this.networkControllers[r].startLoad(t,e),this.started&&this.networkControllers);r++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[f]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[g]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[m]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&this.startLoad(e))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?r:3&r|8).toString(16)})}}}()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return Ut.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const r=t.length;for(let i=0;i<r;i++)if(t[i].maxBitrate>=e)return i;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:r}=this;let i;if(i=-1===e&&null!=t&&t.length?t.length-1:e,r)for(let e=i;e--;){const i=t[e].attrs["HDCP-LEVEL"];if(i&&i<=r)return e}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){var t;return(null==(t=this.interstitialsController)?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,e=this.allAudioTracks){return un(t,Zt(e),navigator.mediaCapabilities)}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new di,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const e=this.logger=function(t,e,r){const i=b();if("object"==typeof console&&!0===t||"object"==typeof t){const s=["debug","log","info","warn","error"];s.forEach(e=>{i[e]=D(e,t,r)});try{i.log(`Debug logs enabled for "${e}" in hls.js version 1.6.16`)}catch(t){return b()}s.forEach(e=>{k[e]=D(e,t)})}else y(k,i);return i}(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=function(t,e,r){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=Fs(t),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[n],o=[];s.forEach(r=>{const s=`${t}Loading${r}`,l=e[s];if(void 0!==l&&a){o.push(s);const t=i[n].default;switch(e[n]={default:t},r){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&r.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${zt(e[n])}`)}),S(S({},i),e)}(gn.DefaultConfig,t,e);this.userConfig=t,r.progressive&&Ms(r,e);const{abrController:i,bufferController:s,capLevelController:n,errorController:a,fpsController:o}=r,d=new a(this),h=this.abrController=new i(this),u=new pr(this),c=r.interstitialsController,f=c?this.interstitialsController=new c(this,gn):null,g=this.bufferController=new s(this,u),m=this.capLevelController=new n(this),p=new o(this),v=new ln(this),E=r.contentSteeringController,T=E?new E(this):null,L=this.levelController=new qs(this,T),R=new Ws(this),A=new sn(this.config,this.logger),_=this.streamController=new rn(this,u,A),I=this.gapController=new Ns(this,u);m.setStreamController(_),p.setStreamController(_);const C=[v,L,_];f&&C.splice(1,0,f),T&&C.splice(1,0,T),this.networkControllers=C;const x=[h,g,I,m,p,R,u];this.audioTrackController=this.createController(r.audioTrackController,C);const w=r.audioStreamController;w&&C.push(this.audioStreamController=new w(this,u,A)),this.subtitleTrackController=this.createController(r.subtitleTrackController,C);const P=r.subtitleStreamController;P&&C.push(this.subtititleStreamController=new P(this,u,A)),this.createController(r.timelineController,x),A.emeController=this.emeController=this.createController(r.emeController,x),this.cmcdController=this.createController(r.cmcdController,x),this.latencyController=this.createController(js,x),this.coreComponents=x,C.push(d);const O=d.onErrorOut;"function"==typeof O&&this.on(l.ERROR,O,d),this.on(l.MANIFEST_LOADED,v.onManifestLoaded,v)}}gn.defaultConfig=void 0;w.KeySystemFormats,w.KeySystems,w.SubtitleStreamController,w.TimelineController,w.requestMediaKeySystemAccess}};