ranui
Version:
A framework-agnostic Web Components UI library built on native custom elements, with TypeScript types, light/dark theming, SSR and PWA support.
41 lines • 521 kB
JavaScript
var N=Number.isFinite||function(e){return typeof e=="number"&&isFinite(e)},Oa=Number.isSafeInteger||function(e){return typeof e=="number"&&Math.abs(e)<=xa},xa=Number.MAX_SAFE_INTEGER||9007199254740991,$=(function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e})({}),L=(function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e})({}),g=(function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e})({}),X={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},U={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},it=class{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},Fa=class{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new it(e),this.fast_=new it(t),this.defaultTTFB_=i,this.ttfb_=new it(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new it(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new it(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new it(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function Na(e,t,s){return(t=Ua(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function te(){return te=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)({}).hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},te.apply(null,arguments)}function Oi(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),s.push.apply(s,i)}return s}function J(e){for(var t=1;t<arguments.length;t++){var s=arguments[t]!=null?arguments[t]:{};t%2?Oi(Object(s),!0).forEach(function(i){Na(e,i,s[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):Oi(Object(s)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(s,i))})}return e}function Ba(e,t){if(typeof e!="object"||!e)return e;var s=e[Symbol.toPrimitive];if(s!==void 0){var i=s.call(e,t);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Ua(e){var t=Ba(e,"string");return typeof t=="symbol"?t:t+""}var _e=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=Ye,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}},Ye=function(){},$a={trace:Ye,debug:Ye,log:Ye,warn:Ye,info:Ye,error:Ye};function Hs(){return te({},$a)}function Ga(e,t){const s=self.console[e];return s?s.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):Ye}function xi(e,t,s){return t[e]?t[e].bind(t):Ga(e,s)}var Ys=Hs();function Ka(e,t,s){const i=Hs();if(typeof console=="object"&&e===!0||typeof e=="object"){const r=["debug","log","info","warn","error"];r.forEach(n=>{i[n]=xi(n,e,s)});try{i.log(`Debug logs enabled for "${t}" in hls.js version 1.6.17`)}catch{return Hs()}r.forEach(n=>{Ys[n]=xi(n,e)})}else te(Ys,i);return i}var ee=Ys;function We(e=!0){if(!(typeof self>"u"))return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Va(e){return typeof self<"u"&&e===self.ManagedMediaSource}function Qr(e,t){const s=Object.keys(e),i=Object.keys(t),r=s.length,n=i.length;return!r||!n||r===n&&!s.some(a=>i.indexOf(a)===-1)}function be(e,t=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(e);if(t){const h=l.indexOf("\0");return h!==-1?l.substring(0,h):l}return l.replace(/\0/g,"")}const s=e.length;let i,r,n,a="",o=0;for(;o<s;){if(i=e[o++],i===0&&t)return a;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(i);break;case 12:case 13:r=e[o++],a+=String.fromCharCode((i&31)<<6|r&63);break;case 14:r=e[o++],n=e[o++],a+=String.fromCharCode((i&15)<<12|(r&63)<<6|(n&63)<<0)}}return a}function fe(e){let t="";for(let s=0;s<e.length;s++){let i=e[s].toString(16);i.length<2&&(i="0"+i),t+=i}return t}function Zr(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Ha(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ts={exports:{}},Fi;function Ya(){return Fi||(Fi=1,(function(e,t){(function(s){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,h,c){if(c=c||{},l=l.trim(),h=h.trim(),!h){if(!c.alwaysNormalize)return l;var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(h);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return c.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):h;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var m=r.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(p.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)p.path=f.path,d.params||(p.params=f.params,d.query||(p.query=f.query));else{var E=f.path,y=E.substring(0,E.lastIndexOf("/")+1)+d.path;p.path=o.normalizePath(y)}return p.path===null&&(p.path=c.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(p)},parseURL:function(l){var h=i.exec(l);return h?{scheme:h[1]||"",netLoc:h[2]||"",path:h[3]||"",params:h[4]||"",query:h[5]||"",fragment:h[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(n,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};e.exports=o})()})(Ts)),Ts.exports}var ci=Ya(),ui=class{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}}},se={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Jr=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,qa(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[se.AUDIO]:null,[se.VIDEO]:null,[se.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new ui),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=ci.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[se.AUDIO]=null,e[se.VIDEO]=null,e[se.AUDIOVIDEO]=null}};function oe(e){return e.sn!=="initSegment"}var Ss=class extends Jr{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(N(e)&&N(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=N(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!N(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return oe(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:a}=this,o=a[e];if(!o){a[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n};return}o.startPTS=Math.min(o.startPTS,t),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,r)}},Wa=class extends Jr{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function en(e,t){const s=Object.getPrototypeOf(e);if(s){const i=Object.getOwnPropertyDescriptor(s,t);return i||en(s,t)}}function qa(e,t){const s=en(e,t);s&&(s.enumerable=!0,Object.defineProperty(e,t,s))}var Ni=Math.pow(2,32)-1,ja=[].push,tn={video:1,audio:2,id3:3,text:4};function le(e){return String.fromCharCode.apply(null,e)}function sn(e,t){const s=e[t]<<8|e[t+1];return s<0?65536+s:s}function V(e,t){const s=rn(e,t);return s<0?4294967296+s:s}function Bi(e,t){let s=V(e,t);return s*=Math.pow(2,32),s+=V(e,t+4),s}function rn(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Xa(e){const t=e.byteLength;for(let s=0;s<t;){const i=V(e,s);if(i>8&&e[s+4]===109&&e[s+5]===111&&e[s+6]===111&&e[s+7]===102)return!0;s=i>1?s+i:t}return!1}function q(e,t){const s=[];if(!t.length)return s;const i=e.byteLength;for(let r=0;r<i;){const n=V(e,r),a=le(e.subarray(r+4,r+8)),o=n>1?r+n:i;if(a===t[0])if(t.length===1)s.push(e.subarray(r+8,o));else{const l=q(e.subarray(r+8,o),t.slice(1));l.length&&ja.apply(s,l)}r=o}return s}function za(e){const t=[],s=e[0];let i=8;const r=V(e,i);i+=4;let n=0,a=0;s===0?(n=V(e,i),a=V(e,i+4),i+=8):(n=Bi(e,i),a=Bi(e,i+8),i+=16),i+=2;let o=e.length+a;const l=sn(e,i);i+=2;for(let h=0;h<l;h++){let c=i;const u=V(e,c);c+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return ee.warn("SIDX has hierarchical references (not supported)"),null;const f=V(e,c);c+=4,t.push({referenceSize:d,subsegmentDuration:f,info:{duration:f/r,start:o,end:o+d-1}}),o+=d,c+=4,i=c}return{earliestPresentationTime:n,timescale:r,version:s,referencesCount:l,references:t}}function nn(e){const t=[],s=q(e,["moov","trak"]);for(let i=0;i<s.length;i++){const r=s[i],n=q(r,["tkhd"])[0];if(n){let a=n[0];const o=V(n,a===0?12:20),l=q(r,["mdia","mdhd"])[0];if(l){a=l[0];const h=V(l,a===0?12:20),c=q(r,["mdia","hdlr"])[0];if(c){const u=le(c.subarray(8,12)),d={soun:se.AUDIO,vide:se.VIDEO}[u],f=q(r,["mdia","minf","stbl","stsd"])[0],m=Qa(f);d?(t[o]={timescale:h,type:d,stsd:m},t[d]=J({timescale:h,id:o},m)):t[o]={timescale:h,type:u,stsd:m}}}}}return q(e,["moov","mvex","trex"]).forEach(i=>{const r=V(i,4),n=t[r];n&&(n.default={duration:V(i,12),flags:V(i,20)})}),t}function Qa(e){const t=e.subarray(8),s=t.subarray(86),i=le(t.subarray(4,8));let r=i,n;const a=i==="enca"||i==="encv";a&&q(q(t,[i])[0].subarray(i==="enca"?28:78),["sinf"]).forEach(l=>{const h=q(l,["schm"])[0];if(h){const c=le(h.subarray(4,8));if(c==="cbcs"||c==="cenc"){const u=q(l,["frma"])[0];u&&(r=le(u))}}});const o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const l=q(s,["avcC"])[0];l&&l.length>3&&(r+="."+xt(l[1])+xt(l[2])+xt(l[3]),n=Ot(o==="avc1"?"dva1":"dvav",s));break}case"mp4a":{const l=q(t,[i])[0],h=q(l.subarray(28),["esds"])[0];if(h&&h.length>7){let c=4;if(h[c++]!==3)break;c=As(h,c),c+=2;const u=h[c++];if(u&128&&(c+=2),u&64&&(c+=h[c++]),h[c++]!==4)break;c=As(h,c);const d=h[c++];if(d===64)r+="."+xt(d);else break;if(c+=12,h[c++]!==5)break;c=As(h,c);const f=h[c++];let m=(f&248)>>3;m===31&&(m+=1+((f&7)<<3)+((h[c]&224)>>5)),r+="."+m}break}case"hvc1":case"hev1":{const l=q(s,["hvcC"])[0];if(l&&l.length>12){const h=l[1],c=["","A","B","C"][h>>6],u=h&31,d=V(l,2),f=(h&32)>>5?"H":"L",m=l[12],p=l.subarray(6,12);r+="."+c+u,r+="."+Za(d).toString(16).toUpperCase(),r+="."+f+m;let E="";for(let y=p.length;y--;){const T=p[y];(T||E)&&(E="."+T.toString(16).toUpperCase()+E)}r+=E}n=Ot(o=="hev1"?"dvhe":"dvh1",s);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":r=Ot(r,s)||r;break;case"vp09":{const l=q(s,["vpcC"])[0];if(l&&l.length>6){const h=l[4],c=l[5],u=l[6]>>4&15;r+="."+xe(h)+"."+xe(c)+"."+xe(u)}break}case"av01":{const l=q(s,["av1C"])[0];if(l&&l.length>2){const h=l[1]>>>5,c=l[1]&31,u=l[2]>>>7?"H":"M",d=(l[2]&64)>>6,f=(l[2]&32)>>5,m=h===2&&d?f?12:10:d?10:8,p=(l[2]&16)>>4,E=(l[2]&8)>>3,y=(l[2]&4)>>2,T=l[2]&3;r+="."+h+"."+xe(c)+u+"."+xe(m)+"."+p+"."+E+y+T+"."+xe(1)+"."+xe(1)+"."+xe(1)+".0",n=Ot("dav1",s)}break}}return{codec:r,encrypted:a,supplemental:n}}function Ot(e,t){const s=q(t,["dvvC"]),i=s.length?s[0]:q(t,["dvcC"])[0];if(i){const r=i[2]>>1&127,n=i[2]<<5&32|i[3]>>3&31;return e+"."+xe(r)+"."+xe(n)}}function Za(e){let t=0;for(let s=0;s<32;s++)t|=(e>>s&1)<<31-s;return t>>>0}function As(e,t){const s=t+5;for(;e[t++]&128&&t<s;);return t}function xt(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function xe(e){return(e<10?"0":"")+e}function Ja(e,t){if(!e||!t)return;const s=t.keyId;s&&t.isCommonEncryption&&an(e,(i,r)=>{const n=i.subarray(8,24);n.some(a=>a!==0)||(ee.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${fe(n)} -> ${fe(s)}`),i.set(s,8))})}function eo(e){const t=[];return an(e,s=>t.push(s.subarray(8,24))),t}function an(e,t){q(e,["moov","trak"]).forEach(s=>{const i=q(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let n=q(r,["enca"]);const a=n.length>0;a||(n=q(r,["encv"])),n.forEach(o=>{q(a?o.subarray(28):o.subarray(78),["sinf"]).forEach(l=>{const h=on(l);h&&t(h,a)})})})}function on(e){const t=q(e,["schm"])[0];if(t){const s=le(t.subarray(4,8));if(s==="cbcs"||s==="cenc"){const i=q(e,["schi","tenc"])[0];if(i)return i}}}function to(e,t,s){const i={},r=q(e,["moof","traf"]);for(let n=0;n<r.length;n++){const a=r[n],o=q(a,["tfhd"])[0],l=V(o,4),h=t[l];if(!h)continue;i[l]||(i[l]={start:NaN,duration:0,sampleCount:0,timescale:h.timescale,type:h.type});const c=i[l],u=q(a,["tfdt"])[0];if(u){const v=u[0];let S=V(u,4);v===1&&(S===Ni?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=Ni+1,S+=V(u,8))),N(S)&&(!N(c.start)||S<c.start)&&(c.start=S)}const d=h.default,f=V(o,0)|d?.flags;let m=d?.duration||0;f&8&&(f&2?m=V(o,12):m=V(o,8));const p=q(a,["trun"]);let E=c.start||0,y=0,T=m;for(let v=0;v<p.length;v++){const S=p[v],R=V(S,4),A=c.sampleCount;c.sampleCount+=R;const I=S[3]&1,D=S[3]&4,P=S[2]&1,_=S[2]&2,M=S[2]&4,B=S[2]&8;let x=8,K=R;for(I&&(x+=4),D&&R&&(!(S[x+1]&1)&&c.keyFrameIndex===void 0&&(c.keyFrameIndex=A),x+=4,P?(T=V(S,x),x+=4):T=m,_&&(x+=4),B&&(x+=4),E+=T,y+=T,K--);K--;)P?(T=V(S,x),x+=4):T=m,_&&(x+=4),M&&(S[x+1]&1||c.keyFrameIndex===void 0&&(c.keyFrameIndex=c.sampleCount-(K+1),c.keyFrameStart=E),x+=4),B&&(x+=4),E+=T,y+=T;!y&&m&&(y+=m*R)}c.duration+=y}if(!Object.keys(i).some(n=>i[n].duration)){let n=1/0,a=0;const o=q(e,["sidx"]);for(let l=0;l<o.length;l++){const h=za(o[l]);if(h!=null&&h.references){n=Math.min(n,h.earliestPresentationTime/h.timescale);const c=h.references.reduce((u,d)=>u+d.info.duration||0,0);a=Math.max(a,c+h.earliestPresentationTime/h.timescale)}}a&&N(a)&&Object.keys(i).forEach(l=>{i[l].duration||(i[l].duration=a*i[l].timescale-i[l].start)})}return i}function so(e){const t={valid:null,remainder:null},s=q(e,["moof"]);if(s.length<2)return t.remainder=e,t;const i=s[s.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}function De(e,t){const s=new Uint8Array(e.length+t.length);return s.set(e),s.set(t,e.length),s}function Ui(e,t){const s=[],i=t.samples,r=t.timescale,n=t.id;let a=!1;return q(i,["moof"]).map(o=>{const l=o.byteOffset-8;q(o,["traf"]).map(h=>{const c=q(h,["tfdt"]).map(u=>{const d=u[0];let f=V(u,4);return d===1&&(f*=Math.pow(2,32),f+=V(u,8)),f/r})[0];return c!==void 0&&(e=c),q(h,["tfhd"]).map(u=>{const d=V(u,4),f=V(u,0)&16777215,m=(f&1)!==0,p=(f&2)!==0,E=(f&8)!==0;let y=0;const T=(f&16)!==0;let v=0;const S=(f&32)!==0;let R=8;d===n&&(m&&(R+=8),p&&(R+=4),E&&(y=V(u,R),R+=4),T&&(v=V(u,R),R+=4),S&&(R+=4),t.type==="video"&&(a=ps(t.codec)),q(h,["trun"]).map(A=>{const I=A[0],D=V(A,0)&16777215,P=(D&1)!==0;let _=0;const M=(D&4)!==0,B=(D&256)!==0;let x=0;const K=(D&512)!==0;let F=0;const O=(D&1024)!==0,Y=(D&2048)!==0;let k=0;const w=V(A,4);let G=8;P&&(_=V(A,G),G+=4),M&&(G+=4);let W=_+l;for(let Q=0;Q<w;Q++){if(B?(x=V(A,G),G+=4):x=y,K?(F=V(A,G),G+=4):F=v,O&&(G+=4),Y&&(I===0?k=V(A,G):k=rn(A,G),G+=4),t.type===se.VIDEO){let z=0;for(;z<F;){const Z=V(i,W);W+=4,io(a,i[W])&&di(i.subarray(W,W+Z),a?2:1,e+k/r,s),W+=Z,z+=Z+4}}e+=x/r}}))})})}),s}function ps(e){if(!e)return!1;const t=e.substring(0,4);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function io(e,t){if(e){const s=t>>1&63;return s===39||s===40}else return(t&31)===6}function di(e,t,s,i){const r=ln(e);let n=0;n+=t;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(l===255);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(l===255);const h=r.length-n;let c=n;if(o<h)n+=o;else if(o>h){ee.error(`Malformed SEI payload. ${o} is too small, only ${h} bytes left to parse.`);break}if(a===4){if(r[c++]===181){const u=sn(r,c);if(c+=2,u===49){const d=V(r,c);if(c+=4,d===1195456820){const f=r[c++];if(f===3){const m=r[c++],p=31&m,E=64&m,y=E?2+p*3:0,T=new Uint8Array(y);if(E){T[0]=m;for(let v=1;v<y;v++)T[v]=r[c++]}i.push({type:f,payloadType:a,pts:s,bytes:T})}}}}}else if(a===5&&o>16){const u=[];for(let m=0;m<16;m++){const p=r[c++].toString(16);u.push(p.length==1?"0"+p:p),(m===3||m===5||m===7||m===9)&&u.push("-")}const d=o-16,f=new Uint8Array(d);for(let m=0;m<d;m++)f[m]=r[c++];i.push({payloadType:a,pts:s,uuid:u.join(""),userData:be(f),userDataBytes:f})}}}function ln(e){const t=e.byteLength,s=[];let i=1;for(;i<t-2;)e[i]===0&&e[i+1]===0&&e[i+2]===3?(s.push(i+2),i+=2):i++;if(s.length===0)return e;const r=t-s.length,n=new Uint8Array(r);let a=0;for(i=0;i<r;a++,i++)a===s[0]&&(a++,s.shift()),n[i]=e[a];return n}function ro(e){const t=e[0];let s="",i="",r=0,n=0,a=0,o=0,l=0,h=0;if(t===0){for(;le(e.subarray(h,h+1))!=="\0";)s+=le(e.subarray(h,h+1)),h+=1;for(s+=le(e.subarray(h,h+1)),h+=1;le(e.subarray(h,h+1))!=="\0";)i+=le(e.subarray(h,h+1)),h+=1;i+=le(e.subarray(h,h+1)),h+=1,r=V(e,12),n=V(e,16),o=V(e,20),l=V(e,24),h=28}else if(t===1){h+=4,r=V(e,h),h+=4;const u=V(e,h);h+=4;const d=V(e,h);for(h+=4,a=2**32*u+d,Oa(a)||(a=Number.MAX_SAFE_INTEGER,ee.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=V(e,h),h+=4,l=V(e,h),h+=4;le(e.subarray(h,h+1))!=="\0";)s+=le(e.subarray(h,h+1)),h+=1;for(s+=le(e.subarray(h,h+1)),h+=1;le(e.subarray(h,h+1))!=="\0";)i+=le(e.subarray(h,h+1)),h+=1;i+=le(e.subarray(h,h+1)),h+=1}const c=e.subarray(h,e.byteLength);return{schemeIdUri:s,value:i,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:c}}function no(e,...t){const s=t.length;let i=8,r=s;for(;r--;)i+=t[r].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(e,4),r=0,i=8;r<s;r++)n.set(t[r],i),i+=t[r].byteLength;return n}function ao(e,t,s){if(e.byteLength!==16)throw new RangeError("Invalid system id");let i,r;i=0,r=new Uint8Array;let n;i>0?(n=new Uint8Array(4),t.length>0&&new DataView(n.buffer).setUint32(0,t.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),no([112,115,115,104],new Uint8Array([i,0,0,0]),e,n,r,a,s)}function oo(e){const t=[];if(e instanceof ArrayBuffer){const s=e.byteLength;let i=0;for(;i+32<s;){const r=lo(new DataView(e,i));t.push(r),i+=r.size}}return t}function lo(e){const t=e.getUint32(0),s=e.byteOffset,i=e.byteLength;if(i<t)return{offset:s,size:i};if(e.getUint32(4)!==1886614376)return{offset:s,size:t};const r=e.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:s,size:t};const n=e.buffer,a=fe(new Uint8Array(n,s+12,16));let o=null,l=null,h=0;if(r===0)h=28;else{const u=e.getUint32(28);if(!u||i<32+u*16)return{offset:s,size:t};o=[];for(let d=0;d<u;d++)o.push(new Uint8Array(n,s+32+d*16,16));h=32+u*16}if(!h)return{offset:s,size:t};const c=e.getUint32(h);return t-32<c?{offset:s,size:t}:(l=new Uint8Array(n,s+h+4,c),{version:r,systemId:a,kids:o,data:l,offset:s,size:t})}var hn=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),pt={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 fi(e,t){const s=pt[t];return!!s&&!!s[e.slice(0,4)]}function Dt(e,t,s=!0){return!e.split(",").some(i=>!gi(i,t,s))}function gi(e,t,s=!0){var i;const r=We(s);return(i=r?.isTypeSupported(_t(e,t)))!=null?i:!1}function _t(e,t){return`${t}/mp4;codecs=${e}`}function $i(e){if(e){const t=e.substring(0,4);return pt.video[t]}return 2}function rs(e){const t=hn();return e.split(",").reduce((s,i)=>{const r=t&&ps(i)?9:pt.video[i];return r?(r*2+s)/(s?3:2):(pt.audio[i]+s)/(s?2:1)},0)}var Is={};function ho(e,t=!0){if(Is[e])return Is[e];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let r=0;r<s.length;r++){var i;if(gi(s[r],"audio",t))return Is[e]=s[r],s[r];if(s[r]==="mp3"&&(i=We(t))!=null&&i.isTypeSupported("audio/mpeg"))return""}return e}var co=/flac|opus|mp4a\.40\.34/i;function ns(e,t=!0){return e.replace(co,s=>ho(s.toLowerCase(),t))}function uo(e,t){const s=[];if(e){const i=e.split(",");for(let r=0;r<i.length;r++)fi(i[r],"video")||s.push(i[r])}return t&&s.push(t),s.join(",")}function jt(e,t){if(e&&(e.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)!==-1)&&(Gi(e,"audio")||Gi(e,"video")))return e;if(t){const s=t.split(",");if(s.length>1){if(e){for(let i=s.length;i--;)if(s[i].substring(0,4)===e.substring(0,4))return s[i]}return s[0]}}return t||e}function Gi(e,t){return fi(e,t)&&gi(e,t)}function fo(e){const t=e.split(",");for(let s=0;s<t.length;s++){const i=t[s].split(".");i.length>2&&i[0]==="avc1"&&(t[s]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return t.join(",")}function go(e){if(e.startsWith("av01.")){const t=e.split("."),s=["0","111","01","01","01","0"];for(let i=t.length;i>4&&i<10;i++)t[i]=s[i-4];return t.join(".")}return e}function Ki(e){const t=We(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ws(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var mo={supported:!0,powerEfficient:!0,smooth:!0},po={supported:!1,smooth:!1,powerEfficient:!1},cn={supported:!0,configurations:[],decodingInfoResults:[mo]};function un(e,t){return{supported:!1,configurations:t,decodingInfoResults:[po],error:e}}function Eo(e,t,s,i,r,n){const a=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=n?.audioCodec,h=n?.channels,c=h?parseInt(h):l?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=t.groups[o[0]].channels:u=o.reduce((d,f)=>{if(f){const m=t.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(p=>{d[p]=(d[p]||0)+m.channels[p]})}return d},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(d=>ps(d))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||e.videoRange!=="SDR"&&e.videoRange!==s||e.bitrate>Math.max(r,8e6))||!!u&&N(c)&&Object.keys(u).some(d=>parseInt(d)>c)}function dn(e,t,s,i={}){const r=e.videoCodec;if(!r&&!e.audioCodec||!s)return Promise.resolve(cn);const n=[],a=yo(e),o=a.length,l=vo(e,t,o>0),h=l.length;for(let c=o||1*h||1;c--;){const u={type:"media-source"};if(o&&(u.video=a[c%o]),h){u.audio=l[c%h];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}n.push(u)}if(r){const c=navigator.userAgent;if(r.split(",").some(u=>ps(u))&&hn())return Promise.resolve(un(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${c})`),n))}return Promise.all(n.map(c=>{const u=So(c);return i[u]||(i[u]=s.decodingInfo(c))})).then(c=>({supported:!c.some(u=>!u.supported),configurations:n,decodingInfoResults:c})).catch(c=>({supported:!1,configurations:n,decodingInfoResults:[],error:c}))}function yo(e){var t;const s=(t=e.videoCodec)==null?void 0:t.split(","),i=fn(e),r=e.width||640,n=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return s?s.map(l=>{const h={contentType:_t(go(l),"video"),width:r,height:n,bitrate:i,framerate:a};return o!=="sdr"&&(h.transferFunction=o),h}):[]}function vo(e,t,s){var i;const r=(i=e.audioCodec)==null?void 0:i.split(","),n=fn(e);return r&&e.audioGroups?e.audioGroups.reduce((a,o)=>{var l;const h=o?(l=t.groups[o])==null?void 0:l.tracks:null;return h?h.reduce((c,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");r.forEach(f=>{const m={contentType:_t(f,"audio"),bitrate:s?To(f,n):n};d&&(m.channels=""+d),c.push(m)})}return c},a):a},[]):[]}function To(e,t){if(t<=1)return 1;let s=128e3;return e==="ec-3"?s=768e3:e==="ac-3"&&(s=64e4),Math.min(t/2,s)}function fn(e){return Math.ceil(Math.max(e.bitrate*.9,e.averageBitrate)/1e3)*1e3||1}function So(e){let t="";const{audio:s,video:i}=e;if(i){const r=Ws(i.contentType);t+=`${r}_r${i.height}x${i.width}f${Math.ceil(i.framerate)}${i.transferFunction||"sd"}_${Math.ceil(i.bitrate/1e5)}`}if(s){const r=Ws(s.contentType);t+=`${i?"_":""}${r}_c${s.channels}`}return t}var qs=["NONE","TYPE-0","TYPE-1",null];function Ao(e){return qs.indexOf(e)>-1}var as=["SDR","PQ","HLG"];function Io(e){return!!e&&as.indexOf(e)>-1}var Xt={No:"",Yes:"YES",v2:"v2"};function Vi(e){const{canSkipUntil:t,canSkipDateRanges:s,age:i}=e,r=i<t/2;return t&&r?s?Xt.v2:Xt.Yes:Xt.No}var Hi=class{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},Pt=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Yi(this._audioGroups,e)}hasSubtitleGroup(e){return Yi(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function Yi(e,t){return!t||!e?!1:e.indexOf(t)!==-1}function Lo(){if(typeof matchMedia=="function"){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return e.matches===!0}return!1}function Ro(e,t){let s=!1,i=[];if(e&&(s=e!=="SDR",i=[e]),t){i=t.allowedVideoRanges||as.slice(0);const r=i.join("")!=="SDR"&&!t.videoCodec;s=t.preferHDR!==void 0?t.preferHDR:r&&Lo(),s||(i=["SDR"])}return{preferHDR:s,allowedVideoRanges:i}}var bo=e=>{const t=new WeakSet;return(s,i)=>{if(e&&(i=e(s,i)),typeof i=="object"&&i!==null){if(t.has(i))return;t.add(i)}return i}},ie=(e,t)=>JSON.stringify(e,bo(t));function Do(e,t,s,i,r){const n=Object.keys(e),a=i?.channels,o=i?.audioCodec,l=r?.videoCodec,h=a&&parseInt(a)===2;let c=!1,u=!1,d=1/0,f=1/0,m=1/0,p=1/0,E=0,y=[];const{preferHDR:T,allowedVideoRanges:v}=Ro(t,r);for(let I=n.length;I--;){const D=e[n[I]];c||(c=D.channels[2]>0),d=Math.min(d,D.minHeight),f=Math.min(f,D.minFramerate),m=Math.min(m,D.minBitrate),v.filter(P=>D.videoRanges[P]>0).length>0&&(u=!0)}d=N(d)?d:0,f=N(f)?f:0;const S=Math.max(1080,d),R=Math.max(30,f);m=N(m)?m:s,s=Math.max(m,s),u||(t=void 0);const A=n.length>1;return{codecSet:n.reduce((I,D)=>{const P=e[D];if(D===I)return I;if(y=u?v.filter(_=>P.videoRanges[_]>0):[],A){if(P.minBitrate>s)return Me(D,`min bitrate of ${P.minBitrate} > current estimate of ${s}`),I;if(!P.hasDefaultAudio)return Me(D,"no renditions with default or auto-select sound found"),I;if(o&&D.indexOf(o.substring(0,4))%5!==0)return Me(D,`audio codec preference "${o}" not found`),I;if(a&&!h){if(!P.channels[a])return Me(D,`no renditions with ${a} channel sound found (channels options: ${Object.keys(P.channels)})`),I}else if((!o||h)&&c&&P.channels[2]===0)return Me(D,"no renditions with stereo sound found"),I;if(P.minHeight>S)return Me(D,`min resolution of ${P.minHeight} > maximum of ${S}`),I;if(P.minFramerate>R)return Me(D,`min framerate of ${P.minFramerate} > maximum of ${R}`),I;if(!y.some(_=>P.videoRanges[_]>0))return Me(D,`no variants with VIDEO-RANGE of ${ie(y)} found`),I;if(l&&D.indexOf(l.substring(0,4))%5!==0)return Me(D,`video codec preference "${l}" not found`),I;if(P.maxScore<E)return Me(D,`max score of ${P.maxScore} < selected max of ${E}`),I}return I&&(rs(D)>=rs(I)||P.fragmentError>e[I].fragmentError)?I:(p=P.minIndex,E=P.maxScore,D)},void 0),videoRanges:y,preferHDR:T,minFramerate:f,minBitrate:m,minIndex:p}}function Me(e,t){ee.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function gn(e){return e.reduce((t,s)=>{let i=t.groups[s.groupId];i||(i=t.groups[s.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(s);const r=s.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||s.default,i.hasAutoSelect=i.hasAutoSelect||s.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function _o(e,t,s,i){return e.slice(s,i+1).reduce((r,n,a)=>{if(!n.codecSet)return r;const o=n.audioGroups;let l=r[n.codecSet];l||(r[n.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,n.bitrate);const h=Math.min(n.height,n.width);return l.minHeight=Math.min(l.minHeight,h),l.minFramerate=Math.min(l.minFramerate,n.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,n.score),l.fragmentError+=n.fragmentError,l.videoRanges[n.videoRange]=(l.videoRanges[n.videoRange]||0)+1,o&&o.forEach(c=>{if(!c)return;const u=t.groups[c];u&&(l.hasDefaultAudio=l.hasDefaultAudio||t.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{l.channels[d]=(l.channels[d]||0)+u.channels[d]}))}),r},{})}function Wi(e){if(!e)return e;const{lang:t,assocLang:s,characteristics:i,channels:r,audioCodec:n}=e;return{lang:t,assocLang:s,characteristics:i,channels:r,audioCodec:n}}function Ne(e,t,s){if("attrs"in e){const i=t.indexOf(e);if(i!==-1)return i}for(let i=0;i<t.length;i++){const r=t[i];if(et(e,r,s))return i}return-1}function et(e,t,s){const{groupId:i,name:r,lang:n,assocLang:a,default:o}=e,l=e.forced;return(i===void 0||t.groupId===i)&&(r===void 0||t.name===r)&&(n===void 0||Po(n,t.lang))&&(n===void 0||t.assocLang===a)&&(o===void 0||t.default===o)&&(l===void 0||t.forced===l)&&(!("characteristics"in e)||Co(e.characteristics||"",t.characteristics))&&(s===void 0||s(e,t))}function Po(e,t="--"){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}function Co(e,t=""){const s=e.split(","),i=t.split(",");return s.length===i.length&&!s.some(r=>i.indexOf(r)===-1)}function Ze(e,t){const{audioCodec:s,channels:i}=e;return(s===void 0||(t.audioCodec||"").substring(0,4)===s.substring(0,4))&&(i===void 0||i===(t.channels||"2"))}function ko(e,t,s,i,r){const n=t[i],a=t.reduce((u,d,f)=>{const m=d.uri;return(u[m]||(u[m]=[])).push(f),u},{})[n.uri];a.length>1&&(i=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),c=qi(t,i,u=>{if(u.videoRange!==o||u.frameRate!==l||u.codecSet.substring(0,4)!==h)return!1;const d=u.audioGroups;return Ne(e,s.filter(f=>!d||d.indexOf(f.groupId)!==-1),r)>-1});return c>-1?c:qi(t,i,u=>{const d=u.audioGroups;return Ne(e,s.filter(f=>!d||d.indexOf(f.groupId)!==-1),r)>-1})}function qi(e,t,s){for(let i=t;i>-1;i--)if(s(e[i]))return i;for(let i=t+1;i<e.length;i++)if(s(e[i]))return i;return-1}function os(e,t){var s;return!!e&&e!==((s=t.loadLevelObj)==null?void 0:s.uri)}var wo=class extends _e{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:n}=this,{autoLevelEnabled:a,media:o}=n;if(!i||!o)return;const l=performance.now(),h=r?r.stats:i.stats,c=r?r.duration:i.duration,u=l-h.loading.start,d=n.minAutoLevel,f=i.level,m=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||f<=d){this.clearTimer(),this._nextAutoLevel=-1;return}if(!a)return;const p=m>-1&&m!==f,E=!!t||p;if(!E&&(o.paused||!o.playbackRate||!o.readyState))return;const y=n.mainForwardBufferInfo;if(!E&&y===null)return;const T=this.bwEstimator.getEstimateTTFB(),v=Math.abs(o.playbackRate);if(u<=Math.max(T,1e3*(c/(v*2))))return;const S=y?y.len/v:0,R=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&R>-1,I=this.getBwEstimate(),D=n.levels,P=D[f],_=Math.max(h.loaded,Math.round(c*(i.bitrate||P.averageBitrate)/8));let M=A?u-R:u;M<1&&A&&(M=Math.min(u,h.loaded*8/I));const B=A?h.loaded*1e3/M:0,x=T/1e3,K=B?(_-h.loaded)/B:_*8/I+x;if(K<=S)return;const F=B?B*8:I,O=((s=t?.details||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,Y=this.hls.config.abrBandWidthUpFactor;let k=Number.POSITIVE_INFINITY,w;for(w=f-1;w>d;w--){const z=D[w].maxBitrate,Z=!D[w].details||O;if(k=this.getTimeToLoadFrag(x,F,c*z,Z),k<Math.min(S,c+x))break}if(k>=K||k>c*10)return;A?this.bwEstimator.sample(u-Math.min(T,R),h.loaded):this.bwEstimator.sampleTTFB(u);const G=D[w].maxBitrate;this.getBwEstimate()*Y>G&&this.resetEstimator(G);const W=this.findBestLevel(G,d,w,0,S,1,1);W>-1&&(w=W),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${f} is loading too slowly;
Fragment duration: ${i.duration.toFixed(3)}
Time to underbuffer: ${S.toFixed(3)} s
Estimated load time for current fragment: ${K.toFixed(3)} s
Estimated load time for down switch fragment: ${k.toFixed(3)} s
TTFB estimate: ${R|0} ms
Current BW estimate: ${N(I)?I|0:"Unknown"} bps
New BW estimate: ${this.getBwEstimate()|0} bps
Switching to level ${w} @ ${G|0} bps`),n.nextLoadLevel=n.nextAutoLevel=w,this.clearTimer();const Q=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===w&&w>0){const z=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${w>0?"and switching down":""}
Fragment duration: ${i.duration.toFixed(3)} s
Time to underbuffer: ${z.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,w>d){let Z=this.findBestLevel(this.hls.levels[d].bitrate,d,w,0,z,1,1);Z===-1&&(Z=d),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Z,this.resetEstimator(this.hls.levels[Z].bitrate)}}};p||K>k*2?Q():this.timer=self.setInterval(Q,k*1e3),n.trigger(g.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Fa(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.FRAG_LOADING,this.onFragLoading,this),e.on(g.FRAG_LOADED,this.onFragLoaded,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this),e.on(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(g.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.FRAG_LOADING,this.onFragLoading,this),e.off(g.FRAG_LOADED,this.onFragLoaded,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this),e.off(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(g.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){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(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case L.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const n=performance.now(),a=r?r.stats:s.stats,o=n-a.loading.start,l=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&l>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(h,l),a.loaded)}else this.bwEstimator.sampleTTFB(o)}break}}}getTimeToLoadFrag(e,t,s,i){return e+s/t+(i?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;N(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===U.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,n=this.hls.levels[t.level],a=(n.loaded?n.loaded.bytes:0)+i.loaded,o=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:a,duration:o},n.realBitrate=Math.round(8*a/o)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(g.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==U.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,a=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!t||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const i=t&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const r=this.hls.levels;if(r.length>Math.max(e,i)&&r[e].loadError<=r[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,a=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,c=r.abrBandWidthUpFactor;if(l){const p=this.findBestLevel(o,n,i,l,0,h,c);if(p>=0)return this.rebufferNotice=-1,p}let u=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const p=this.bitrateTestDelay;p&&(u=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-p,this.info(`bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=c=1)}const d=this.findBestLevel(o,n,i,l,u,h,c);if(this.rebufferNotice!==d&&(this.rebufferNotice=d,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${d}`)),d>-1)return d;const f=s.levels[n],m=s.loadLevelObj;return m&&f?.bitrate<m.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,a){var o;const l=i+r,h=this.lastLoadedFragLevel,c=h===-1?this.hls.firstLevel:h,{fragCurrent:u,partCurrent:d}=this,{levels:f,allAudioTracks:m,loadLevel:p,config:E}=this.hls;if(f.length===1)return 0;const y=f[c],T=!!((o=this.hls.latestLevelDetails)!=null&&o.live),v=p===-1||h===-1;let S,R="SDR",A=y?.frameRate||0;const{audioPreference:I,videoPreference:D}=E,P=this.audioTracksByGroup||(this.audioTracksByGroup=gn(m));let _=-1;if(v){if(this.firstSelection!==-1)return this.firstSelection;const F=Do(this.codecTiers||(this.codecTiers=_o(f,P,t,s)),R,e,I,D),{codecSet:O,videoRanges:Y,minFramerate:k,minBitrate:w,minIndex:G,preferHDR:W}=F;_=G,S=O,R=W?Y[Y.length-1]:Y[0],A=k,e=Math.max(e,w),this.log(`picked start tier ${ie(F)}`)}else S=y?.codecSet,R=y?.videoRange;const M=d?d.duration:u?u.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,x=[];for(let F=s;F>=t;F--){var K;const O=f[F],Y=F>c;if(!O)continue;if(E.useMediaCapabilities&&!O.supportedResult&&!O.supportedPromise){const z=navigator.mediaCapabilities;typeof z?.decodingInfo=="function"&&Eo(O,P,R,A,e,I)?(O.supportedPromise=dn(O,P,z,this.supportedCache),O.supportedPromise.then(Z=>{if(!this.hls)return;O.supportedResult=Z;const Ee=this.hls.levels,Se=Ee.indexOf(O);Z.error?this.warn(`MediaCapabilities decodingInfo error: "${Z.error}" for level ${Se} ${ie(Z)}`):Z.supported?Z.decodingInfoResults.some(ke=>ke.smooth===!1||ke.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Se} not smooth or powerEfficient: ${ie(Z)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Se} ${ie(Z)}`),Se>-1&&Ee.length>1&&(this.log(`Removing unsupported level ${Se}`),this.hls.removeLevel(Se),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Z=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Z}`)})):O.supportedResult=cn}if((S&&O.codecSet!==S||R&&O.videoRange!==R||Y&&A>O.frameRate||!Y&&A>0&&A<O.frameRate||(K=O.supportedResult)!=null&&(K=K.decodingInfoResults)!=null&&K.some(z=>z.smooth===!1))&&(!v||F!==_)){x.push(F);continue}const k=O.details,w=(d?k?.partTarget:k?.averagetargetduration)||M;let G;Y?G=a*e:G=n*e;const W=M&&i>=M*2&&r===0?O.averageBitrate:O.maxBitrate,Q=this.getTimeToLoadFrag(B,G,W*w,k===void 0);if(G>=W&&(F===h||O.loadError===0&&O.fragmentError===0)&&(Q<=B||!N(Q)||T&&!this.bitrateTestDelay||Q<l)){const z=this.forcedAutoLevel;return F!==p&&(z===-1||z!==p)&&(x.length&&this.trace(`Skipped level(s) ${x.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[x[0]].codecs}" ${f[x[0]].videoRange}; not compatible with "${S}" ${R}`),this.info(`switch candidate:${c}->${F} adjustedbw(${Math.round(G)})-bitrate=${Math.round(G-W)} ttfb:${B.toFixed(1)} avgDuration:${w.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${Q.toFixed(1)} firstSelection:${v} codecSet:${O.codecSet} videoRange:${O.videoRange} hls.loadLevel:${p}`)),v&&(this.firstSelection=F),F}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}},mn={search:function(e,t){let s=0,i=e.length-1,r=null,n=null;for(;s<=i;){r=(s+i)/2|0,n=e[r];const a=t(n);if(a>0)s=r+1;else if(a<0)i=r-1;else return n}return null}};function Mo(e,t,s){if(t===null||!Array.isArray(e)||!e.length||!N(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let i=0;i<e.length;++i){const r=e[i];if(xo(t,s,r))return r}return null}function tt(e,t,s=0,i=0,r=.005){let n=null;if(e){n=t[1+e.sn-t[0].sn]||null;const o=e.endDTS-s;o>0&&o<15e-7&&(s+=15e-7),n&&e.level!==n.level&&n.end<=e.end&&(n=t[2+e.sn-t[0].sn]||null)}else s===0&&t[0].start===0&&(n=t[0]);if(n&&((!e||e.level===n.level)&&ji(s,i,n)===0||Oo(n,e,Math.min(r,i))))return n;const a=mn.search(t,ji.bind(null,s,i));return a&&(a!==e||!n)?a:n}function Oo(e,t,s){if(t&&t.start===0&&t.level<e.level&&(t.endPTS||0)>0){const i=t.tagList.reduce((r,n)=>(n[0]==="INF"&&(r+=parseFloat(n[1])),r),s);return e.start<=i}return!1}function ji(e=0,t=0,s){if(s.start<=e&&s.start+s.duration>e)return 0;const i=Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-i<=e?1:s.start-i>e&&s.start?-1:0}function xo(e,t,s){const i=Math.min(t,s.duration+(s.deltaPTS?s.deltaPTS:0))*1e3;return(s.endProgramDateTime||0)-i>e}function pn(e,t,s){if(e&&e.startCC<=t&&e.endCC>=t){let i=e.fragments;const{fragmentHint:r}=e;r&&(i=i.concat(r));let n;return mn.search(i,a=>a.cc<t?1:a.cc>t?-1:(n=a,a.end<=s?1:a.start>s?-1:0)),n||null}return null}function ls(e){switch(e.details){case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_TIMEOUT:case L.LEVEL_LOAD_TIMEOUT:case L.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function En(e){return e.details.startsWith("key")}function yn(e){return En(e)&&!!e.frag&&!e.frag.decryptdata}function Xi(e,t){const s=ls(t);return e.default[`${s?"timeout":"error"}Retry`]}function mi(e,t){const s=e.backoff==="linear"?1:Math.pow(2,t);return Math.min(s*e.retryDelayMs,e.maxRetryDelayMs)}function zi(e){return J(J({},e),{errorRetry:null,timeoutRetry:null})}function hs(e,t,s,i){if(!e)return!1;const r=i?.code,n=t<e.maxNumRetry&&(Fo(r)||!!s);return e.shouldRetry?e.shouldRetry(e,t,s,i,n):n}function Fo(e){return js(e)||!!e&&(e<400||e>499)}function js(e){return e===0&&navigator.onLine===!1}var ue={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Ie={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},No=class extends _e{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(g.ERROR,this.onError,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(g.ERROR,this.onError,this),e.off(g.ERROR,this.onErrorOut,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===U.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(r=>i.indexOf(r.groupId)>=0).some(r=>{var n;return(n=r.details)==null?void 0:n.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case L.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=ft();return}case L.FRAG_GAP:case L.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ue.SendAlternateToPenaltyBox;return;case L.LEVEL_EMPTY_ERROR:case L.LEVEL_PARSING_ERROR:{var n;const o=t.parent===U.MAIN?t.level:i.loadLevel;t.details===L.LEVEL_EMPTY_ERROR&&((n=t.context)!=null&&(n=n.levelDetails)!=null&&n.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o))}return;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.SUBTITLE_LOAD_ERROR:case L.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const o=i.loadLevelObj;if(o&&(r.type===X.AUDIO_TRACK&&o.hasAudioGroup(r.groupId)||r.type===X.SUBTITLE_TRACK&&o.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=ue.SendAlternateToPenaltyBox,t.errorAction.flags=Ie.MoveAllAlternatesMatchingHost;return}}return;case L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:ue.SendAlternateToPenaltyBox,flags:Ie.MoveAllAlternatesMatchingHDCP};return;case L.KEY_SYSTEM_SESSION_UPDATE_FAILED:case L.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case L.KEY_SYSTEM_NO_SESSION:t.errorAction={action:ue.SendAlternateToPenaltyBox,flags:Ie.MoveAllAlternatesMatchingKey};return;case L.BUFFER_ADD_CODEC_ERROR:case L.REMUX_ALLOC_ERROR:case L.BUFFER_APPEND_ERROR:if(!t.errorAction){var a;t.errorAction=this.getLevelSwitchAction(t,(a=t.level)!=null?a:i.loadLevel)}return;case L.INTERNAL_EXCEPTION:case L.BUFFER_APPENDING_ERROR:case L.BUFFER_FULL_ERROR:case L.LEVEL_SWITCH_ERROR:case L.BUFFER_STALLED_ERROR:case L.BUFFER_SEEK_OVER_HOLE:case L.BUFFER_NUDGE_ON_STALL:t.errorAction=ft();return}t.type===$.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ft())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=Xi(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(hs(i,r,ls(e),e.response))return{action:ue.RetryRequest,flags:Ie.None,retryConfig:i,retryCount:r};const n=this.getLevelSwitchAction(e,t);return i&&(n.retryConfig=i,n.retryCount=r),n}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,a=Xi(En(e)?n:r,e),o=t.levels.reduce((h,c)=>h+c.fragmentError,0);if(i&&(e.details!==L.FRAG_GAP&&i.fragmentError++,!yn(e)&&hs(a,o,ls(e),e.response)))return{action:ue.RetryRequest,flags:Ie.None,retryConfig:a,retryCount:o};const l=this.getLevelSwitchAction(e,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const l=e.details;i.loadError++,l===L.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:c,loadLevel:u,minAutoLevel:d,maxAutoLevel:f}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const m=(r=e.frag)==null?void 0:r.type,p=(m===U.AUDIO&&l===L.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===L.BUFFER_ADD_CODEC_ERROR||l===L.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:v})=>i.audioCodec!==v),E=e.sourceBufferName==="video"&&(l===L.BUFFER_ADD_CODEC_ERROR||l===L.BUFFER_APPEND_ERROR)&&c.some(({codecSet:v,audioCodec:S})=>i.codecSet!==v&&i.audioCodec===S),{type:y,groupId:T}=(n=e.context)!=null?n:{};for(let v=c.length;v--;){const S=(v+u)%c.length;if(S!==u&&S>=d&&S<=f&&c[S].loadError===0){var a,o;const R=c[S];if(l===L.FRAG_GAP&&m===U.MAIN&&e.frag){const A=c[S].details;if(A){const I=tt(e.frag,A.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(y===X.AUDIO_TRACK&&R.hasAudioGroup(T)||y===X.SUBTITLE_TRACK&&R.hasSubtitleGroup(T))continue;if(m===U.AUDIO&&(a=i.audioGroups)!=null&&a.some(A=>R.hasAudioGroup(A))||m===U.SUBTITLE&&(o=i.subtitleGroups)!=null&&o.some(A=>R.hasSubtitleGroup(A))||p&&i.audioCodec===R.audioCodec||E&&i.codecSet===R.codecSet||!p&&i.codecSet!==R.codecSet)continue}h=S;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:ue.SendAlternateToPenaltyBox,flags:Ie.None,nextAutoLevel:h}}return{action:ue.SendAlternateToPenaltyBox,flags:Ie.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case ue.DoNothing:break;case ue.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==L.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case ue.RetryRequest:}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Ie.None:this.switchLevel(e,r);break;case Ie.MoveAllAlternatesMatchingHDCP:{const o=this.getVariantLevelIndex(e.frag),l=t.levels[o],h=l?.attrs["HDCP-LEVEL"];if(s.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){t.maxHdcpLevel=qs[qs.indexOf(h)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Ie.MoveAllAlternatesMatchingKey:{const o=e.decryptdata;if(o){const l=this.hls.levels,h=l.length;for(let u=h;u--;)if(this.variantHasKey(l[u],o)){var n,a;this.log(`Banned key found in level ${u} (${l[u].bitrate}bps) or audio group "${(n=l[u].audioGroups)==null?void 0:n.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${fe(o.keyId||[])}`),l[u].fragmentError++,l[u].loadError++,this.log(`Removing level ${u} with key error (${e.error})`),this.hls.removeLevel(u)}const c=e.frag;if(this.hls.levels.length<h)s.resolved=!0;else if(c&&c.type!==U.MAIN){const u=c.decryptdata;u&&!o.matches(u)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===L.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Ws(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}};function ft(e){const t={action:ue.DoNothing,flags:Ie.None};return e&&(t.resolved=!0),t}var he={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Bo=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.BUFFER_APPENDED,this.onBufferAppended,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this),e.on(g.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.BUFFER_APPENDED,this.onBufferAppended,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this),e.off(g.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const a=i[r[n]];if(a?.body.type===t&&(!s||a.buffered)){const o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=i?.fragment.sn||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||n>=o.body.sn)return;if(!o.buffered&&(!o.loaded||r)){o.body.type===s&&this.removeFragment(o.body);return}const l=o.range[e];if(l){if(l.time.length===0){this.removeFragment(o.body);return}l.time.some(h=>{const c=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return c&&this.removeFragment(o.body),c})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,i=rt(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(t).forEach(a=>{const o=s.elementaryStreams[a];if(!o)return;const l=t[a],h=n||o.partial===!0;r.range[a]=this.getBufferedTimes(s,e.part,h,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),Ft(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Qi(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=rt(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,a=e.end,o=e.minEndPTS||a,l=e.maxStartPTS||n;for(let h=0;h<i.length;h++){const c=i.start(h)-this.bufferPadding,u=i.end(h)+this.bufferPadding;if(l>=c&&o<=u){r.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(a,i.end(h))});break}else if(n<u&&a>c){const d=Math.max(n,i.start(h)),f=Math.min(a,i.end(h));f>d&&(r.partial=!0,r.time.push({startPTS:d,endPTS:f}))}else if(a<=c)break}return r}getPartialFragment(e){let t=null,s,i,r,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const h=o[l];h&&Ft(h)&&(i=h.body.start-a,r=h.body.end+a,e>=i&&e<=r&&(s=Math.min(e-i,r-e),n<=s&&(t=h.body,n=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Ft(t))}getState(e){const t=rt(e),s=this.fragments[t];return s?s.buffered?Ft(s)?he.PARTIAL:he.OK:he.APPENDING:he.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=rt(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:n}=t;if(s.sn==="initSegment")return;const a=s.type;if(i){let l=this.activePartLists[a];l||(this.activePartLists[a]=l=[]),l.push(i)}this.timeRanges=r;const o=r[n];this.detectEvictedFragments(n,o,a,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=rt(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||i&&!o.gap||o.start<t&&o.end>e&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(e){const t=rt(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Qi(s,r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}};function Ft(e){var t,s,i;return e.buffered&&!!(e.body.gap||(t=e.range.video)!=null&&t.partial||(s=e.range.audio)!=null&&s.partial||(i=e.range.audiovideo)!=null&&i.partial)}function rt(e){return`${e.type}_${e.level}_${e.sn}`}function Qi(e,t){return e.filter(s=>{const i=t(s);return i||s.clearElementaryStreamInfo(),i})}var qe={cbc:0,ctr:1},Uo=class{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case qe.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case qe.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function $o(e){const t=e.byteLength,s=t&&new DataView(e.buffer).getUint8(t-1);return s?e.slice(0,t-s):e}var Go=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],c=o[2],u=o[3],d=new Uint32Array(256);let f=0,m=0,p=0;for(p=0;p<256;p++)p<128?d[p]=p<<1:d[p]=p<<1^283;for(p=0;p<256;p++){let E=m^m<<1^m<<2^m<<3^m<<4;E=E>>>8^E&255^99,e[f]=E,t[E]=f;const y=d[f],T=d[y],v=d[T];let S=d[E]*257^E*16843008;i[f]=S<<24|S>>>8,r[f]=S<<16|S>>>16,n[f]=S<<8|S>>>24,a[f]=S,S=v*16843009^T*65537^y*257^f*16843008,l[E]=S<<24|S>>>8,h[E]=S<<16|S>>>16,c[E]=S<<8|S>>>24,u[E]=S,f?(f=y^d[d[d[v^y]]],m^=d[d[m]]):f=m=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const n=this.ksRows=(r+6+1)*4;let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),c=this.sBox,u=this.rcon,d=this.invSubMix,f=d[0],m=d[1],p=d[2],E=d[3];let y,T;for(a=0;a<n;a++){if(a<r){y=l[a]=t[a];continue}T=y,a%r===0?(T=T<<8|T>>>24,T=c[T>>>24]<<24|c[T>>>16&255]<<16|c[T>>>8&255]<<8|c[T&255],T^=u[a/r|0]<<24):r>6&&a%r===4&&(T=c[T>>>24]<<24|c[T>>>16&255]<<16|c[T>>>8&255]<<8|c[T&255]),l[a]=y=(l[a-r]^T)>>>0}for(o=0;o<n;o++)a=n-o,o&3?T=l[a]:T=l[a-4],o<4||a<=4?h[o]=T:h[o]=f[c[T>>>24]]^m[c[T>>>16&255]]^p[c[T>>>8&255]]^E[c[T&255]],h[o]=h[o]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],c=a[3],u=this.uint8ArrayToUint32Array_(s);let d=u[0],f=u[1],m=u[2],p=u[3];const E=new Int32Array(e),y=new Int32Array(E.length);let T,v,S,R,A,I,D,P,_,M,B,x,K,F;const O=this.networkToHostOrderSwap;for(;t<E.length;){for(_=O(E[t]),M=O(E[t+1]),B=O(E[t+2]),x=O(E[t+3]),A=_^r[0],I=x^r[1],D=B^r[2],P=M^r[3],K=4,F=1;F<i;F++)T=o[A>>>24]^l[I>>16&255]^h[D>>8&255]^c[P&255]^r[K],v=o[I>>>24]^l[D>>16&255]^h[P>>8&255]^c[A&255]^r[K+1],S=o[D>>>24]^l[P>>16&255]^h[A>>8&255]^c[I&255]^r[K+2],R=o[P>>>24]^l[A>>16&255]^h[I>>8&255]^c[D&255]^r[K+3],A=T,I=v,D=S,P=R,K=K+4;T=n[A>>>24]<<24^n[I>>16&255]<<16^n[D>>8&255]<<8^n[P&255]^r[K],v=n[I>>>24]<<24^n[D>>16&255]<<16^n[P>>8&255]<<8^n[A&255]^r[K+1],S=n[D>>>24]<<24^n[P>>16&255]<<16^n[A>>8&255]<<8^n[I&255]^r[K+2],R=n[P>>>24]<<24^n[A>>16&255]<<16^n[I>>8&255]<<8^n[D&255]^r[K+3],y[t]=O(T^d),y[t+1]=O(R^f),y[t+2]=O(S^m),y[t+3]=O(v^p),d=_,f=M,m=B,p=x,t=t+4}return y.buffer}},Ko=class{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=Vo(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function Vo(e){switch(e){case qe.cbc:return"AES-CBC";case qe.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}var Ho=16,pi=class{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?$o(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,n)=>{const a=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(a,t,s,i);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:a}=this;if(i!==qe.cbc||t.byteLength!==16)return ee.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(e=De(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Go),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Ko(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Uo(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(ee.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%Ho;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(ee.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},Zi=Math.pow(2,17),Yo=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new Ge({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){o(er(e));return}else e.gap=!1;const l=this.loader=r?new r(i):new n(i),h=Ji(e);e.loader=l;const c=zi(i.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Zi};e.stats=l.stats;const d={onSuccess:(f,m,p,E)=>{this.resetLoader(e,l);let y=f.data;p.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(y.slice(0,16)),y=y.slice(16)),a({frag:e,part:null,payload:y,networkDetails:E})},onError:(f,m,p,E)=>{this.resetLoader(e,l),o(new Ge({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:J({url:s,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:E}))},onAbort:(f,m,p)=>{this.resetLoader(e,l),o(new Ge({type:$.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,m,p)=>{this.resetLoader(e,l),o(new Ge({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:p,stats:f}))}};t&&(d.onProgress=(f,m,p,E)=>t({frag:e,part:null,payload:p,networkDetails:E})),l.load(h,u,d)})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((a,o)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){o(er(e,t));return}const l=this.loader=r?new r(i):new n(i),h=Ji(e,t);e.loader=l;const c=zi(i.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Zi};t.stats=l.stats,l.load(h,u,{onSuccess:(d,f,m,p)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:d.data,networkDetails:p};s(E),a(E)},onError:(d,f,m,p)=>{this.resetLoader(e,l),o(new Ge({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:J({url:h.url,data:void 0},d),error:new Error(`HTTP Error ${d.code} ${d.text}`),networkDetails:m,stats:p}))},onAbort:(d,f,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),o(new Ge({type:$.NETWORK_ERROR,details:L.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:d}))},onTimeout:(d,f,m)=>{this.resetLoader(e,l),o(new Ge({type:$.NETWORK_ERROR,details:L.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:m,stats:d}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const o=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/r),o),h=(o-l)*Math.round(s.loaded/l);s.total=s.loaded+h}else s.total=Math.max(s.loaded,s.total);const n=s.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(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function Ji(e,t=null){const s=t||e,i={frag:e,part:t,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(N(r)&&N(n)){var a;let o=r,l=n;if(e.sn==="initSegment"&&Wo((a=e.decryptdata)==null?void 0:a.method)){const h=n-r;h%16&&(l=n+(16-h%16)),r!==0&&(i.resetIV=!0,o=r-16)}i.rangeStart=o,i.rangeEnd=l}return i}function er(e,t){const s=new Error(`GAP ${e.gap?"tag":"attribute"} found`),i={type:$.MEDIA_ERROR,details:L.FRAG_GAP,fatal:!1,frag:e,error:s,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new Ge(i)}function Wo(e){return e==="AES-128"||e==="AES-256"}var Ge=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},vn=class extends _e{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},Ei=class{constructor(e,t,s,i=0,r=-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=Nt(),this.buffering={audio:Nt(),video:Nt(),audiovideo:Nt()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}};function Nt(){return{start:0,executeStart:0,executeEnd:0,end:0}}var tr={length:0,start:()=>0,end:()=>0},j=class ht{static isBuffered(t,s){if(t){const i=ht.getBuffered(t);for(let r=i.length;r--;)if(s>=i.start(r)&&s<=i.end(r))return!0}return!1}static bufferedRanges(t){if(t){const s=ht.getBuffered(t);return ht.timeRangesToArray(s)}return[]}static timeRangesToArray(t){const s=[];for(let i=0;i<t.length;i++)s.push({start:t.start(i),end:t.end(i)});return s}static bufferInfo(t,s,i){if(t){const r=ht.bufferedRanges(t);if(r.length)return ht.bufferedInfo(r,s,i)}return{len:0,start:s,end:s,bufferedIndex:-1}}static bufferedInfo(t,s,i){s=Math.max(0,s),t.length>1&&t.sort((c,u)=>c.start-u.start||u.end-c.end);let r=-1,n=[];if(i)for(let c=0;c<t.length;c++){s>=t[c].start&&s<=t[c].end&&(r=c);const u=n.length;if(u){const d=n[u-1].end;t[c].start-d<i?t[c].end>d&&(n[u-1].end=t[c].end):n.push(t[c])}else n.push(t[c])}else n=t;let a=0,o,l=s,h=s;for(let c=0;c<n.length;c++){const u=n[c].start,d=n[c].end;if(r===-1&&s>=u&&s<=d&&(r=c),s+i>=u&&s<d)l=u,h=d,a=h-s;else if(s+i<u){o=u;break}}return{len:a,start:l||0,end:h||0,nextStart:o,buffered:t,bufferedIndex:r}}static getBuffered(t){try{return t.buffered||tr}catch(s){return ee.log("failed to get media.buffered",s),tr}}},Tn=/\{\$([a-zA-Z0-9-_]+)\}/g;function sr(e){return Tn.test(e)}function Xs(e,t){if(e.variableList!==null||e.hasVariableRefs){const s=e.variableList;return t.replace(Tn,i=>{const r=i.substring(2,i.length-1),n=s?.[r];return n===void 0?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),i):n})}return t}function ir(e,t,s){let i=e.variableList;i||(e.variableList=i={});let r,n;if("QUERYPARAM"in t){r=t.QUERYPARAM;try{const a=new self.URL(s).searchParams;if(a.has(r))n=a.get(r);else throw new Error(`"${r}" does not match any query parameter in URI: "${s}"`)}catch(a){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else r=t.NAME,n=t.VALUE;r in i?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):i[r]=n||""}function qo(e,t,s){const i=t.IMPORT;if(s&&i in s){let r=e.variableList;r||(e.variableList=r={}),r[i]=s[i]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${i}"`))}var jo=/^(\d+)x(\d+)$/,rr=/(.+?)=(".*?"|.*?)(?:,|$)/g,ae=class Sn{constructor(t,s){typeof t=="string"&&(t=Sn.parseAttrList(t,s)),te(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const s=parseInt(this[t],10);return s>Number.MAX_SAFE_INTEGER?1/0:s}hexadecimalInteger(t){if(this[t]){let s=(this[t]||"0x").slice(2);s=(s.length&1?"0":"")+s;const i=new Uint8Array(s.length/2);for(let r=0;r<s.length/2;r++)i[r]=parseInt(s.slice(r*2,r*2+2),16);return i}return null}hexadecimalIntegerAsNumber(t){const s=parseInt(this[t],16);return s>Number.MAX_SAFE_INTEGER?1/0:s}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,s){const i=this[t];return i?parseFloat(i):s}enumeratedString(t){return this[t]}enumeratedStringList(t,s){const i=this[t];return(i?i.split(/[ ,]+/):[]).reduce((r,n)=>(r[n.toLowerCase()]=!0,r),s)}bool(t){return this[t]==="YES"}decimalResolution(t){const s=jo.exec(this[t]);if(s!==null)return{width:parseInt(s[1],10),height:parseInt(s[2],10)}}static parseAttrList(t,s){let i;const r={};for(rr.lastIndex=0;(i=rr.exec(t))!==null;){const a=i[1].trim();let o=i[2];const l=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1;let h=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":h=!0}if(s&&(l||h))o=Xs(s,o);else if(!h&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":ee.warn(`${t}: attribute ${a} is missing quotes`)}r[a]=o}return r}},Xo="com.apple.hls.interstitial";function zo(e){return e!=="ID"&&e!=="CLASS"&&e!=="CUE"&&e!=="START-DATE"&&e!=="DURATION"&&e!=="END-DATE"&&e!=="END-ON-NEXT"}function Qo(e){return e==="SCTE35-OUT"||e==="SCTE35-IN"||e==="SCTE35-CMD"}var An=class{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(i=t?.tagOrder)!=null?i:s,t){const r=t.attr;for(const n in r)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==r[n]){ee.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=n;break}e=te(new ae({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const r=t?.endDate||new Date(this.attr["END-DATE"]);N(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(ee.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(N(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Xo}get isValid(){return!!this.id&&!this._badValueForSameId&&N(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},Zo=10,Jo=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?N(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Zo}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function cs(e,t){return e.length===t.length?!e.some((s,i)=>s!==t[i]):!1}function nr(e,t){return!e&&!t?!0:!e||!t?!1:cs(e,t)}function gt(e){return e==="AES-128"||e==="AES-256"||e==="AES-256-CTR"}function yi(e){switch(e){case"AES-128":case"AES-256":return qe.cbc;case"AES-256-CTR":return qe.ctr;default:throw new Error(`invalid full segment method ${e}`)}}function vi(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function zs(e){return Uint8Array.from(unescape(encodeURIComponent(e)),t=>t.charCodeAt(0))}function el(e){const t=zs(e).subarray(0,16),s=new Uint8Array(16);return s.set(t,16-t.length),s}function In(e){const t=function(i,r,n){const a=i[r];i[r]=i[n],i[n]=a};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function Ln(e){const t=e.split(":");let s=null;if(t[0]==="data"&&t.length===2){const i=t[1].split(";"),r=i[i.length-1].split(",");if(r.length===2){const n=r[0]==="base64",a=r[1];n?(i.splice(-1,1),s=vi(a)):s=el(a)}}return s}var us=typeof self<"u"?self:void 0,re={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ge={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function zt(e){switch(e){case ge.FAIRPLAY:return re.FAIRPLAY;case ge.PLAYREADY:return re.PLAYREADY;case ge.WIDEVINE:return re.WIDEVINE;case ge.CLEARKEY:return re.CLEARKEY}}function Ls(e){switch(e){case re.FAIRPLAY:return ge.FAIRPLAY;case re.PLAYREADY:return ge.PLAYREADY;case re.WIDEVINE:return ge.WIDEVINE;case re.CLEARKEY:return ge.CLEARKEY}}function St(e){const{drmSystems:t,widevineLicenseUrl:s}=e,i=t?[re.FAIRPLAY,re.WIDEVINE,re.PLAYREADY,re.CLEARKEY].filter(r=>!!t[r]):[];return!i[re.WIDEVINE]&&s&&i.push(re.WIDEVINE),i}var Rn=(function(e){return us!=null&&(e=us.navigator)!=null&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function tl(e,t,s,i){let r;switch(e){case re.FAIRPLAY:r=["cenc","sinf"];break;case re.WIDEVINE:case re.PLAYREADY:r=["cenc"];break;case re.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return sl(r,t,s,i)}function sl(e,t,s,i){return[{initDataTypes:e,persistentState:i.persistentState||"optional",distinctiveIdentifier:i.distinctiveIdentifier||"optional",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:t.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null})),videoCapabilities:s.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}))}]}function il(e){var t;return!!e&&(e.sessionType==="persistent-license"||!!((t=e.sessionTypes)!=null&&t.some(s=>s==="persistent-license")))}function bn(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),s=String.fromCharCode.apply(null,Array.from(t)),i=s.substring(s.indexOf("<"),s.length),r=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(r){const n=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(n){const a=vi(n).subarray(0,16);return In(a),a}}return null}var nt={},ds=class Qt{static clearKeyUriToKeyIdMap(){nt={}}static setKeyIdForUri(t,s){nt[t]=s}static addKeyIdForUri(t){const s=Object.keys(nt).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,s),nt[t]=i,i}constructor(t,s,i,r=[1],n=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=s,this.keyFormat=i,this.keyFormatVersions=r,this.iv=n,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!gt(t),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Zr(a)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&cs(t.keyFormatVersions,this.keyFormatVersions)&&nr(t.iv,this.iv)&&nr(t.keyId,this.keyId)}isSupported(){if(this.method){if(gt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case ge.FAIRPLAY:case ge.WIDEVINE:case ge.PLAYREADY:case ge.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,s){if(!this.encrypted||!this.uri)return null;if(gt(this.method)){let n=this.iv;return n||(typeof t!="number"&&(ee.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),n=nl(t)),new Qt(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){const n=nt[this.uri];if(n&&!cs(this.keyId,n)&&Qt.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const i=Ln(this.uri);if(i)switch(this.keyFormat){case ge.WIDEVINE:if(this.pssh=i,!this.keyId){const n=oo(i.buffer);if(n.length){var r;const a=n[0];this.keyId=(r=a.kids)!=null&&r.length?a.kids[0]:null}}this.keyId||(this.keyId=ar(s));break;case ge.PLAYREADY:{const n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=ao(n,null,i),this.keyId=bn(i);break}default:{let n=i.subarray(0,16);if(n.length!==16){const a=new Uint8Array(16);a.set(n,16-n.length),n=a}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n;n=rl(s),n||(n=ar(s),n||(n=nt[this.uri])),n&&(this.keyId=n,Qt.setKeyIdForUri(this.uri,n))}return this}};function rl(e){const t=e?.[ge.WIDEVINE];return t?t.keyId:null}function ar(e){const t=e?.[ge.PLAYREADY];if(t){const s=Ln(t.uri);if(s)return bn(s)}return null}function nl(e){const t=new Uint8Array(16);for(let s=12;s<16;s++)t[s]=e>>8*(15-s)&255;return t}var or=/#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,lr=/#EXT-X-MEDIA:(.*)/g,al=/^#EXT(?:INF|-X-TARGETDURATION):/m,Rs=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ol=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("|")),At=class It{static findGroup(t,s){for(let i=0;i<t.length;i++){const r=t[i];if(r.id===s)return r}}static resolve(t,s){return ci.buildAbsoluteURL(s,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return al.test(t)}static parseMasterPlaylist(t,s){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:sr(t)},r=[];if(or.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let n;for(;(n=or.exec(t))!=null;)if(n[1]){var a;const o=new ae(n[1],i),l=Xs(i,n[2]),h={attrs:o,bitrate:o.decimalInteger("BANDWIDTH")||o.decimalInteger("AVERAGE-BANDWIDTH"),name:o.NAME,url:It.resolve(l,s)},c=o.decimalResolution("RESOLUTION");c&&(h.width=c.width,h.height=c.height),ur(o.CODECS,h);const u=o["SUPPLEMENTAL-CODECS"];u&&(h.supplemental={},ur(u,h.supplemental)),(a=h.unknownCodecs)!=null&&a.length||r.push(h),i.levels.push(h)}else if(n[3]){const o=n[3],l=n[4];switch(o){case"SESSION-DATA":{const h=new ae(l,i),c=h["DATA-ID"];c&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[c]=h);break}case"SESSION-KEY":{const h=hr(l,s,i);h.encrypted&&h.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(h)):ee.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${l}"`);break}case"DEFINE":ir(i,new ae(l,i),s);break;case"CONTENT-STEERING":{const h=new ae(l,i);i.contentSteering={uri:It.resolve(h["SERVER-URI"],s),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=cr(l)}}return i.levels=r.length>0&&r.length<i.levels.length?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,s,i){let r;const n={},a=i.levels,o={AUDIO:a.map(h=>({id:h.attrs.AUDIO,audioCodec:h.audioCodec})),SUBTITLES:a.map(h=>({id:h.attrs.SUBTITLES,textCodec:h.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(lr.lastIndex=0;(r=lr.exec(t))!==null;){const h=new ae(r[1],i),c=h.TYPE;if(c){const u=o[c],d=n[c]||[];n[c]=d;const f=h.LANGUAGE,m=h["ASSOC-LANGUAGE"],p=h.CHANNELS,E=h.CHARACTERISTICS,y=h["INSTREAM-ID"],T={attrs:h,bitrate:0,id:l++,groupId:h["GROUP-ID"]||"",name:h.NAME||f||"",type:c,default:h.bool("DEFAULT"),autoselect:h.bool("AUTOSELECT"),forced:h.bool("FORCED"),lang:f,url:h.URI?It.resolve(h.URI,s):""};if(m&&(T.assocLang=m),p&&(T.channels=p),E&&(T.characteristics=E),y&&(T.instreamId=y),u!=null&&u.length){const v=It.findGroup(u,T.groupId)||u[0];dr(T,v,"audioCodec"),dr(T,v,"textCodec")}d.push(T)}}return n}static parseLevelPlaylist(t,s,i,r,n,a){var o;const l={url:s},h=new Jo(s),c=h.fragments,u=[];let d=null,f=0,m=0,p=0,E=0,y=0,T=null,v=new Ss(r,l),S,R,A,I=-1,D=!1,P=null,_;if(Rs.lastIndex=0,h.m3u8=t,h.hasVariableRefs=sr(t),((o=Rs.exec(t))==null?void 0:o[0])!=="#EXTM3U")return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;(S=Rs.exec(t))!==null;){D&&(D=!1,v=new Ss(r,l),v.playlistOffset=p,v.setStart(p),v.sn=f,v.cc=E,y&&(v.bitrate=y),v.level=i,d&&(v.initSegment=d,d.rawProgramDateTime&&(v.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),P&&(v.setByteRange(P),P=null)));const K=S[1];if(K){v.duration=parseFloat(K);const F=(" "+S[2]).slice(1);v.title=F||null,v.tagList.push(F?["INF",K,F]:["INF",K])}else if(S[3]){if(N(v.duration)){v.playlistOffset=p,v.setStart(p),A&&gr(v,A,h),v.sn=f,v.level=i,v.cc=E,c.push(v);const F=(" "+S[3]).slice(1);v.relurl=Xs(h,F),Qs(v,T,u),T=v,p+=v.duration,f++,m=0,D=!0}}else{if(S=S[0].match(ol),!S){ee.warn("No matches on slow regex match for level playlist!");continue}for(R=1;R<S.length&&S[R]===void 0;R++);const F=(" "+S[R]).slice(1),O=(" "+S[R+1]).slice(1),Y=S[R+2]?(" "+S[R+2]).slice(1):null;switch(F){case"BYTERANGE":T?v.setByteRange(O,T):v.setByteRange(O);break;case"PROGRAM-DATE-TIME":v.rawProgramDateTime=O,v.tagList.push(["PROGRAM-DATE-TIME",O]),I===-1&&(I=c.length);break;case"PLAYLIST-TYPE":h.type&&Ue(h,F,S),h.type=O.toUpperCase();break;case"MEDIA-SEQUENCE":h.startSN!==0?Ue(h,F,S):c.length>0&&mr(h,F,S),f=h.startSN=parseInt(O);break;case"SKIP":{h.skippedSegments&&Ue(h,F,S);const k=new ae(O,h),w=k.decimalInteger("SKIPPED-SEGMENTS");if(N(w)){h.skippedSegments+=w;for(let W=w;W--;)c.push(null);f+=w}const G=k.enumeratedString("RECENTLY-REMOVED-DATERANGES");G&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(G.split(" ")));break}case"TARGETDURATION":h.targetduration!==0&&Ue(h,F,S),h.targetduration=Math.max(parseInt(O),1);break;case"VERSION":h.version!==null&&Ue(h,F,S),h.version=parseInt(O);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":h.live||Ue(h,F,S),h.live=!1;break;case"#":(O||Y)&&v.tagList.push(Y?[O,Y]:[O]);break;case"DISCONTINUITY":E++,v.tagList.push(["DIS"]);break;case"GAP":v.gap=!0,v.tagList.push([F]);break;case"BITRATE":v.tagList.push([F,O]),y=parseInt(O)*1e3,N(y)?v.bitrate=y:y=0;break;case"DATERANGE":{const k=new ae(O,h),w=new An(k,h.dateRanges[k.ID],h.dateRangeTagCount);h.dateRangeTagCount++,w.isValid||h.skippedSegments?h.dateRanges[w.id]=w:ee.warn(`Ignoring invalid DATERANGE tag: "${O}"`),v.tagList.push(["EXT-X-DATERANGE",O]);break}case"DEFINE":{const k=new ae(O,h);"IMPORT"in k?qo(h,k,a):ir(h,k,s)}break;case"DISCONTINUITY-SEQUENCE":h.startCC!==0?Ue(h,F,S):c.length>0&&mr(h,F,S),h.startCC=E=parseInt(O);break;case"KEY":{const k=hr(O,s,h);if(k.isSupported()){if(k.method==="NONE"){A=void 0;break}A||(A={});const w=A[k.keyFormat];w!=null&&w.matches(k)||(w&&(A=te({},A)),A[k.keyFormat]=k)}else ee.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${O}"`);break}case"START":h.startTimeOffset=cr(O);break;case"MAP":{const k=new ae(O,h);if(v.duration){const w=new Ss(r,l);fr(w,k,i,A),d=w,v.initSegment=d,d.rawProgramDateTime&&!v.rawProgramDateTime&&(v.rawProgramDateTime=d.rawProgramDateTime)}else{const w=v.byteRangeEndOffset;if(w){const G=v.byteRangeStartOffset;P=`${w-G}@${G}`}else P=null;fr(v,k,i,A),d=v,D=!0}d.cc=E;break}case"SERVER-CONTROL":_&&Ue(h,F,S),_=new ae(O),h.canBlockReload=_.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=_.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&_.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=_.optionalFloat("PART-HOLD-BACK",0),h.holdBack=_.optionalFloat("HOLD-BACK",0);break;case"PART-INF":h.partTarget&&Ue(h,F,S),h.partTarget=new ae(O).decimalFloatingPoint("PART-TARGET");break;case"PART":{let k=h.partList;k||(k=h.partList=[]);const w=m>0?k[k.length-1]:void 0,G=m++,W=new ae(O,h),Q=new Wa(W,v,l,G,w);k.push(Q),v.duration+=Q.duration;break}case"PRELOAD-HINT":h.preloadHint=new ae(O,h);break;case"RENDITION-REPORT":{const k=new ae(O,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(k);break}default:ee.warn(`line parsed but not handled: ${S}`)}}}T&&!T.relurl?(c.pop(),p-=T.duration,h.partList&&(h.fragmentHint=T)):h.partList&&(Qs(v,T,u),v.cc=E,h.fragmentHint=v,A&&gr(v,A,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));const M=c.length,B=c[0],x=c[M-1];if(p+=h.skippedSegments*h.targetduration,p>0&&M&&x){h.averagetargetduration=p/M;const K=x.sn;h.endSN=K!=="initSegment"?K:0,h.live||(x.endList=!0),I>0&&(hl(c,I),B&&u.unshift(B))}return h.fragmentHint&&(p+=h.fragmentHint.duration),h.totalduration=p,u.length&&h.dateRangeTagCount&&B&&Dn(u,h),h.endCC=E,h}};function Dn(e,t){let s=e.length;if(!s)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];e.push(o),s++}else return;const i=e[s-1],r=t.live?1/0:t.totalduration,n=Object.keys(t.dateRanges);for(let o=n.length;o--;){const l=t.dateRanges[n[o]],h=l.startDate.getTime();l.tagAnchor=i.ref;for(let c=s;c--;){var a;if(((a=e[c])==null?void 0:a.sn)<t.startSN)break;const u=ll(t,h,e,c,r);if(u!==-1){l.tagAnchor=t.fragments[u].ref;break}}}}function ll(e,t,s,i,r){const n=s[i];if(n){const o=n.programDateTime;if(t>=o||i===0){var a;if(t<=o+((((a=s[i+1])==null?void 0:a.start)||r)-n.start)*1e3){const l=s[i].sn-e.startSN;if(l<0)return-1;const h=e.fragments;if(h.length>s.length){const c=(s[i+1]||h[h.length-1]).sn-e.startSN;for(let u=c;u>l;u--){const d=h[u].programDateTime;if(t>=d&&t<d+h[u].duration*1e3)return u}}return l}}}return-1}function hr(e,t,s){var i,r;const n=new ae(e,s),a=(i=n.METHOD)!=null?i:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,c=(r=n.KEYFORMAT)!=null?r:"identity";o&&n.IV&&!l&&ee.error(`Invalid IV: ${n.IV}`);const u=o?At.resolve(o,t):"",d=(h||"1").split("/").map(Number).filter(Number.isFinite);return new ds(a,u,c,d,l,n.KEYID)}function cr(e){const t=new ae(e).decimalFloatingPoint("TIME-OFFSET");return N(t)?t:null}function ur(e,t){let s=(e||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const r=s.filter(n=>fi(n,i));r.length&&(t[`${i}Codec`]=r.map(n=>n.split("/")[0]).join(","),s=s.filter(n=>r.indexOf(n)===-1))}),t.unknownCodecs=s}function dr(e,t,s){const i=t[s];i&&(e[s]=i)}function hl(e,t){let s=e[t];for(let i=t;i--;){const r=e[i];if(!r)return;r.programDateTime=s.programDateTime-r.duration*1e3,s=r}}function Qs(e,t,s){e.rawProgramDateTime?s.push(e):t!=null&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function fr(e,t,s,i){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=s,e.sn="initSegment",i&&(e.levelkeys=i),e.initSegment=null}function gr(e,t,s){e.levelkeys=t;const{encryptedFragments:i}=s;(!i.length||i[i.length-1].levelkeys!==t)&&Object.keys(t).some(r=>t[r].isCommonEncryption)&&i.push(e)}function Ue(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${s[0]})`)}function mr(e,t,s){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${s[0]})`)}function bs(e,t){const s=t.startPTS;if(N(s)){let i=0,r;t.sn>e.sn?(i=s-e.start,r=e):(i=e.start-s,r=t),r.duration!==i&&r.setDuration(i)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function _n(e,t,s,i,r,n,a){i-s<=0&&(a.warn("Fragment should have a positive duration",t),i=s+t.duration,n=r+t.duration);let o=s,l=i;const h=t.startPTS,c=t.endPTS;if(N(h)){const E=Math.abs(h-s);e&&E>e.totalduration?a.warn(`media timestamps and playlist times differ by ${E}s for level ${t.level} ${e.url}`):N(t.deltaPTS)?t.deltaPTS=Math.max(E,t.deltaPTS):t.deltaPTS=E,o=Math.max(s,h),s=Math.min(s,h),r=t.startDTS!==void 0?Math.min(r,t.startDTS):r,l=Math.min(i,c),i=Math.max(i,c),n=t.endDTS!==void 0?Math.max(n,t.endDTS):n}const u=s-t.start;t.start!==0&&t.setStart(s),t.setDuration(i-t.start),t.startPTS=s,t.maxStartPTS=o,t.startDTS=r,t.endPTS=i,t.minEndPTS=l,t.endDTS=n;const d=t.sn;if(!e||d<e.startSN||d>e.endSN)return 0;let f;const m=d-e.startSN,p=e.fragments;for(p[m]=t,f=m;f>0;f--)bs(p[f],p[f-1]);for(f=m;f<p.length-1;f++)bs(p[f],p[f+1]);return e.fragmentHint&&bs(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,u}function cl(e,t,s){if(e===t)return;let i=null;const r=e.fragments;for(let c=r.length-1;c>=0;c--){const u=r[c].initSegment;if(u){i=u;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let n;fl(e,t,(c,u,d,f)=>{if((!t.startCC||t.skippedSegments)&&u.cc!==c.cc){const m=c.cc-u.cc;for(let p=d;p<f.length;p++)f[p].cc+=m;t.endCC=f[f.length-1].cc}N(c.startPTS)&&N(c.endPTS)&&(u.setStart(u.startPTS=c.startPTS),u.startDTS=c.startDTS,u.maxStartPTS=c.maxStartPTS,u.endPTS=c.endPTS,u.endDTS=c.endDTS,u.minEndPTS=c.minEndPTS,u.setDuration(c.endPTS-c.startPTS),u.duration&&(n=u),t.PTSKnown=t.alignedSliding=!0),c.hasStreams&&(u.elementaryStreams=c.elementaryStreams),u.loader=c.loader,c.hasStats&&(u.stats=c.stats),c.initSegment&&(u.initSegment=c.initSegment,i=c.initSegment)});const a=t.fragments,o=t.fragmentHint?a.concat(t.fragmentHint):a;if(i&&o.forEach(c=>{var u;c&&(!c.initSegment||c.initSegment.relurl===((u=i)==null?void 0:u.relurl))&&(c.initSegment=i)}),t.skippedSegments){if(t.deltaUpdateFailed=a.some(c=>!c),t.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let c=t.skippedSegments;c--;)a.shift();t.startSN=a[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=ul(e.dateRanges,t,s));const c=e.fragments.filter(u=>u.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Qs(o[u],o[u-1],c);Dn(c,t)}t.endCC=a[a.length-1].cc}if(!t.startCC){var l;const c=kn(e,t.startSN-1);t.startCC=(l=c?.cc)!=null?l:a[0].cc}dl(e.partList,t.partList,(c,u)=>{u.elementaryStreams=c.elementaryStreams,u.stats=c.stats}),n?_n(t,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,s):Pn(e,t),a.length&&(t.totalduration=t.edge-a[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const h=t.advancedDateTime;if(t.advanced&&h){const c=t.edge;t.driftStart||(t.driftStartTime=h,t.driftStart=c),t.driftEndTime=h,t.driftEnd=c}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=e.requestScheduled)}function ul(e,t,s){const{dateRanges:i,recentlyRemovedDateranges:r}=t,n=te({},e);r&&r.forEach(o=>{delete n[o]});const a=Object.keys(n).length;return a?(Object.keys(i).forEach(o=>{const l=n[o],h=new An(i[o].attr,l);h.isValid?(n[o]=h,l||(h.tagOrder+=a)):s.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ie(i[o].attr)}"`)}),n):i}function dl(e,t,s){if(e&&t){let i=0;for(let r=0,n=e.length;r<n;r++){const a=e[r],o=t[r+i];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?s(a,o):i--}}}function fl(e,t,s){var i;const r=t.skippedSegments,n=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,h=(i=e.fragmentHint)!=null&&i.duration?e.fragments.concat(e.fragmentHint):e.fragments;for(let c=n;c<=a;c++){const u=h[o+c];let d=l[c];if(r&&!d&&u&&(d=t.fragments[c]=u),u&&d){s(u,d,c,l);const f=u.relurl,m=d.relurl;if(f&&gl(f,m)){t.playlistParsingError=pr(`media sequence mismatch ${d.sn}:`,e,t,u,d);return}else if(u.cc!==d.cc){t.playlistParsingError=pr(`discontinuity sequence mismatch (${u.cc}!=${d.cc})`,e,t,u,d);return}}}}function pr(e,t,s,i,r){return new Error(`${e} ${r.url}
Playlist starting @${t.startSN}
${t.m3u8}
Playlist starting @${s.startSN}
${s.m3u8}`)}function Pn(e,t,s=!0){const i=t.startSN+t.skippedSegments-e.startSN,r=e.fragments,n=i>=0;let a=0;if(n&&i<r.length)a=r[i].start;else if(n&&t.startSN===e.endSN+1)a=e.fragmentEnd;else if(n&&s)a=e.fragmentStart+i*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)a=e.fragmentStart;else return;Zs(t,a)}function Zs(e,t){if(t){const s=e.fragments;for(let i=e.skippedSegments;i<s.length;i++)s[i].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function Cn(e,t=1/0){let s=1e3*e.targetduration;if(e.updated){const i=e.fragments;if(i.length&&s*4>t){const r=i[i.length-1].duration*1e3;r<s&&(s=r)}}else s/=2;return Math.round(s)}function kn(e,t,s){if(!e)return null;let i=e.fragments[t-e.startSN];return i||(i=e.fragmentHint,i&&i.sn===t)?i:t<e.startSN&&s&&s.sn===t?s:null}function Er(e,t,s){return e?wn(e.partList,t,s):null}function wn(e,t,s){if(e)for(let i=e.length;i--;){const r=e[i];if(r.index===s&&r.fragment.sn===t)return r}return null}function Mn(e){e.forEach((t,s)=>{var i;(i=t.details)==null||i.fragments.forEach(r=>{r.level=s,r.initSegment&&(r.initSegment.level=s)})})}function gl(e,t){return e!==t&&t?yr(e)!==yr(t):!1}function yr(e){return e.replace(/\?[^?]*$/,"")}function Lt(e,t){for(let i=0,r=e.length;i<r;i++){var s;if(((s=e[i])==null?void 0:s.cc)===t)return e[i]}return null}function ml(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function vr(e,t){const s=e.start+t;e.startPTS=s,e.setStart(s),e.endPTS=s+e.duration}function On(e,t){const s=t.fragments;for(let i=0,r=s.length;i<r;i++)vr(s[i],e);t.fragmentHint&&vr(t.fragmentHint,e),t.alignedSliding=!0}function pl(e,t){e&&(xn(t,e),t.alignedSliding||fs(t,e),!t.alignedSliding&&!t.skippedSegments&&Pn(e,t,!1))}function xn(e,t){if(!ml(t,e))return;const s=Math.min(t.endCC,e.endCC),i=Lt(t.fragments,s),r=Lt(e.fragments,s);!i||!r||(ee.log(`Aligning playlist at start of dicontinuity sequence ${s}`),On(i.start-r.start,e))}function fs(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const s=e.fragments,i=t.fragments;if(!s.length||!i.length)return;let r,n;const a=Math.min(t.endCC,e.endCC);t.startCC<a&&e.startCC<a&&(r=Lt(i,a),n=Lt(s,a)),(!r||!n)&&(r=i[Math.floor(i.length/2)],n=Lt(s,r.cc)||s[Math.floor(s.length/2)]);const o=r.programDateTime,l=n.programDateTime;!o||!l||On((l-o)/1e3-(n.start-r.start),e)}function ye(e,t,s){Te(e,t,s),e.addEventListener(t,s)}function Te(e,t,s){e.removeEventListener(t,s)}var El={toString:function(e){let t="";const s=e.length;for(let i=0;i<s;i++)t+=`[${e.start(i).toFixed(3)}-${e.end(i).toFixed(3)}]`;return t}},C={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},Ti=class extends vn{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=C.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:n,fragCurrent:a,media:o,mediaBuffer:l,state:h}=this,c=o?o.currentTime:0,u=j.bufferInfo(l||o,c,n.maxBufferHole),d=!u.len;if(this.log(`Media seeking to ${N(c)?c.toFixed(3):c}, state: ${h}, ${d?"out of":"in"} buffer`),this.state===C.ENDED)this.resetLoadingState();else if(a){const f=n.maxFragLookUpTolerance,m=a.start-f,p=a.start+a.duration+f;if(d||p<u.start||m>u.end){const E=c>p;(c<m||E)&&(E&&a.loader&&(this.log(`Cancelling fragment load for seek (sn: ${a.sn})`),a.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(o&&(this.fragmentTracker.removeFragmentsInRange(c,1/0,this.playlistType,!0),c>this.lastCurrentTime&&(this.lastCurrentTime=c),!this.loadingParts)){const f=Math.max(u.end,c),m=this.shouldLoadParts(this.getLevelDetails(),f);m&&(this.log(`LL-Part loading ON after seeking to ${c.toFixed(2)} with buffer @${f.toFixed(2)}`),this.loadingParts=m)}this.hls.hasEnoughToStart||(this.log(`Setting ${d?"startPosition":"nextLoadPosition"} to ${c} for seek without enough to start`),this.nextLoadPosition=c,d&&(this.startPosition=c)),d&&this.state===C.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new Yo(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new pi(e.config)}registerListeners(){const{hls:e}=this;e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===C.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=C.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=j.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge||this.media.currentTime<e.start)return!1;const a=t.partList;if(a!=null&&a.length){const l=a[a.length-1];return j.isBuffered(this.media,l.start+l.duration/2)}const o=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(o)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;ye(s,"seeking",this.onMediaSeeking),ye(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===C.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Te(i,"seeking",this.onMediaSeeking),Te(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=C.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const n=r.frag;if(this.fragContextChanged(n)){this.warn(`${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(n);return}n.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const n=this.state,a=r.frag;if(this.fragContextChanged(a)){(n===C.FRAG_LOADING||!this.fragCurrent&&n===C.PARSING)&&(this.fragmentTracker.removeFragment(a),this.state=C.IDLE);return}"payload"in r&&(this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level}`),this.hls.trigger(g.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===he.APPENDING){const i=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,i),n=Math.max(e.duration,r?r.len:this.config.maxBufferLength),a=this.backtrackFragment;((a?e.sn-a.sn:0)===1||this.reduceMaxBufferLength(n,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===he.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(g.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const i=s?.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{frag:r,payload:n}=s,a=r.decryptdata;if(n&&n.byteLength>0&&a!=null&&a.key&&a.iv&>(a.method)){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,yi(a.method)).catch(l=>{throw i.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const h=self.performance.now();return i.trigger(g.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:o,tdecrypt:h}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==C.STOPPED&&(this.state=C.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const n=this.media,a=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${n?"attached mediaKeys: "+n.mediaKeys:"detached"})`);return this.warn(a.message),!n||n.mediaKeys?!1:(this.hls.trigger(g.ERROR,{type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,fatal:!1,error:a,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?El.toString(j.getBuffered(s)):"(detached)"})`),oe(e)){var i;if(e.type!==U.SUBTITLE){const n=e.elementaryStreams;if(!Object.keys(n).some(a=>!!n[a])){this.state=C.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=C.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||r.length===0||r.some(o=>!o),a=new Ei(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(a)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=C.KEY_LOADING,this.fragCurrent=e,a=this.keyLoader.load(e).then(u=>{if(!this.fragContextChanged(u.frag))return this.hls.trigger(g.KEY_LOADED,u),this.state===C.KEY_LOADING&&(this.state=C.IDLE),u}),this.hls.trigger(g.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(a=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),a&&this.log("[eme] blocking frag load until media-keys acquired"));const o=this.fragPrevious;if(oe(e)&&(!o||e.sn!==o.sn)){const u=this.shouldLoadParts(t.details,e.end);u!==this.loadingParts&&(this.log(`LL-Part loading ${u?"ON":"OFF"} loading sn ${o?.sn}->${e.sn}`),this.loadingParts=u)}if(s=Math.max(e.start,s||0),this.loadingParts&&oe(e)){const u=n.partList;if(u&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const d=this.getNextPart(u,e,s);if(d>-1){const f=u[d];e=this.fragCurrent=f.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${f.index} (${d}/${u.length-1}) of ${this.fragInfo(e,!1,f)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=C.FRAG_LOADING;let m;return a?m=a.then(p=>!p||this.fragContextChanged(p.frag)?null:this.doFragPartsLoad(e,f,t,i)).catch(p=>this.handleFragLoadError(p)):m=this.doFragPartsLoad(e,f,t,i).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(g.FRAG_LOADING,{frag:e,part:f,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):m}else if(!e.url||this.loadedEndOfParts(u,s))return Promise.resolve(null)}}if(oe(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=n.partList)==null?void 0:l.filter(u=>u.loaded).map(u=>`[${u.start}-${u.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),N(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;const h=this.config.progressive&&e.type!==U.SUBTITLE;let c;return h&&a?c=a.then(u=>!u||this.fragContextChanged(u.frag)?null:this.fragmentLoader.load(e,i)).catch(u=>this.handleFragLoadError(u)):c=Promise.all([this.fragmentLoader.load(e,h?i:void 0),a]).then(([u])=>(!h&&i&&i(u),u)).catch(u=>this.handleFragLoadError(u)),this.hls.trigger(g.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var a;const o=[],l=(a=s.details)==null?void 0:a.partList,h=c=>{this.fragmentLoader.loadPart(e,c,i).then(u=>{o[c.index]=u;const d=u.part;this.hls.trigger(g.FRAG_LOADED,u);const f=Er(s.details,e.sn,c.index+1)||wn(l,e.sn,c.index+1);if(f)h(f);else return r({frag:e,part:d,partsLoaded:o})}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===L.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===$.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(g.ERROR,t)}else this.hls.trigger(g.ERROR,{type:$.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==C.PARSING){!this.fragCurrent&&this.state!==C.STOPPED&&this.state!==C.ERROR&&(this.state=C.IDLE);return}const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&s.sn>a.endSN||this.shouldLoadParts(a,s.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=o),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===U.SUBTITLE)return!1;if(t>=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0)){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const a=t[i],o=a.details,l=n>-1?Er(o,r,n):null,h=l?l.fragment:kn(o,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==C.PARSING)return;const{data1:n,data2:a}=e;let o=n;if(a&&(o=De(n,a)),!o.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,c={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:o};if(this.hls.trigger(g.BUFFER_APPENDING,c),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!j.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=j.bufferInfo(t,s,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),a=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-a>n&&this.flushMainBuffer(a,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!N(i))return null;const r=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,r)}getFwdBufferInfoAtPos(e,t,s,i){const r=j.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const a=Math.max(Math.min(r.nextStart,n.end)-t,i);return j.bufferInfo(e,t,a)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,s){const i=e.nextStart;if(i&&s.start>i){const r=e.buffered;if(r){let n=e.len;const a=e.bufferedIndex;for(let o=r.length-1;o>a;o--)r[o].start<s.start&&(n+=r[o].end-r[o].start);return n>=t}}return!1}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=U.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=t.fragmentStart,a=r.lowLatencyMode&&!!t.partList;let o=null;if(t.live){const c=r.initialLiveManifestSize;if(i<c)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${c})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n){var l;a&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),o=this.getInitialLiveFragment(t);const u=this.config.startPosition,d=this.hls.startPosition,f=this.hls.liveSyncPosition,m=((l=o)==null?void 0:l.start)||0;let p,E;d!==-1&&d>=n?(p=d,E=d===u?"config":"next load start"):f!==null?(p=f,E="live edge"):(p=e,E="buffer pos"),p<m&&(p=m,E="live frag start"),p<n&&(p=n,E="playlist start"),(this.startPosition!=p||this.nextLoadPosition!=p)&&(this.log(`Setting startPosition to ${p.toFixed(3)} ${d===-1?"":`(from ${u}) `}based on ${E}. live edge: ${f} live frag start: ${m.toFixed(3)} playlist start: ${n.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=p)}}else e<=n&&(o=s[0]);if(!o){const c=this.loadingParts?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,c,t)}let h=this.filterReplacedPrimary(o,t);if(!h&&o){const c=o.sn-t.startSN;h=this.filterReplacedPrimary(s[c+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const s=this.fragmentTracker.getState(e);return s===he.OK||s===he.PARTIAL&&!!e.gap}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(a!==null&&s.len+a.len>=r){const o=n.sn;return this.loopSn!==o&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${o}`),this.loopSn=o),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(Tr(this.config)){var e;if(!((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null)&&e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Tr(this.config)&&e.type!==U.SUBTITLE){const s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){const n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&t?.live===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const r=s?.playerQueue;if(r)for(let n=r.length;n--;){const a=r[n].interstitial;if(a.appendInPlace&&e.start>=a.startTime&&e.end<=a.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let a=0,o=e.length;a<o;a++){const l=e[a];if(n=n&&!l.independent,i>-1&&s<l.start)break;const h=l.loaded;h?i=-1:(r||(l.independent||n)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=a),r=h}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(i=Mo(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=pn(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,c=!!(this.loadingParts&&h!=null&&h.length&&o);c&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn);let u;if(e<t){var d;const f=e<this.lastCurrentTime||e>t-l||(d=this.media)!=null&&d.paused||!this.startFragRequested?0:l;u=tt(r,n,e,f)}else u=n[n.length-1];if(u){const f=u.sn-s.startSN,m=this.fragmentTracker.getState(u);if((m===he.OK||m===he.PARTIAL&&u.gap)&&(r=u),r&&u.sn===r.sn&&(!c||h[0].fragment.sn>u.sn||!s.live)&&u.level===r.level){const p=n[f+1];u.sn<a&&this.fragmentTracker.getState(p)!==he.OK?u=p:u=null}}return u}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,a=e.alignedSliding&&N(r);if(n||!a&&!r){pl(s,e);const o=e.fragmentStart;return this.log(`Live playlist sliding: ${o.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),o}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&N(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&oe(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==C.FRAG_LOADING_WAITING_RETRY)&&(this.state=C.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const n=t.details===L.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const a=t.errorAction;if(!a){this.state=C.ERROR;return}const{action:o,flags:l,retryCount:h=0,retryConfig:c}=a,u=!!c,d=u&&o===ue.RetryRequest,f=u&&!a.resolved&&l===Ie.MoveAllAlternatesMatchingHost,m=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!d&&f&&oe(i)&&!i.endList&&m&&!yn(t))this.resetFragmentErrors(e),this.treatAsGap(i),a.resolved=!0;else if((d||f)&&h<c.maxNumRetry){var p;const E=js((p=t.response)==null?void 0:p.code),y=mi(c,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+y,this.state=C.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${c.maxNumRetry} in ${y}ms`)}else if(c)if(this.resetFragmentErrors(e),h<c.maxNumRetry)!n&&o!==ue.RemoveAlternatePermanently&&(a.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else o===ue.SendAlternateToPenaltyBox?this.state=C.WAITING_LEVEL:this.state=C.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!js(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=C.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===C.PARSING||this.state===C.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===U.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==C.STOPPED&&(this.state=C.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=j.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===C.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==C.STOPPED&&(this.state=C.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((a,o)=>{const l=e.elementaryStreams[o];if(l){const h=l.endPTS-l.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${e.sn} ${o} duration reliably (${h})`),a||!1;const c=i?0:_n(r,e,l.startPTS,l.endPTS,l.startDTS,l.endDTS,this);return this.hls.trigger(g.LEVEL_PTS_UPDATED,{details:r,level:s,drift:c,type:o,frag:e,start:l.startPTS,end:l.endPTS}),!0}return a},!1)){var n;const a=((n=this.transmuxer)==null?void 0:n.error)===null;if((s.fragmentError===0||a&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),a){const o=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(o.message),this.hls.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=C.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(g.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===U.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}};function Tr(e){return!!e.interstitialsController&&e.enableInterstitialPlayback!==!1}var Fn=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=yl(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}};function yl(e,t){const s=new Uint8Array(t);let i=0;for(let r=0;r<e.length;r++){const n=e[r];s.set(n,i),i+=n.length}return s}var Ds={exports:{}},Sr;function vl(){return Sr||(Sr=1,(function(e){var t=Object.prototype.hasOwnProperty,s="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(s=!1));function r(l,h,c){this.fn=l,this.context=h,this.once=c||!1}function n(l,h,c,u,d){if(typeof c!="function")throw new TypeError("The listener must be a function");var f=new r(c,u||l,d),m=s?s+h:h;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,h){--l._eventsCount===0?l._events=new i:delete l._events[h]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var h=[],c,u;if(this._eventsCount===0)return h;for(u in c=this._events)t.call(c,u)&&h.push(s?u.slice(1):u);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(c)):h},o.prototype.listeners=function(h){var c=s?s+h:h,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,m=new Array(f);d<f;d++)m[d]=u[d].fn;return m},o.prototype.listenerCount=function(h){var c=s?s+h:h,u=this._events[c];return u?u.fn?1:u.length:0},o.prototype.emit=function(h,c,u,d,f,m){var p=s?s+h:h;if(!this._events[p])return!1;var E=this._events[p],y=arguments.length,T,v;if(E.fn){switch(E.once&&this.removeListener(h,E.fn,void 0,!0),y){case 1:return E.fn.call(E.context),!0;case 2:return E.fn.call(E.context,c),!0;case 3:return E.fn.call(E.context,c,u),!0;case 4:return E.fn.call(E.context,c,u,d),!0;case 5:return E.fn.call(E.context,c,u,d,f),!0;case 6:return E.fn.call(E.context,c,u,d,f,m),!0}for(v=1,T=new Array(y-1);v<y;v++)T[v-1]=arguments[v];E.fn.apply(E.context,T)}else{var S=E.length,R;for(v=0;v<S;v++)switch(E[v].once&&this.removeListener(h,E[v].fn,void 0,!0),y){case 1:E[v].fn.call(E[v].context);break;case 2:E[v].fn.call(E[v].context,c);break;case 3:E[v].fn.call(E[v].context,c,u);break;case 4:E[v].fn.call(E[v].context,c,u,d);break;default:if(!T)for(R=1,T=new Array(y-1);R<y;R++)T[R-1]=arguments[R];E[v].fn.apply(E[v].context,T)}}return!0},o.prototype.on=function(h,c,u){return n(this,h,c,u,!1)},o.prototype.once=function(h,c,u){return n(this,h,c,u,!0)},o.prototype.removeListener=function(h,c,u,d){var f=s?s+h:h;if(!this._events[f])return this;if(!c)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===c&&(!d||m.once)&&(!u||m.context===u)&&a(this,f);else{for(var p=0,E=[],y=m.length;p<y;p++)(m[p].fn!==c||d&&!m[p].once||u&&m[p].context!==u)&&E.push(m[p]);E.length?this._events[f]=E.length===1?E[0]:E:a(this,f)}return this},o.prototype.removeAllListeners=function(h){var c;return h?(c=s?s+h:h,this._events[c]&&a(this,c)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,e.exports=o})(Ds)),Ds.exports}var Si=Ha(vl()),Ct="1.6.17",Et={};function Tl(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Sl(){const e=Et[Ct];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),s=self.URL.createObjectURL(t),i={worker:new self.Worker(s),objectURL:s,clientCount:1};return Et[Ct]=i,i}function Al(e){const t=Et[e];if(t)return t.clientCount++,t;const s=new self.URL(e,self.location.href).href,i={worker:new self.Worker(s),scriptURL:s,clientCount:1};return Et[e]=i,i}function Il(e){const t=Et[e||Ct];if(t&&t.clientCount--===1){const{worker:s,objectURL:i}=t;delete Et[e||Ct],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Nn(e,t){return t+10<=e.length&&e[t]===51&&e[t+1]===68&&e[t+2]===73&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Ai(e,t){return t+10<=e.length&&e[t]===73&&e[t+1]===68&&e[t+2]===51&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Es(e,t){let s=0;return s=(e[t]&127)<<21,s|=(e[t+1]&127)<<14,s|=(e[t+2]&127)<<7,s|=e[t+3]&127,s}function kt(e,t){const s=t;let i=0;for(;Ai(e,t);){i+=10;const r=Es(e,t+6);i+=r,Nn(e,t+10)&&(i+=10),t+=i}if(i>0)return e.subarray(s,s+i)}function Ll(e,t,s,i){const r=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],n=t[s+2],a=n>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);e.emit(g.ERROR,g.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(n>>6&3)+1,l=t[s+3]>>6&3|(n&1)<<2,h="mp4a.40."+o,c=r[a];let u=a;(o===5||o===29)&&(u-=3);const d=[o<<3|(u&14)>>1,(u&1)<<7|l<<3];return ee.log(`manifest codec:${i}, parsed codec:${h}, channels:${l}, rate:${c} (ADTS object type:${o} sampling index:${a})`),{config:d,samplerate:c,channelCount:l,codec:h,parsedCodec:h,manifestCodec:i}}function Bn(e,t){return e[t]===255&&(e[t+1]&246)===240}function Un(e,t){return e[t+1]&1?7:9}function Ii(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function Rl(e,t){return t+5<e.length}function gs(e,t){return t+1<e.length&&Bn(e,t)}function bl(e,t){return Rl(e,t)&&Bn(e,t)&&Ii(e,t)<=e.length-t}function Dl(e,t){if(gs(e,t)){const s=Un(e,t);if(t+s>=e.length)return!1;const i=Ii(e,t);if(i<=s)return!1;const r=t+i;return r===e.length||gs(e,r)}return!1}function $n(e,t,s,i,r){if(!e.samplerate){const n=Ll(t,s,i,r);if(!n)return;te(e,n)}}function Gn(e){return 9216e4/e}function _l(e,t){const s=Un(e,t);if(t+s<=e.length){const i=Ii(e,t)-s;if(i>0)return{headerLength:s,frameLength:i}}}function Kn(e,t,s,i,r){const n=i+r*Gn(e.samplerate),a=_l(t,s);let o;if(a){const{frameLength:h,headerLength:c}=a,u=c+h,d=Math.max(0,s+u-t.length);d?(o=new Uint8Array(u-c),o.set(t.subarray(s+c,t.length),0)):o=t.subarray(s+c,s+u);const f={unit:o,pts:n};return d||e.samples.push(f),{sample:f,length:u,missing:d}}const l=t.length-s;return o=new Uint8Array(l),o.set(t.subarray(s,t.length),0),{sample:{unit:o,pts:n},length:l,missing:-1}}function Pl(e,t){return Ai(e,t)&&Es(e,t+6)+10<=e.length-t}function Cl(e){return e instanceof ArrayBuffer?e:e.byteOffset==0&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function _s(e,t=0,s=1/0){return kl(e,t,s,Uint8Array)}function kl(e,t,s,i){const r=wl(e);let n=1;"BYTES_PER_ELEMENT"in i&&(n=i.BYTES_PER_ELEMENT);const a=Ml(e)?e.byteOffset:0,o=(a+e.byteLength)/n,l=(a+t)/n,h=Math.floor(Math.max(0,Math.min(l,o)));return new i(r,h,Math.floor(Math.min(h+Math.max(s,0),o))-h)}function wl(e){return e instanceof ArrayBuffer?e:e.buffer}function Ml(e){return e&&e.buffer instanceof ArrayBuffer&&e.byteLength!==void 0&&e.byteOffset!==void 0}function Ol(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null},s=3;if(e.size<2||e.data[0]!==s)return;const i=e.data.subarray(1).indexOf(0);if(i===-1)return;const r=be(_s(e.data,1,i)),n=e.data[2+i],a=e.data.subarray(3+i).indexOf(0);if(a===-1)return;const o=be(_s(e.data,3+i,a));let l;return r==="-->"?l=be(_s(e.data,4+i+a)):l=Cl(e.data.subarray(4+i+a)),t.mimeType=r,t.pictureType=n,t.description=o,t.data=l,t}function xl(e){if(e.size<2)return;const t=be(e.data,!0),s=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:s.buffer}}function Fl(e){if(e.size<2)return;if(e.type==="TXXX"){let s=1;const i=be(e.data.subarray(s),!0);s+=i.length+1;const r=be(e.data.subarray(s));return{key:e.type,info:i,data:r}}const t=be(e.data.subarray(1));return{key:e.type,info:"",data:t}}function Nl(e){if(e.type==="WXXX"){if(e.size<2)return;let s=1;const i=be(e.data.subarray(s),!0);s+=i.length+1;const r=be(e.data.subarray(s));return{key:e.type,info:i,data:r}}const t=be(e.data);return{key:e.type,info:"",data:t}}function Bl(e){return e.type==="PRIV"?xl(e):e.type[0]==="W"?Nl(e):e.type==="APIC"?Ol(e):Fl(e)}function Ul(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),s=Es(e,4),i=10;return{type:t,size:s,data:e.subarray(i,i+s)}}var Bt=10,$l=10;function Vn(e){let t=0;const s=[];for(;Ai(e,t);){const i=Es(e,t+6);e[t+5]>>6&1&&(t+=Bt),t+=Bt;const r=t+i;for(;t+$l<r;){const n=Ul(e.subarray(t)),a=Bl(n);a&&s.push(a),t+=n.size+Bt}Nn(e,t)&&(t+=Bt)}return s}function Hn(e){return e&&e.key==="PRIV"&&e.info==="com.apple.streaming.transportStreamTimestamp"}function Gl(e){if(e.data.byteLength===8){const t=new Uint8Array(e.data),s=t[3]&1;let i=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return i/=45,s&&(i+=4772185884e-2),Math.round(i)}}function Li(e){const t=Vn(e);for(let s=0;s<t.length;s++){const i=t[s];if(Hn(i))return Gl(i)}}var Re=(function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e})({});function Fe(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var Ri=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=De(this.cachedData,e),this.cachedData=null);let s=kt(e,0),i=s?s.length:0,r;const n=this._audioTrack,a=this._id3Track,o=s?Li(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&N(o))&&(this.basePTS=Kl(o,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Re.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const h=this.appendFrame(n,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=l}else Pl(e,i)?(s=kt(e,i),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Re.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const h=e.slice(r);this.cachedData?this.cachedData=De(this.cachedData,h):this.cachedData=h}}return{audioTrack:n,videoTrack:Fe(),id3Track:a,textTrack:Fe()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Fe(),id3Track:this._id3Track,textTrack:Fe()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},Kl=(e,t,s)=>{if(N(e))return e*90;const i=s?s.baseTime*9e4/s.timescale:0;return t*9e4+i},Ut=null,Vl=[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],Hl=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Yl=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Wl=[0,1,1,4];function Yn(e,t,s,i,r){if(s+24>t.length)return;const n=Wn(t,s);if(n&&s+n.frameLength<=t.length){const a=i+r*(n.samplesPerFrame*9e4/n.sampleRate),o={unit:t.subarray(s,s+n.frameLength),pts:a,dts:a};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Wn(e,t){const s=e[t+1]>>3&3,i=e[t+1]>>1&3,r=e[t+2]>>4&15,n=e[t+2]>>2&3;if(s!==1&&r!==0&&r!==15&&n!==3){const a=e[t+2]>>1&1,o=e[t+3]>>6,l=s===3?3-i:i===3?3:4,h=Vl[l*14+r-1]*1e3,c=Hl[(s===3?0:s===2?1:2)*3+n],u=o===3?1:2,d=Yl[s][i],f=Wl[i],m=d*8*f,p=Math.floor(d*h/c+a)*f;if(Ut===null){const E=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ut=E?parseInt(E[1]):0}return Ut&&Ut<=87&&i===2&&h>=224e3&&o===0&&(e[t+3]=e[t+3]|128),{sampleRate:c,channelCount:u,frameLength:p,samplesPerFrame:m}}}function bi(e,t){return e[t]===255&&(e[t+1]&224)===224&&(e[t+1]&6)!==0}function qn(e,t){return t+1<e.length&&bi(e,t)}function ql(e,t){return bi(e,t)&&4<=e.length-t}function jn(e,t){if(t+1<e.length&&bi(e,t)){const i=Wn(e,t);let r=4;i!=null&&i.frameLength&&(r=i.frameLength);const n=t+r;return n===e.length||qn(e,n)}return!1}var jl=class extends Ri{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=kt(e,0);let i=s?.length||0;if(jn(e,i))return!1;for(let r=e.length;i<r;i++)if(Dl(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return bl(e,t)}appendFrame(e,t,s){$n(e,this.observer,t,s,e.manifestCodec);const i=Kn(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}},Xn=(e,t)=>{let s=0,i=5;t+=i;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;i>0;){a[0]=e[t];const o=Math.min(i,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,s=s?s<<o|r[0]:r[0],t+=1,i-=o}return s},Xl=class extends Ri{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=zn(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=kt(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&Li(t)!==void 0&&Xn(e,s)<16}};function zn(e,t,s,i,r){if(s+8>t.length||t[s]!==11||t[s+1]!==119)return-1;const n=t[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=t[s+4]&63,l=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][o*3+n]*2;if(s+l>t.length)return-1;const h=t[s+6]>>5;let c=0;h===2?c+=2:(h&1&&h!==1&&(c+=2),h&4&&(c+=2));const u=(t[s+6]<<8|t[s+7])>>12-c&1,d=[2,1,2,3,3,4,4,5][h]+u,f=t[s+5]>>3,m=t[s+5]&7,p=new Uint8Array([n<<6|f<<1|m>>2,(m&3)<<6|h<<3|u<<2|o>>4,o<<4&224]),E=i+r*(1536/a*9e4),y=t.subarray(s,s+l);return e.config=p,e.channelCount=d,e.samplerate=a,e.samples.push({unit:y,pts:E}),l}var zl=class extends Ri{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=kt(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&Li(t)!==void 0&&Xn(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(jn(e,s))return ee.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return ql(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return Yn(e,t,s,this.basePTS,this.frameIndex)}},Ql=/\/emsg[-/]ID3/i,Zl=class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Fe("video",1),n=this.audioTrack=Fe("audio",1),a=this.txtTrack=Fe("text",1);if(this.id3Track=Fe("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const o=nn(e);if(o.video){const{id:l,timescale:h,codec:c,supplemental:u}=o.video;r.id=l,r.timescale=a.timescale=h,r.codec=c,r.supplemental=u}if(o.audio){const{id:l,timescale:h,codec:c}=o.audio;n.id=l,n.timescale=h,n.codec=c}a.id=tn.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Xa(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=De(this.remainderData,e));const a=so(s);this.remainderData=a.remainder,i.samples=a.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=Ui(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Ui(e,t),{videoTrack:t,audioTrack:Fe(),id3Track:i,textTrack:Fe()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=q(e.samples,["emsg"]);i&&i.forEach(r=>{const n=ro(r);if(Ql.test(n.schemeIdUri)){const a=Ar(n,t);let o=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;o<=.001&&(o=Number.POSITIVE_INFINITY);const l=n.payload;s.samples.push({data:l,len:l.byteLength,dts:a,pts:a,type:Re.emsg,duration:o})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const a=Ar(n,t);s.samples.push({data:n.payload,len:n.payload.byteLength,dts:a,pts:a,type:Re.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}};function Ar(e,t){return N(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var Jl=class{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new pi(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,qe.cbc)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(a=>{const o=new Uint8Array(a);i.set(o,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const n=ln(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(o=>{r.data=this.getAvcDecryptedUnit(n,o),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,s,i,n),!this.decrypter.isSync()))return}}}},Qn=class{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,a=[];let o=0,l,h,c,u=-1,d=0;for(r===-1&&(u=0,d=this.getNALuType(t,0),r=0,o=1);o<i;){if(l=t[o++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(h=o-r-1,u>=0){const f={data:t.subarray(u,h),type:d};a.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(n&&o<=4-n&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-n)),h>0&&(f.data=De(f.data,t.subarray(0,h)),f.state=0))}o<i?(c=this.getNALuType(t,o),u=o,d=c,r=0):r=-1}else r=0}if(u>=0&&r>=0){const f={data:t.subarray(u,i),type:d,state:r};a.push(f)}if(a.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=De(f.data,t))}return e.naluState=r,a}},Rt=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&ee.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},eh=class extends Qn{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,a,o=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,c;switch(l.type){case 1:{let m=!1;a=!0;const p=l.data;if(o&&p.length>4){const E=this.readSliceType(p);(E===2||E===4||E===7||E===9)&&(m=!0)}if(m){var u;(u=n)!=null&&u.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.frame=!0,n.key=m;break}case 5:a=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 6:a=!0,di(l.data,1,s.pts,t.samples);break;case 7:{var d,f;a=!0,o=!0;const m=l.data,p=this.readSPS(m);if(!e.sps||e.width!==p.width||e.height!==p.height||((d=e.pixelRatio)==null?void 0:d[0])!==p.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[m];const E=m.subarray(1,4);let y="avc1.";for(let T=0;T<3;T++){let v=E[T].toString(16);v.length<2&&(v="0"+v),y+=v}e.codec=y}break}case 8:a=!0,e.pps=[l.data];break;case 9:a=!0,e.audFound=!0,(c=n)!=null&&c.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:a=!0;break;default:a=!1}n&&a&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Rt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let n=0;n<e;n++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new Rt(e);let s=0,i=0,r=0,n=0,a,o,l;const h=t.readUByte.bind(t),c=t.readBits.bind(t),u=t.readUEG.bind(t),d=t.readBoolean.bind(t),f=t.skipBits.bind(t),m=t.skipEG.bind(t),p=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);h();const y=h();if(c(5),f(3),h(),p(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){const I=u();if(I===3&&f(1),p(),p(),f(1),d())for(o=I!==3?8:12,l=0;l<o;l++)d()&&(l<6?E(16,t):E(64,t))}p();const T=u();if(T===0)u();else if(T===1)for(f(1),m(),m(),a=u(),l=0;l<a;l++)m();p(),f(1);const v=u(),S=u(),R=c(1);R===0&&f(1),f(1),d()&&(s=u(),i=u(),r=u(),n=u());let A=[1,1];if(d()&&d())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[h()<<8|h(),h()<<8|h()]}return{width:Math.ceil((v+1)*16-s*2-i*2),height:(2-R)*(S+1)*16-(R?2:4)*(r+n),pixelRatio:A}}},th=class extends Qn{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,a,o=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,c;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.frame=!0,a=!0;break;case 16:case 17:case 18:case 21:if(a=!0,o){var u;(u=n)!=null&&u.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:a=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 39:a=!0,di(l.data,2,s.pts,t.samples);break;case 32:a=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=te(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(a=!0,o=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const d=this.readSPS(l.data);e.width=d.width,e.height=d.height,e.pixelRatio=d.pixelRatio,e.codec=d.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const f in d.params)e.params[f]=d.params[f]}this.pushParameterSet(e.sps,l.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0;break;case 34:if(a=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const d=this.readPPS(l.data);for(const f in d)e.params[f]=d[f]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:a=!0,e.audFound=!0,(c=n)!=null&&c.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:a=!1}n&&a&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Rt(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new Rt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),a=t.readUByte(),o=t.readUByte(),l=t.readUByte(),h=t.readUByte(),c=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),m=t.readUByte(),p=t.readUByte(),E=t.readUByte(),y=[],T=[];for(let H=0;H<s;H++)y.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let H=s;H<8;H++)t.readBits(2);for(let H=0;H<s;H++)y[H]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[H]&&t.readUByte();t.readUEG();const v=t.readUEG();v==3&&t.skipBits(1);const S=t.readUEG(),R=t.readUEG(),A=t.readBoolean();let I=0,D=0,P=0,_=0;A&&(I+=t.readUEG(),D+=t.readUEG(),P+=t.readUEG(),_+=t.readUEG());const M=t.readUEG(),B=t.readUEG(),x=t.readUEG(),K=t.readBoolean();for(let H=K?0:s;H<=s;H++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let H=0;H<4;H++)for(let de=0;de<(H===3?2:6);de++)if(!t.readBoolean())t.readUEG();else{const ce=Math.min(64,1<<4+(H<<1));H>1&&t.readEG();for(let Pe=0;Pe<ce;Pe++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const F=t.readUEG();let O=0;for(let H=0;H<F;H++){let de=!1;if(H!==0&&(de=t.readBoolean()),de){H===F&&t.readUEG(),t.readBoolean(),t.readUEG();let ce=0;for(let Pe=0;Pe<=O;Pe++){const we=t.readBoolean();let yt=!1;we||(yt=t.readBoolean()),(we||yt)&&ce++}O=ce}else{const ce=t.readUEG(),Pe=t.readUEG();O=ce+Pe;for(let we=0;we<ce;we++)t.readUEG(),t.readBoolean();for(let we=0;we<Pe;we++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const H=t.readUEG();for(let de=0;de<H;de++){for(let ce=0;ce<x+4;ce++)t.readBits(1);t.readBits(1)}}let Y=0,k=1,w=1,G=!0,W=1,Q=0;t.readBoolean(),t.readBoolean();let z=!1;if(t.readBoolean()){if(t.readBoolean()){const H=t.readUByte(),de=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],ce=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];H>0&&H<16?(k=de[H-1],w=ce[H-1]):H===255&&(k=t.readBits(16),w=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),z=t.readBoolean(),z&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(W=t.readBits(32),Q=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const H=t.readBoolean(),de=t.readBoolean();let ce=!1;(H||de)&&(ce=t.readBoolean(),ce&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),ce&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Pe=0;Pe<=s;Pe++){G=t.readBoolean();const we=G||t.readBoolean();let yt=!1;we?t.readEG():yt=t.readBoolean();const Mi=yt?1:t.readUEG()+1;if(H)for(let vt=0;vt<Mi;vt++)t.readUEG(),t.readUEG(),ce&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(de)for(let vt=0;vt<Mi;vt++)t.readUEG(),t.readUEG(),ce&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Y=t.readUEG())}let Z=S,Ee=R;if(A){let H=1,de=1;v===1?H=de=2:v==2&&(H=2),Z=S-H*D-H*I,Ee=R-de*_-de*P}const Se=i?["A","B","C"][i]:"",ke=a<<24|o<<16|l<<8|h;let je=0;for(let H=0;H<32;H++)je=(je|(ke>>H&1)<<31-H)>>>0;let vs=je.toString(16);return n===1&&vs==="2"&&(vs="6"),{codecString:`hvc1.${Se}${n}.${vs}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[c,u,d,f,m,p],general_level_idc:E,bit_depth:M+8,bit_depth_luma_minus8:M,bit_depth_chroma_minus8:B,min_spatial_segmentation_idc:Y,chroma_format_idc:v,frame_rate:{fixed:G,fps:Q/W}},width:Z,height:Ee,pixelRatio:[k,w]}}readPPS(e){const t=new Rt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const s=t.readBoolean(),i=t.readBoolean();let r=1;return i&&s?r=0:i?r=3:s&&(r=2),{parallelismType:r}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},pe=188,sh=class Je{constructor(t,s,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=s,this.typeSupported=i,this.logger=r,this.videoParser=null}static probe(t,s){const i=Je.syncOffset(t);return i>0&&s.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),i!==-1}static syncOffset(t){const s=t.length;let i=Math.min(940,s-pe)+1,r=0;for(;r<i;){let n=!1,a=-1,o=0;for(let l=r;l<s;l+=pe)if(t[l]===71&&(s-l===pe||t[l+pe]===71)){if(o++,a===-1&&(a=l,a!==0&&(i=Math.min(a+18612,t.length-pe)+1)),n||(n=Js(t,l)===0),n&&o>1&&(a===0&&o>2||l+pe>i))return a}else{if(o)return-1;break}r++}return-1}static createTrack(t,s){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:tn[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?s:void 0}}resetInitSegment(t,s,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Je.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=Je.createTrack("audio",r),this._id3Track=Je.createTrack("id3"),this._txtTrack=Je.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=s,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:s,_id3Track:i}=this;t&&(t.pesData=null),s&&(s.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,s,i=!1,r=!1){i||(this.sampleAes=null);let n;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,h=this._txtTrack;let c=a.pid,u=a.pesData,d=o.pid,f=l.pid,m=o.pesData,p=l.pesData,E=null,y=this.pmtParsed,T=this._pmtId,v=t.length;if(this.remainderData&&(t=De(this.remainderData,t),v=t.length,this.remainderData=null),v<pe&&!r)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};const S=Math.max(0,Je.syncOffset(t));v-=(v-S)%pe,v<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,v,t.buffer.byteLength-v));let R=0;for(let I=S;I<v;I+=pe)if(t[I]===71){const D=!!(t[I+1]&64),P=Js(t,I),_=(t[I+3]&48)>>4;let M;if(_>1){if(M=I+5+t[I+4],M===I+pe)continue}else M=I+4;switch(P){case c:D&&(u&&(n=at(u,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,h,n,!1)),u={data:[],size:0}),u&&(u.data.push(t.subarray(M,I+pe)),u.size+=I+pe-M);break;case d:if(D){if(m&&(n=at(m,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n);break;case"mp3":this.parseMPEGPES(o,n);break;case"ac3":this.parseAC3PES(o,n)}m={data:[],size:0}}m&&(m.data.push(t.subarray(M,I+pe)),m.size+=I+pe-M);break;case f:D&&(p&&(n=at(p,this.logger))&&this.parseID3PES(l,n),p={data:[],size:0}),p&&(p.data.push(t.subarray(M,I+pe)),p.size+=I+pe-M);break;case 0:D&&(M+=t[M]+1),T=this._pmtId=ih(t,M);break;case T:{D&&(M+=t[M]+1);const B=rh(t,M,this.typeSupported,i,this.observer,this.logger);c=B.videoPid,c>0&&(a.pid=c,a.segmentCodec=B.segmentVideoCodec),d=B.audioPid,d>0&&(o.pid=d,o.segmentCodec=B.segmentAudioCodec),f=B.id3Pid,f>0&&(l.pid=f),E!==null&&!y&&(this.logger.warn(`MPEG-TS PMT found at ${I} after unknown PID '${E}'. Backtracking to sync byte @${S} to parse all TS packets.`),E=null,I=S-188),y=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=P}}else R++;R>0&&ei(this.observer,new Error(`Found ${R} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=u,o.pesData=m,l.pesData=p;const A={audioTrack:o,videoTrack:a,id3Track:l,textTrack:h};return r&&this.extractRemainingSamples(A),A}flush(){const{remainderData:t}=this;this.remainderData=null;let s;return t?s=this.demux(t,-1,!1,!0):s={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(s),this.sampleAes?this.decrypt(s,this.sampleAes):s}extractRemainingSamples(t){const{audioTrack:s,videoTrack:i,id3Track:r,textTrack:n}=t,a=i.pesData,o=s.pesData,l=r.pesData;let h;if(a&&(h=at(a,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,n,h,!0),i.pesData=null)):i.pesData=a,o&&(h=at(o,this.logger))){switch(s.segmentCodec){case"aac":this.parseAACPES(s,h);break;case"mp3":this.parseMPEGPES(s,h);break;case"ac3":this.parseAC3PES(s,h)}s.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),s.pesData=o;l&&(h=at(l,this.logger))?(this.parseID3PES(r,h),r.pesData=null):r.pesData=l}demuxSampleAes(t,s,i){const r=this.demux(t,i,!0,!this.config.progressive),n=this.sampleAes=new Jl(this.observer,this.config,s);return this.decrypt(r,n)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new eh:t==="hevc"&&(this.videoParser=new th))}decrypt(t,s){return new Promise(i=>{const{audioTrack:r,videoTrack:n}=t;r.samples&&r.segmentCodec==="aac"?s.decryptAacSamples(r.samples,0,()=>{n.samples?s.decryptAvcSamples(n.samples,0,0,()=>{i(t)}):i(t)}):n.samples&&s.decryptAvcSamples(n.samples,0,0,()=>{i(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,s){let i=0;const r=this.aacOverFlow;let n=s.data;if(r){this.aacOverFlow=null;const u=r.missing,d=r.sample.unit.byteLength;if(u===-1)n=De(r.sample.unit,n);else{const f=d-u;r.sample.unit.set(n.subarray(0,u),f),t.samples.push(r.sample),i=r.missing}}let a,o;for(a=i,o=n.length;a<o-1&&!gs(n,a);a++);if(a!==i){let u;const d=a<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${a}`:u="No ADTS header found in AAC PES",ei(this.observer,new Error(u),d,this.logger),!d)return}$n(t,this.observer,n,a,this.audioCodec);let l;if(s.pts!==void 0)l=s.pts;else if(r){const u=Gn(t.samplerate);l=r.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let h=0,c;for(;a<o;)if(c=Kn(t,n,a,l,h),a+=c.length,c.missing){this.aacOverFlow=c;break}else for(h++;a<o-1&&!gs(n,a);a++);}parseMPEGPES(t,s){const i=s.data,r=i.length;let n=0,a=0;const o=s.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(qn(i,a)){const l=Yn(t,i,a,o,n);if(l)a+=l.length,n++;else break}else a++}parseAC3PES(t,s){{const i=s.data,r=s.pts;if(r===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const n=i.length;let a=0,o=0,l;for(;o<n&&(l=zn(t,i,o,r,a++))>0;)o+=l}}parseID3PES(t,s){if(s.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=te({},s,{type:this._videoTrack?Re.emsg:Re.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}};function Js(e,t){return((e[t+1]&31)<<8)+e[t+2]}function ih(e,t){return(e[t+10]&31)<<8|e[t+11]}function rh(e,t,s,i,r,n){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(e[t+1]&15)<<8|e[t+2],l=t+3+o-4,h=(e[t+10]&15)<<8|e[t+11];for(t+=12+h;t<l;){const c=Js(e,t),u=(e[t+3]&15)<<8|e[t+4];switch(e[t]){case 207:if(!i){Ps("ADTS AAC",n);break}case 15:a.audioPid===-1&&(a.audioPid=c);break;case 21:a.id3Pid===-1&&(a.id3Pid=c);break;case 219:if(!i){Ps("H.264",n);break}case 27:a.videoPid===-1&&(a.videoPid=c);break;case 3:case 4:!s.mpeg&&!s.mp3?n.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=c,a.segmentAudioCodec="mp3");break;case 193:if(!i){Ps("AC-3",n);break}case 129:s.ac3?a.audioPid===-1&&(a.audioPid=c,a.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&u>0){let d=t+5,f=u;for(;f>2;){e[d]===106&&(s.ac3!==!0?n.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=c,a.segmentAudioCodec="ac3"));const m=e[d+1]+2;d+=m,f-=m}}break;case 194:case 135:return ei(r,new Error("Unsupported EC-3 in M2TS found"),void 0,n),a;case 36:a.videoPid===-1&&(a.videoPid=c,a.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}t+=u+5}return a}function ei(e,t,s,i){i.warn(`parsing error: ${t.message}`),e.emit(g.ERROR,g.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,error:t,reason:t.message})}function Ps(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function at(e,t){let s=0,i,r,n,a,o;const l=e.data;if(!e||e.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=De(l[0],l[1]),l.splice(1,1);if(i=l[0],(i[0]<<16)+(i[1]<<8)+i[2]===1){if(r=(i[4]<<8)+i[5],r&&r>e.size-6)return null;const h=i[7];h&192&&(a=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,h&64?(o=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,a-o>54e5&&(t.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),n=i[8];let c=n+9;if(e.size<=c)return null;e.size-=c;const u=new Uint8Array(e.size);for(let d=0,f=l.length;d<f;d++){i=l[d];let m=i.byteLength;if(c)if(c>m){c-=m;continue}else i=i.subarray(c),m-=c,c=0;u.set(i,s),s+=m}return r&&(r-=n+3),{data:u,pts:a,dts:o,len:r}}return null}var nh=class{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}},Ve=Math.pow(2,32)-1,me=class b{static init(){b.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in b.types)b.types.hasOwnProperty(t)&&(b.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const s=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);b.HDLR_TYPES={video:s,audio:i};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),n=new Uint8Array([0,0,0,0,0,0,0,0]);b.STTS=b.STSC=b.STCO=n,b.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),b.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),b.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),b.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);b.FTYP=b.box(b.types.ftyp,a,l,a,o),b.DINF=b.box(b.types.dinf,b.box(b.types.dref,r))}static box(t,...s){let i=8,r=s.length;const n=r;for(;r--;)i+=s[r].byteLength;const a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=i&255,a.set(t,4),r=0,i=8;r<n;r++)a.set(s[r],i),i+=s[r].byteLength;return a}static hdlr(t){return b.box(b.types.hdlr,b.HDLR_TYPES[t])}static mdat(t){return b.box(b.types.mdat,t)}static mdhd(t,s){s*=t;const i=Math.floor(s/(Ve+1)),r=Math.floor(s%(Ve+1));return b.box(b.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))}static mdia(t){return b.box(b.types.mdia,b.mdhd(t.timescale||0,t.duration||0),b.hdlr(t.type),b.minf(t))}static mfhd(t){return b.box(b.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?b.box(b.types.minf,b.box(b.types.smhd,b.SMHD),b.DINF,b.stbl(t)):b.box(b.types.minf,b.box(b.types.vmhd,b.VMHD),b.DINF,b.stbl(t))}static moof(t,s,i){return b.box(b.types.moof,b.mfhd(t),b.traf(i,s))}static moov(t){let s=t.length;const i=[];for(;s--;)i[s]=b.trak(t[s]);return b.box.apply(null,[b.types.moov,b.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(b.mvex(t)))}static mvex(t){let s=t.length;const i=[];for(;s--;)i[s]=b.trex(t[s]);return b.box.apply(null,[b.types.mvex,...i])}static mvhd(t,s){s*=t;const i=Math.floor(s/(Ve+1)),r=Math.floor(s%(Ve+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,i>>24,i>>16&255,i>>8&255,i&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return b.box(b.types.mvhd,n)}static sdtp(t){const s=t.samples||[],i=new Uint8Array(4+s.length);let r,n;for(r=0;r<s.length;r++)n=s[r].flags,i[r+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return b.box(b.types.sdtp,i)}static stbl(t){return b.box(b.types.stbl,b.stsd(t),b.box(b.types.stts,b.STTS),b.box(b.types.stsc,b.STSC),b.box(b.types.stsz,b.STSZ),b.box(b.types.stco,b.STCO))}static avc1(t){let s=[],i=[],r,n,a;for(r=0;r<t.sps.length;r++)n=t.sps[r],a=n.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(n));for(r=0;r<t.pps.length;r++)n=t.pps[r],a=n.byteLength,i.push(a>>>8&255),i.push(a&255),i=i.concat(Array.prototype.slice.call(n));const o=b.box(b.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(i))),l=t.width,h=t.height,c=t.pixelRatio[0],u=t.pixelRatio[1];return b.box(b.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,h>>8&255,h&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,b.box(b.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),b.box(b.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(t){const s=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,...s,6,1,2])}static audioStsd(t){const s=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,s>>8&255,s&255,0,0])}static mp4a(t){return b.box(b.types.mp4a,b.audioStsd(t),b.box(b.types.esds,b.esds(t)))}static mp3(t){return b.box(b.types[".mp3"],b.audioStsd(t))}static ac3(t){return b.box(b.types["ac-3"],b.audioStsd(t),b.box(b.types.dac3,t.config))}static stsd(t){const{segmentCodec:s}=t;if(t.type==="audio"){if(s==="aac")return b.box(b.types.stsd,b.STSD,b.mp4a(t));if(s==="ac3"&&t.config)return b.box(b.types.stsd,b.STSD,b.ac3(t));if(s==="mp3"&&t.codec==="mp3")return b.box(b.types.stsd,b.STSD,b.mp3(t))}else if(t.pps&&t.sps){if(s==="avc")return b.box(b.types.stsd,b.STSD,b.avc1(t));if(s==="hevc"&&t.vps)return b.box(b.types.stsd,b.STSD,b.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${s}/${t.codec})`)}static tkhd(t){const s=t.id,i=(t.duration||0)*(t.timescale||0),r=t.width||0,n=t.height||0,a=Math.floor(i/(Ve+1)),o=Math.floor(i%(Ve+1));return b.box(b.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,s>>24&255,s>>16&255,s>>8&255,s&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,n>>8&255,n&255,0,0]))}static traf(t,s){const i=b.sdtp(t),r=t.id,n=Math.floor(s/(Ve+1)),a=Math.floor(s%(Ve+1));return b.box(b.types.traf,b.box(b.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),b.box(b.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&255])),b.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,b.box(b.types.trak,b.tkhd(t),b.mdia(t))}static trex(t){const s=t.id;return b.box(b.types.trex,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,s){const i=t.samples||[],r=i.length,n=12+16*r,a=new Uint8Array(n);let o,l,h,c,u,d;for(s+=8+n,a.set([t.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255],0),o=0;o<r;o++)l=i[o],h=l.duration,c=l.size,u=l.flags,d=l.cts,a.set([h>>>24&255,h>>>16&255,h>>>8&255,h&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return b.box(b.types.trun,a)}static initSegment(t){b.types||b.init();const s=b.moov(t);return De(b.FTYP,s)}static hvc1(t){const s=t.params,i=[t.vps,t.sps,t.pps],r=new Uint8Array([1,s.general_profile_space<<6|(s.general_tier_flag?32:0)|s.general_profile_idc,s.general_profile_compatibility_flags[0],s.general_profile_compatibility_flags[1],s.general_profile_compatibility_flags[2],s.general_profile_compatibility_flags[3],s.general_constraint_indicator_flags[0],s.general_constraint_indicator_flags[1],s.general_constraint_indicator_flags[2],s.general_constraint_indicator_flags[3],s.general_constraint_indicator_flags[4],s.general_constraint_indicator_flags[5],s.general_level_idc,240|s.min_spatial_segmentation_idc>>8,255&s.min_spatial_segmentation_idc,252|s.parallelismType,252|s.chroma_format_idc,248|s.bit_depth_luma_minus8,248|s.bit_depth_chroma_minus8,0,parseInt(s.frame_rate.fps),3|s.temporal_id_nested<<2|s.num_temporal_layers<<3|(s.frame_rate.fixed?64:0),i.length]);let n=r.length;for(let f=0;f<i.length;f+=1){n+=3;for(let m=0;m<i[f].length;m+=1)n+=2+i[f][m].length}const a=new Uint8Array(n);a.set(r,0),n=r.length;const o=i.length-1;for(let f=0;f<i.length;f+=1){a.set(new Uint8Array([32+f|(f===o?128:0),0,i[f].length]),n),n+=3;for(let m=0;m<i[f].length;m+=1)a.set(new Uint8Array([i[f][m].length>>8,i[f][m].length&255]),n),n+=2,a.set(i[f][m],n),n+=i[f][m].length}const l=b.box(b.types.hvcC,a),h=t.width,c=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return b.box(b.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,h&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,b.box(b.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),b.box(b.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&255])))}};me.types=void 0;me.HDLR_TYPES=void 0;me.STTS=void 0;me.STSC=void 0;me.STCO=void 0;me.STSZ=void 0;me.VMHD=void 0;me.SMHD=void 0;me.STSD=void 0;me.FTYP=void 0;me.DINF=void 0;var Zn=9e4;function Di(e,t,s=1,i=!1){const r=e*t*s;return i?Math.round(r):r}function ah(e,t,s=1,i=!1){return Di(e,t,1/s,i)}function Tt(e,t=!1){return Di(e,1e3,1/Zn,t)}function oh(e,t=1){return Di(e,Zn,1/t)}function Ir(e){const{baseTime:t,timescale:s,trackId:i}=e;return`${t/s} (${t}/${s}) trackId: ${i}`}var lh=1e4,hh=1024,ch=1152,uh=1536,Jn=8589934592,ot=null,Cs=null;function Lr(e,t,s,i){return{duration:t,size:s,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Zt=class extends _e{constructor(e,t,s,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=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,ot===null){const r=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ot=r?parseInt(r[1]):0}if(Cs===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Cs=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Ir(t)} > ${e&&Ir(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((r,n)=>{let a=n.pts,o=a-r;return o<-4294967296&&(t=!0,a=Le(a,s),o=a-r),o>0?r:a},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,a,o){let l,h,c,u,d,f,m=r,p=r;const E=e.pid>-1,y=t.pid>-1,T=t.samples.length,v=e.samples.length>0,S=a&&T>0||T>1;if((!E||v)&&(!y||S)||this.ISGenerated||a){if(this.ISGenerated){var R,A,I,D;const B=this.videoTrackConfig;(B&&(t.width!==B.width||t.height!==B.height||((R=t.pixelRatio)==null?void 0:R[0])!==((A=B.pixelRatio)==null?void 0:A[0])||((I=t.pixelRatio)==null?void 0:I[1])!==((D=B.pixelRatio)==null?void 0:D[1]))||!B&&S||this.nextAudioTs===null&&v)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(e,t,r,n));const P=this.isVideoContiguous;let _=-1,M;if(S&&(_=dh(t.samples),!P&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,_>0){this.warn(`Dropped ${_} out of ${T} video samples due to a missing keyframe`);const B=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(_),t.dropped+=_,p+=(t.samples[0].pts-B)/t.inputTimeScale,M=p}else _===-1&&(this.warn(`No keyframe found out of ${T} video samples`),f=!1);if(this.ISGenerated){if(v&&S){const B=this.getVideoStartPts(t.samples),x=(Le(e.samples[0].pts,B)-B)/t.inputTimeScale;m+=Math.max(0,x),p+=Math.max(0,-x)}if(v){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,m,this.isAudioContiguous,n,y||S||o===U.AUDIO?p:void 0),S){const B=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,p,P,B)}}else S&&(l=this.remuxVideo(t,p,P,0));l&&(l.firstKeyFrame=_,l.independent=_!==-1,l.firstKeyFramePTS=M)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(d=ea(s,r,this._initPTS,this._initDTS)),i.samples.length&&(u=ta(i,r,this._initPTS))),{audio:h,video:l,initSegment:c,independent:f,text:u,id3:d}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=Le(e,r);if(n<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r;)n+=Jn;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,a=this.typeSupported,o={},l=this._initPTS;let h=!l||i,c="audio/mp4",u,d,f,m=-1;if(h&&(u=d=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":a.mpeg?(c="audio/mpeg",e.codec=""):a.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}o.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):me.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(m=e.id,f=e.inputTimeScale,!l||f!==l.timescale?u=d=this.computeInitPts(r[0].pts,f,s,"audio"):h=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:me.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(m=t.id,f=t.inputTimeScale,!l||f!==l.timescale){const p=this.getVideoStartPts(n),E=Le(n[0].dts,p),y=this.computeInitPts(E,f,s,"video"),T=this.computeInitPts(p,f,s,"video");d=Math.min(d,y),u=Math.min(u,T)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${u/f} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${u/f} (${u}/${f}) trackId: ${m}`),this._initPTS={baseTime:u,timescale:f,trackId:m},this._initDTS={baseTime:d,timescale:f,trackId:m}):u=f=void 0,{tracks:o,initPTS:u,timescale:f,trackId:m}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,a=[],o=n.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let c=this.nextVideoTs,u=8,d=this.videoSampleDuration,f,m,p=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,y=!1;if(!s||c===null){const k=h+t*r,w=n[0].pts-Le(n[0].dts,n[0].pts);ot&&c!==null&&Math.abs(k-w-(c+h))<15e3?s=!0:c=k-w-h}const T=c+h;for(let k=0;k<o;k++){const w=n[k];w.pts=Le(w.pts,T),w.dts=Le(w.dts,T),w.dts<n[k>0?k-1:k].dts&&(y=!0)}y&&n.sort(function(k,w){const G=k.dts-w.dts,W=k.pts-w.pts;return G||W}),f=n[0].dts,m=n[n.length-1].dts;const v=m-f,S=v?Math.round(v/(o-1)):d||e.inputTimeScale/30;if(s){const k=f-T,w=k>S,G=k<-1;if((w||G)&&(w?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Tt(k,!0)} ms (${k}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Tt(-k,!0)} ms (${k}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!G||T>=n[0].pts||ot)){f=T;const W=n[0].pts-k;if(w)n[0].dts=f,n[0].pts=W;else{let Q=!0;for(let z=0;z<n.length&&!(n[z].dts>W&&Q);z++){const Z=n[z].pts;if(n[z].dts-=k,n[z].pts-=k,z<n.length-1){const Ee=n[z+1].pts;Q=Ee<=n[z].pts==Ee<=Z}}}this.log(`Video: Initial PTS/DTS adjusted: ${Tt(W,!0)}/${Tt(f,!0)}, delta: ${Tt(k,!0)} ms`)}}f=Math.max(0,f);let R=0,A=0,I=f;for(let k=0;k<o;k++){const w=n[k],G=w.units,W=G.length;let Q=0;for(let z=0;z<W;z++)Q+=G[z].data.length;A+=Q,R+=W,w.length=Q,w.dts<I?(w.dts=I,I+=S/4|0||1):I=w.dts,p=Math.min(w.pts,p),E=Math.max(w.pts,E)}m=n[o-1].dts;const D=A+4*R+8;let P;try{P=new Uint8Array(D)}catch(k){this.observer.emit(g.ERROR,g.ERROR,{type:$.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:k,bytes:D,reason:`fail allocating video mdat ${D}`});return}const _=new DataView(P.buffer);_.setUint32(0,D),P.set(me.types.mdat,4);let M=!1,B=Number.POSITIVE_INFINITY,x=Number.POSITIVE_INFINITY,K=Number.NEGATIVE_INFINITY,F=Number.NEGATIVE_INFINITY;for(let k=0;k<o;k++){const w=n[k],G=w.units;let W=0;for(let Z=0,Ee=G.length;Z<Ee;Z++){const Se=G[Z],ke=Se.data,je=Se.data.byteLength;_.setUint32(u,je),u+=4,P.set(ke,u),u+=je,W+=4+je}let Q;if(k<o-1)d=n[k+1].dts-w.dts,Q=n[k+1].pts-w.pts;else{const Z=this.config,Ee=k>0?w.dts-n[k-1].dts:S;if(Q=k>0?w.pts-n[k-1].pts:S,Z.stretchShortVideoTrack&&this.nextAudioTs!==null){const Se=Math.floor(Z.maxBufferHole*r),ke=(i?p+i*r:this.nextAudioTs+h)-w.pts;ke>Se?(d=ke-Ee,d<0?d=Ee:M=!0,this.log(`It is approximately ${ke/90} ms to the next segment; using duration ${d/90} ms for the last video frame.`)):d=Ee}else d=Ee}const z=Math.round(w.pts-w.dts);B=Math.min(B,d),K=Math.max(K,d),x=Math.min(x,Q),F=Math.max(F,Q),a.push(Lr(w.key,d,W,z))}if(a.length){if(ot){if(ot<70){const k=a[0].flags;k.dependsOn=2,k.isNonSync=0}}else if(Cs&&F-x<K-B&&S/K<.025&&a[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let k=f;for(let w=0,G=a.length;w<G;w++){const W=k+a[w].duration,Q=k+a[w].cts;if(w<G-1){const z=W+a[w+1].cts;a[w].duration=z-Q}else a[w].duration=w?a[w-1].duration:S;a[w].cts=0,k=W}}}d=M||!d?S:d;const O=m+d;this.nextVideoTs=c=O-h,this.videoSampleDuration=d,this.isVideoContiguous=!0;const Y={data1:me.moof(e.sequenceNumber++,f,te(e,{samples:a})),data2:P,startPTS:(p-h)/r,endPTS:(E+d-h)/r,startDTS:(f-h)/r,endDTS:c/r,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Y}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return ch;case"ac3":return uh;default:return hh}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,a=n/(e.samplerate?e.samplerate:n),o=this.getSamplesPerFrame(e),l=o*a,h=this._initPTS,c=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,u=[],d=r!==void 0;let f=e.samples,m=c?0:8,p=this.nextAudioTs||-1;const E=h.baseTime*n/h.timescale,y=E+t*n;if(this.isAudioContiguous=s=s||f.length&&p>0&&(i&&Math.abs(y-(p+E))<9e3||Math.abs(Le(f[0].pts,y)-(p+E))<20*l),f.forEach(function(x){x.pts=Le(x.pts,y)}),!s||p<0){const x=f.length;if(f=f.filter(K=>K.pts>=0),x!==f.length&&this.warn(`Removed ${f.length-x} of ${x} samples (initPTS ${E} / ${n})`),!f.length)return;r===0?p=0:i&&!d?p=Math.max(0,y-E):p=f[0].pts-E}if(e.segmentCodec==="aac"){const x=this.config.maxAudioFramesDrift;for(let K=0,F=p+E;K<f.length;K++){const O=f[K],Y=O.pts,k=Y-F,w=Math.abs(1e3*k/n);if(k<=-x*l&&d)K===0&&(this.warn(`Audio frame @ ${(Y/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*k/n)} ms.`),this.nextAudioTs=p=Y-E,F=Y);else if(k>=x*l&&w<lh&&d){let G=Math.round(k/l);for(F=Y-G*l;F<0&&G&&l;)G--,F+=l;K===0&&(this.nextAudioTs=p=F-E),this.warn(`Injecting ${G} audio frames @ ${((F-E)/n).toFixed(3)}s due to ${Math.round(1e3*k/n)} ms gap.`);for(let W=0;W<G;W++){let Q=nh.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);Q||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),Q=O.unit.subarray()),f.splice(K,0,{unit:Q,pts:F}),F+=l,K++}}O.pts=F,F+=l}}let T=null,v=null,S,R=0,A=f.length;for(;A--;)R+=f[A].unit.byteLength;for(let x=0,K=f.length;x<K;x++){const F=f[x],O=F.unit;let Y=F.pts;if(v!==null){const w=u[x-1];w.duration=Math.round((Y-v)/a)}else if(s&&e.segmentCodec==="aac"&&(Y=p+E),T=Y,R>0){R+=m;try{S=new Uint8Array(R)}catch(w){this.observer.emit(g.ERROR,g.ERROR,{type:$.MUX_ERROR,details:L.REMUX_ALLOC_ERROR,fatal:!1,error:w,bytes:R,reason:`fail allocating audio mdat ${R}`});return}c||(new DataView(S.buffer).setUint32(0,R),S.set(me.types.mdat,4))}else return;S.set(O,m);const k=O.byteLength;m+=k,u.push(Lr(!0,o,k,0)),v=Y}const I=u.length;if(!I)return;const D=u[u.length-1];p=v-E,this.nextAudioTs=p+a*D.duration;const P=c?new Uint8Array(0):me.moof(e.sequenceNumber++,T/a,te({},e,{samples:u}));e.samples=[];const _=(T-E)/n,M=this.nextAudioTs/n,B={data1:P,data2:S,startPTS:_,endPTS:M,startDTS:_,endDTS:M,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,B}};function Le(e,t){let s;if(t===null)return e;for(t<e?s=-8589934592:s=Jn;Math.abs(e-t)>4294967296;)e+=s;return e}function dh(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function ea(e,t,s,i){const r=e.samples.length;if(!r)return;const n=e.inputTimeScale;for(let o=0;o<r;o++){const l=e.samples[o];l.pts=Le(l.pts-s.baseTime*n/s.timescale,t*n)/n,l.dts=Le(l.dts-i.baseTime*n/i.timescale,t*n)/n}const a=e.samples;return e.samples=[],{samples:a}}function ta(e,t,s){const i=e.samples.length;if(!i)return;const r=e.inputTimeScale;for(let a=0;a<i;a++){const o=e.samples[a];o.pts=Le(o.pts-s.baseTime*r/s.timescale,t*r)/r}e.samples.sort((a,o)=>a.pts-o.pts);const n=e.samples;return e.samples=[],{samples:n}}var fh=class extends _e{constructor(e,t,s,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}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:n}=this.initData=nn(e);if(t)Ja(e,t);else{const o=r||n;o!=null&&o.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${o.codec}")!`)}r&&(s=Rr(r,se.AUDIO,this)),n&&(i=Rr(n,se.VIDEO,this));const a={};r&&n?a.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?a.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?a.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,t,s,i,r,n){var a,o;let{initPTS:l,lastEndTime:h}=this;const c={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};N(h)||(h=this.lastEndTime=r||0);const u=t.samples;if(!u.length)return c;const d={initPTS:void 0,timescale:void 0,trackId:void 0};let f=this.initData;if((a=f)!=null&&a.length||(this.generateInitSegment(u),f=this.initData),!((o=f)!=null&&o.length))return this.warn("Failed to generate initSegment."),c;this.emitInitSegment&&(d.tracks=this.initTracks,this.emitInitSegment=!1);const m=to(u,f,this),p=f.audio?m[f.audio.id]:null,E=f.video?m[f.video.id]:null,y=$t(E,1/0),T=$t(p,1/0),v=$t(E,0,!0),S=$t(p,0,!0);let R=r,A=0;const I=p&&(!E||!l&&T<y||l&&l.trackId===f.audio.id),D=I?p:E;if(D){const Y=D.timescale,k=D.start-r*Y,w=I?f.audio.id:f.video.id;R=D.start/Y,A=I?S-T:v-y,(n||!l)&&(gh(l,R,r,A)||Y!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${k/Y} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${R-r} (${k}/${Y}) trackId: ${w}`),l=null,d.initPTS=k,d.timescale=Y,d.trackId=w)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(d.initPTS=l.baseTime,d.timescale=l.timescale,d.trackId=l.trackId):((!d.timescale||d.trackId===void 0||d.initPTS===void 0)&&(this.warn("Could not set initPTS"),d.initPTS=R,d.timescale=1,d.trackId=-1),this.initPTS=l={baseTime:d.initPTS,timescale:d.timescale,trackId:d.trackId});const P=R-l.baseTime/l.timescale,_=P+A;A>0?this.lastEndTime=_:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const M=!!f.audio,B=!!f.video;let x="";M&&(x+="audio"),B&&(x+="video");const K=(f.audio?f.audio.encrypted:!1)||(f.video?f.video.encrypted:!1),F={data1:u,startPTS:P,startDTS:P,endPTS:_,endDTS:_,type:x,hasAudio:M,hasVideo:B,nb:1,dropped:0,encrypted:K};c.audio=M&&!B?F:void 0,c.video=B?F:void 0;const O=E?.sampleCount;if(O){const Y=E.keyFrameIndex,k=Y!==-1;F.nb=O,F.dropped=Y===0||this.isVideoContiguous?0:k?Y:O,F.independent=k,F.firstKeyFrame=Y,k&&E.keyFrameStart&&(F.firstKeyFramePTS=(E.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(c.independent=k),this.isVideoContiguous||(this.isVideoContiguous=k),F.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${Y}/${O} dropped: ${F.dropped} start: ${F.firstKeyFramePTS||"NA"}`)}return c.initSegment=d,c.id3=ea(s,r,l,l),i.samples.length&&(c.text=ta(i,r,l)),c}};function $t(e,t,s=!1){return e?.start!==void 0?(e.start+(s?e.duration:0))/e.timescale:t}function gh(e,t,s,i){if(e===null)return!0;const r=Math.max(i,1),n=t-e.baseTime/e.timescale;return Math.abs(n-s)>r}function Rr(e,t,s){const i=e.codec;return i&&i.length>4?i:t===se.AUDIO?i==="ec-3"||i==="ac-3"||i==="alac"?i:i==="fLaC"||i==="Opus"?ns(i,!1):(s.warn(`Unhandled audio codec "${i}" in mp4 MAP`),i||"mp4a"):(s.warn(`Unhandled video codec "${i}" in mp4 MAP`),i||"avc1")}var Ke;try{Ke=self.performance.now.bind(self.performance)}catch{Ke=Date.now}var Jt=[{demux:Zl,remux:fh},{demux:sh,remux:Zt},{demux:jl,remux:Zt},{demux:zl,remux:Zt}];Jt.splice(2,0,{demux:Xl,remux:Zt});var br=class{constructor(e,t,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=Ke();let n=new Uint8Array(e);const{currentTransmuxState:a,transmuxConfig:o}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:c,accurateTimeOffset:u,timeOffset:d,initSegmentChange:f}=i||a,{audioCodec:m,videoCodec:p,defaultInitPts:E,duration:y,initSegmentData:T}=o,v=mh(n,t);if(v&>(v.method)){const I=this.getDecrypter(),D=yi(v.method);if(I.isSync()){let P=I.softwareDecrypt(n,v.key.buffer,v.iv.buffer,D);if(s.part>-1){const _=I.flush();P=_&&_.buffer}if(!P)return r.executeEnd=Ke(),ks(s);n=new Uint8Array(P)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(n,v.key.buffer,v.iv.buffer,D).then(P=>{const _=this.push(P,null,s);return this.decryptionPromise=null,_}),this.decryptionPromise}const S=this.needsProbing(h,c);if(S){const I=this.configureTransmuxer(n);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(g.ERROR,g.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),r.executeEnd=Ke(),ks(s)}(h||c||f||S)&&this.resetInitSegment(T,m,p,y,t),(h||f||S)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const R=this.transmux(n,v,d,u,s);this.asyncResult=wt(R);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=Ke(),R}flush(e){const t=e.transmuxing;t.executeStart=Ke();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:a}=i;if(s){const c=s.flush();c&&n.push(this.push(c.buffer,null,e))}const{demuxer:o,remuxer:l}=this;if(!o||!l){t.executeEnd=Ke();const c=[ks(e)];return this.asyncResult?Promise.resolve(c):c}const h=o.flush(a);return wt(h)?(this.asyncResult=!0,h.then(c=>(this.flushRemux(n,c,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:a}=t,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===U.MAIN?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,a,l,o,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=Ke()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:a}=this;!n||!a||(n.resetInitSegment(e,t,s,i),a.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,s,i,r):n=this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,a,o,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let c=0,u=Jt.length;c<u;c++){var n;if((n=Jt[c].demux)!=null&&n.probe(e,this.logger)){r=Jt[c];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.remux,h=r.demux;(!o||!(o instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!a||!(a instanceof h))&&(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new pi(this.config)),e}};function mh(e,t){let s=null;return e.byteLength>0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(s=t),s}var ks=e=>({remuxResult:{},chunkMeta:e});function wt(e){return"then"in e&&e.then instanceof Function}var ph=class{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}},Eh=class{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}},Dr=0,sa=class{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Dr++,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=o=>{const l=o.data,h=this.hls;if(!(!h||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var c;const u=(c=this.workerContext)==null?void 0:c.objectURL;u&&self.URL.revokeObjectURL(u);break}case"transmuxComplete":this.handleTransmuxComplete(l.data);break;case"flush":this.onFlush(l.data);break;case"workerLog":h.logger[l.data.logType]&&h.logger[l.data.logType](l.data.message);break;default:l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,h.trigger(l.event,l.data)}},this.onWorkerError=o=>{if(!this.hls)return;const l=new Error(`${o.message} (${o.filename}:${o.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(g.ERROR,{type:$.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(o,l)=>{l=l||{},l.frag=this.frag||void 0,o===g.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(o,l)};this.observer=new Si,this.observer.on(g.FRAG_DECRYPTED,n),this.observer.on(g.ERROR,n);const a=Ki(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const o=this.hls.logger;if(r.workerPath||Tl()){try{r.workerPath?(o.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Al(r.workerPath)):(o.log(`injecting Web Worker for "${t}"`),this.workerContext=Sl());const{worker:l}=this.workerContext;l.addEventListener("message",this.onWorkerMessage),l.addEventListener("error",this.onWorkerError),l.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:t,config:ie(r)})}catch(l){o.warn(`Error setting up "${t}" Web Worker, fallback to inline`,l),this.terminateWorker(),this.error=null,this.transmuxer=new br(this.observer,a,r,"",t,e.logger)}return}}this.transmuxer=new br(this.observer,a,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Dr++;const t=this.hls.config,s=Ki(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:ie(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Il(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,a,o,l,h){var c,u;l.transmuxing.start=self.performance.now();const{instanceNo:d,transmuxer:f}=this,m=n?n.start:r.start,p=r.decryptdata,E=this.frag,y=!(E&&r.cc===E.cc),T=!(E&&l.level===E.level),v=E?l.sn-E.sn:-1,S=this.part?l.part-this.part.index:-1,R=v===0&&l.id>1&&l.id===E?.stats.chunkCount,A=!T&&(v===1||v===0&&(S===1||R&&S<=0)),I=self.performance.now();(T||v||r.stats.parsing.start===0)&&(r.stats.parsing.start=I),n&&(S||!A)&&(n.stats.parsing.start=I);const D=!(E&&((c=r.initSegment)==null?void 0:c.url)===((u=E.initSegment)==null?void 0:u.url)),P=new Eh(y,A,o,T,m,D);if(!A||y||D){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===U.MAIN?"level":"track"}: ${l.level} id: ${l.id}
discontinuity: ${y}
trackSwitch: ${T}
contiguous: ${A}
accurateTimeOffset: ${o}
timeOffset: ${m}
initSegmentChange: ${D}`);const _=new ph(s,i,t,a,h);this.configureTransmuxer(_)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:d,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:P},e instanceof ArrayBuffer?[e]:[]);else if(f){const _=f.push(e,p,l,P);wt(_)?_.then(M=>{this.handleTransmuxComplete(M)}).catch(M=>{this.transmuxerError(M,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(_)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);wt(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},_r=100,yh=class extends Ti{constructor(e,t,s){super(e,t,s,"audio-stream-controller",U.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(g.BUFFER_RESET,this.onBufferReset,this),e.on(g.BUFFER_CREATED,this.onBufferCreated,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(g.FRAG_LOADING,this.onFragLoading,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(g.BUFFER_RESET,this.onBufferReset,this),e.off(g.BUFFER_CREATED,this.onBufferCreated,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(g.FRAG_LOADING,this.onFragLoading,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){if(s===U.MAIN){const a=t.cc,o=this.fragCurrent;if(this.initPTS[a]={baseTime:i,timescale:r,trackId:n},this.log(`InitPTS for cc: ${a} found from main: ${i/r} (${i}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===C.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==a)&&this.syncWithAnchor(t,l?.frag)}else!this.hls.hasEnoughToStart&&o&&o.cc!==a?(o.abortRequests(),this.syncWithAnchor(t,o)):this.state===C.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&i?.cc===t.cc)return;const r=(i||e).cc,n=pn(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===C.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=C.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(_r),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=C.IDLE):this.state=C.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case C.IDLE:this.doTickIdle();break;case C.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e?.[t],i=s?.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=C.WAITING_INIT_PTS}break}case C.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case C.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,n=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=C.FRAG_LOADING;const a={frag:t,part:s,payload:i.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(a),r&&super._handleFragmentLoadComplete(a)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=C.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:r}=this,n=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||!(s!=null&&s[r]))return;const a=s[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o)){this.state=C.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,se.AUDIO,U.AUDIO));const h=this.getFwdBufferInfo(l,U.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,o)){t.trigger(g.BUFFER_EOS,{type:"audio"}),this.state=C.ENDED;return}const c=h.len,u=t.maxBufferLength,d=o.fragments,f=d[0].start,m=this.getLoadPosition(),p=this.flushing?m:h.end;if(this.switchingTrack&&i){const T=m;o.PTSKnown&&T<f&&(h.end>f||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=f+.05)}if(c>=u&&!this.switchingTrack&&p<d[d.length-1].start)return;let E=this.getNextFragment(p,o);if(E&&this.isLoopLoading(E,p)&&(E=this.getNextFragmentLoopLoading(E,o,h,U.MAIN,u)),!E){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(h,u,E))return;let y=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&y&&oe(E)&&!E.endList&&(!o.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(y)===he.OK&&(this.mainFragLoading=y=null),y&&oe(y))){if(E.start>y.end){const T=this.fragmentTracker.getFragAtPos(p,U.MAIN);T&&T.end>y.end&&(y=T,this.mainFragLoading={frag:T,targetBufferTime:null})}if(E.start>y.end)return}this.loadFragment(E,a,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Pt(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==C.STOPPED&&(this.setInterval(_r),this.state=C.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(g.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:n,groupId:a,track:o}=t;if(!i){this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${a}"`);return}const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==C.STOPPED&&(this.state=C.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${a}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[n];let c=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var u;c=this.alignPlaylists(r,h.details,(u=this.levelLastLoaded)==null?void 0:u.details)}r.alignedSliding||(xn(r,l),r.alignedSliding||fs(r,l),c=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,c),this.hls.trigger(g.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state===C.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=C.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:n,trackId:a,levels:o}=this;if(!o){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=o[a];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const h=l.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const c=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new sa(this.hls,U.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const d=this.initPTS[s.cc],f=(t=s.initSegment)==null?void 0:t.data;if(d!==void 0){const p=i?i.index:-1,E=p!==-1,y=new Ei(s.level,s.sn,s.stats.chunkCount,r.byteLength,p,E);u.push(r,f,c,"",s,i,h.totalduration,!1,y,d)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:m}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Fn,complete:!1};m.push(new Uint8Array(r)),this.state!==C.STOPPED&&(this.state=C.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===U.MAIN&&oe(t.frag)&&(this.mainFragLoading=t,this.state===C.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==U.AUDIO){!this.audioOnly&&s.type===U.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(oe(s)){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(g.AUDIO_TRACK_SWITCHED,J({},r)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(U.AUDIO,t);break;case L.AUDIO_TRACK_LOAD_ERROR:case L.AUDIO_TRACK_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===X.AUDIO_TRACK&&(this.state=C.IDLE);break;case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case L.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==se.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==se.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===C.ENDED&&(this.state=C.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,U.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}const{frag:o,part:l,level:h}=a,{details:c}=h,{audio:u,text:d,id3:f,initSegment:m}=r;if(this.fragContextChanged(o)||!c){this.fragmentTracker.removeFragment(o);return}if(this.state=C.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){const p=o.initSegment||o;if(this.unhandledEncryptionError(m,o))return;this._bufferInitSegment(h,m.tracks,p,n),i.trigger(g.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:s,tracks:m.tracks})}if(u){const{startPTS:p,endPTS:E,startDTS:y,endDTS:T}=u;l&&(l.elementaryStreams[se.AUDIO]={startPTS:p,endPTS:E,startDTS:y,endDTS:T}),o.setElementaryStreamInfo(se.AUDIO,p,E,y,T),this.bufferFragmentData(u,o,l,n)}if(f!=null&&(t=f.samples)!=null&&t.length){const p=te({id:s,frag:o,details:c},f);i.trigger(g.FRAG_PARSING_METADATA,p)}if(d){const p=te({id:s,frag:o,details:c},d);i.trigger(g.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,s,i){if(this.state!==C.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=U.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&n.split(",").length===1&&(r.levelCodec=n),this.hls.trigger(g.BUFFER_CODECS,t);const a=r.initSegment;if(a!=null&&a.byteLength){const o={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:a};this.hls.trigger(g.BUFFER_APPENDING,o)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===he.NOT_LOADED||i===he.PARTIAL){var r;if(!oe(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=C.WAITING_INIT_PTS;const n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&fs(t.details,n)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;et({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:a},e,Ze)||(os(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(g.AUDIO_TRACK_SWITCHED,J({},e))}},_i=class extends _e{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=t?.renditionReports;if(i){let r=-1;for(let n=0;n<i.length;n++){const a=i[n];let o;try{o=new self.URL(a.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),o=a.URI||""}if(o===e){r=n;break}else o===e.substring(0,o.length)&&(r=n)}if(r!==-1){const n=i[r],a=parseInt(n["LAST-MSN"])||t.lastPartSn;let o=parseInt(n["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);o>=0&&h>t.partTarget&&(o+=1)}const l=s&&Vi(s);return new Hi(a,o>=0?o:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),a=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-a;const o=this.hls.config.timelineOffset;if(o!==i.appliedTimelineOffset){const h=Math.max(o||0,0);i.appliedTimelineOffset=h,i.fragments.forEach(c=>{c.setStart(c.playlistOffset+h)})}if(i.live||s!=null&&s.live){const h="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){cl(s,i,this);const E=i.playlistParsingError;if(E){this.warn(E);const y=this.hls;if(!y.config.ignorePlaylistParsingErrors){var l;const{networkDetails:T}=t;y.trigger(g.ERROR,{type:$.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:E,reason:E.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:T,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const c=this.hls.mainForwardBufferInfo,u=c?c.end-c.len:0,d=Cn(i,(i.edge-u)*1e3);if(i.requestScheduled+d<n?i.requestScheduled=n:i.requestScheduled<=n&&(i.requestScheduled+=d),this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let f,m,p;if(i.canBlockReload&&i.endSN&&i.advanced){const E=this.hls.config.lowLatencyMode,y=i.lastPartSn,T=i.endSN,v=i.lastPartIndex,S=v!==-1,R=y===T;S?R?(m=T+1,p=E?0:v):(m=y,p=E?v+1:i.maxPartIndex):m=T+1;const A=i.age,I=A+i.ageHeader;let D=Math.min(I-i.partTarget,i.targetduration*1.5);if(D>0){if(I>i.targetduration*3)this.log(`Playlist last advanced ${A.toFixed(2)}s ago. Omitting segment and part directives.`),m=void 0,p=void 0;else if(s!=null&&s.tuneInGoal&&I-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${D} with playlist age: ${i.age}`),D=0;else{const P=Math.floor(D/i.targetduration);if(m+=P,p!==void 0){const _=Math.round(D%i.targetduration/i.partTarget);p+=_}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${A.toFixed(2)}s goal: ${D} skip sn ${P} to part ${p}`)}i.tuneInGoal=D}if(f=this.getDeliveryDirectives(i,t.deliveryDirectives,m,p),E||!R){i.requestScheduled=n,this.loadingPlaylist(h,f);return}}else(i.canBlockReload||i.canSkipUntil)&&(f=this.getDeliveryDirectives(i,t.deliveryDirectives,m,p));f&&m!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(d-a*2,d/2)),this.scheduleLoading(h,f,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const r=self.performance.now(),n=i.requestScheduled;if(r>=n){this.loadingPlaylist(e,t);return}const a=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),a)}getDeliveryDirectives(e,t,s,i){let r=Vi(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=Xt.No),new Hi(s,i,r)}checkRetry(e){const t=e.details,s=ls(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:a}=i||{},o=!!i&&!!a&&(r===ue.RetryRequest||!i.resolved&&r===ue.SendAlternateToPenaltyBox);if(o){var l;if(n>=a.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=mi(a,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,i.resolved=!0}return o}};function ia(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(!Mt(e[s].attrs,t[s].attrs))return!1;return!0}function Mt(e,t,s){const i=e["STABLE-RENDITION-ID"];return i&&!s?i===t["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(r=>e[r]!==t[r])}function ti(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}var vh=class extends _i{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(g.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVEL_LOADING,this.onLevelLoading,this),e.off(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(g.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(g.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const a=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(a=>i?.indexOf(a)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(u=>!s||s.indexOf(u.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(u=>u.default)&&(this.selectDefaultTrack=!1),a.forEach((u,d)=>{u.id=d});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.audioPreference;if(!r&&o){const u=Ne(o,a,Ze);if(u>-1)r=a[u];else{const d=Ne(o,this.tracks);r=this.tracks[d]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const h={audioTracks:a};this.log(`Updating audio tracks, ${a.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(g.AUDIO_TRACKS_UPDATED,h);const c=this.trackId;if(l!==-1&&c===-1)this.setAudioTrack(l);else if(a.length&&c===-1){var n;const u=new Error(`No audio track selected for current audio group-ID(s): ${(n=this.groupIds)==null?void 0:n.join(",")} track count: ${a.length}`);this.warn(u.message),this.hls.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:u})}}}onError(e,t){t.fatal||!t.context||t.context.type===X.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&et(e,i,Ze))return i;const r=Ne(e,this.tracksInGroup,Ze);if(r>-1){const n=this.tracksInGroup[r];return this.setAudioTrack(r),n}else if(i){let n=t.loadLevel;n===-1&&(n=t.firstAutoLevel);const a=ko(e,t.levels,s,n,Ze);if(a===-1)return null;t.nextLoadLevel=a}if(e.channels||e.audioCodec){const n=Ne(e,s);if(n>-1)return s[n]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(g.AUDIO_TRACK_SWITCHING,J({},i)),r))return;const n=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||et(e,i,Ze)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o}=e;for(let l=0;l<t.length;l++){const h=t[l];if(et({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:a,channels:o},h,Ze))return l}for(let l=0;l<t.length;l++){const h=t[l];if(Mt(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const h=t[l];if(Mt(e.attrs,h.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&os(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=n?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(g.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}},Th=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){this.queues!==null&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const n=(s=this.tracks[e])==null?void 0:s.buffer;n!=null&&n.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
${this.list("video")}
${this.list("audio")}
${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}},Pr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,ra="HlsJsTrackRemovedError",Sh=class extends Error{constructor(e){super(e),this.name=ra}},Ah=class extends _e{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(g.MEDIA_ATTACHED,{media:i,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=Va(We(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.BUFFER_RESET,this.onBufferReset,this),e.on(g.BUFFER_APPENDING,this.onBufferAppending,this),e.on(g.BUFFER_CODECS,this.onBufferCodecs,this),e.on(g.BUFFER_EOS,this.onBufferEos,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.FRAG_PARSED,this.onFragParsed,this),e.on(g.FRAG_CHANGED,this.onFragChanged,this),e.on(g.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.BUFFER_RESET,this.onBufferReset,this),e.off(g.BUFFER_APPENDING,this.onBufferAppending,this),e.off(g.BUFFER_CODECS,this.onBufferCodecs,this),e.off(g.BUFFER_EOS,this.onBufferEos,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.FRAG_PARSED,this.onFragParsed,this),e.off(g.FRAG_CHANGED,this.onFragChanged,this),e.off(g.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const n=this.isQueued();(r||n)&&this.warn(`Transfering MediaSource with${n?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?te(s,i.tracks):this.sourceBuffers.forEach(r=>{const[n]=r;n&&(s[n]=te({},this.tracks[n]),this.removeBuffer(n)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=We(this.appendSource);if(i){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),r)this._objectUrl=s.src,this.attachTransferred();else{const a=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const o=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||o&&n instanceof o,Cr(s),Ih(s,a),s.load()}catch{s.src=a}else s.src=a}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
required tracks: ${ie(s,(o,l)=>o==="initSegment"?void 0:l)};
transfer tracks: ${ie(i,(o,l)=>o==="initSegment"?void 0:l)}}`),!Qr(i,s)){t.mediaSource=null,t.tracks=void 0;const o=e.currentTime,l=this.details,h=Math.max(o,l?.fragments[0].start||0);if(h-o>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${o} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${o}`),this.onMediaDetaching(g.MEDIA_DETACHING,{}),this.onMediaAttaching(g.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(o=>{const l=o,h=i[l];if(h){const c=h.buffer;if(c){const u=this.fragmentTracker,d=h.id;if(u.hasFragments(d)||u.hasParts(d)){const p=j.getBuffered(c);u.detectEvictedFragments(l,p,d,null,!0)}const f=ws(l),m=[l,c];this.sourceBuffers[f]=m,c.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,h)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([a])=>{a&&this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const a=r.readyState==="open";try{const o=r.sourceBuffers;for(let l=o.length;l--;)a&&o[l].abort(),r.removeSourceBuffer(o[l]);a&&r.endOfStream()}catch(o){this.warn(`onMediaDetaching: ${o.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Cr(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(g.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[ws(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Th(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),a=!n&&this.sourceBufferCount&&this.media&&r.some(o=>!i[o]);if(n||a){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(o=>{var l,h;const{id:c,codec:u,levelCodec:d,container:f,metadata:m,supplemental:p}=t[o];let E=i[o];const y=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[o],T=y!=null&&y.buffer?y:E,v=T?.pendingCodec||T?.codec,S=T?.levelCodec;E||(E=i[o]={buffer:void 0,listeners:[],codec:u,supplemental:p,container:f,levelCodec:d,metadata:m,id:c});const R=jt(v,S),A=R?.replace(Pr,"$1");let I=jt(u,d);const D=(h=I)==null?void 0:h.replace(Pr,"$1");I&&R&&A!==D&&(o.slice(0,5)==="audio"&&(I=ns(I,this.appendSource)),this.log(`switching codec ${v} to ${I}`),I!==(E.pendingCodec||E.codec)&&(E.pendingCodec=I),E.container=f,this.appendChangeType(o,f,I))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const n=this.tracks[e];if(n){const a=n.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),a.changeType(i),n.codec=s,n.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,U.MAIN))==null?void 0:t.gap)===!0)return;const r={label:"block-audio",execute:()=>{var n;const a=this.tracks.video;(this.lastVideoAppendEnd>i||a!=null&&a.buffer&&j.isBuffered(a.buffer,i)||((n=this.fragmentTracker.getAppendedFrag(i,U.MAIN))==null?void 0:n.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn("Error executing block-audio operation",n)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:a,part:o,chunkMeta:l,offset:h}=t,c=l.buffering[r],{sn:u,cc:d}=a,f=self.performance.now();c.start=f;const m=a.stats.buffering,p=o?o.stats.buffering:null;m.start===0&&(m.start=f),p&&p.start===0&&(p.start=f);const E=s.audio;let y=!1;r==="audio"&&E?.container==="audio/mpeg"&&(y=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const T=s.video,v=T?.buffer;if(v&&u!=="initSegment"){const A=o||a,I=this.blockedAudioAppend;if(r==="audio"&&n!=="main"&&!this.blockedAudioAppend&&!(T.ending||T.ended)){const D=A.start+A.duration*.05,P=v.buffered,_=this.currentOp("video");!P.length&&!_?this.blockAudio(A):!_&&!j.isBuffered(v,D)&&this.lastVideoAppendEnd<D&&this.blockAudio(A)}else if(r==="video"){const D=A.end;if(I){const P=I.frag.start;(D>P||D<this.lastVideoAppendEnd||j.isBuffered(v,P))&&this.unblockAudio()}this.lastVideoAppendEnd=D}}const S=(o||a).start,R={label:`append-${r}`,execute:()=>{var A;c.executeStart=self.performance.now();const I=(A=this.tracks[r])==null?void 0:A.buffer;I&&(y?this.updateTimestampOffset(I,S,.1,r,u,d):h!==void 0&&N(h)&&this.updateTimestampOffset(I,h,1e-6,r,u,d)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();c.executeEnd=c.end=A,m.first===0&&(m.first=A),p&&p.first===0&&(p.first=A);const I={};this.sourceBuffers.forEach(([D,P])=>{D&&(I[D]=j.getBuffered(P))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(g.BUFFER_APPENDED,{type:r,frag:a,part:o,chunkMeta:l,parent:a.type,timeRanges:I})},onError:A=>{var I;const D={type:$.MEDIA_ERROR,parent:a.type,details:L.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:o,chunkMeta:l,error:A,err:A,fatal:!1},P=(I=this.media)==null?void 0:I.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)D.details=L.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!P)D.errorAction=ft(!0);else if(A.name===ra&&this.sourceBufferCount===0)D.errorAction=ft(!0);else{const _=++this.appendErrors[r];this.warn(`Failed ${_}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${P||"no media error"})`),(_>=this.hls.config.appendErrorMaxRetry||P)&&(D.fatal=!0)}this.hls.trigger(g.ERROR,D)}};this.log(`queuing "${r}" append sn: ${u}${o?" p: "+o.index:""} of ${a.type===U.MAIN?"level":"track"} ${a.level} cc: ${d}`),this.append(R,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(g.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,i,r),n)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[se.AUDIOVIDEO]?r.push("audiovideo"):(n[se.AUDIO]&&r.push("audio"),n[se.VIDEO]&&r.push("video"));const a=()=>{const o=self.performance.now();s.stats.buffering.end=o,i&&(i.stats.buffering.end=o);const l=i?i.stats:s.stats;this.hls.trigger(g.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(a,r).catch(o=>{this.warn(`Fragment buffered callback ${o}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([r])=>{if(r){const n=this.tracks[r];(!t.type||t.type===r)&&(n.ending=!0,n.ended||(n.ended=!0,this.log(`${r} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([r])=>{var n;return r&&!((n=this.tracks[r])!=null&&n.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:r}=this;if(!r||r.readyState!=="open"){r&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${r.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),r.endOfStream(),this.hls.trigger(g.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(g.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===L.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;N(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,a=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(N(a)&&a>=0){const l=Math.max(a,n),h=Math.floor(r/n)*n-l;this.flushBackBuffer(r,n,h)}const o=i.frontBufferFlushThreshold;if(N(o)&&o>0){const l=Math.max(i.maxBufferLength,o),h=Math.max(l,n),c=Math.floor(r/n)*n+h;this.flushFrontBuffer(r,n,c)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const a=j.getBuffered(r);if(a.length>0&&s>a.start(0)){var n;this.hls.trigger(g.BACK_BUFFER_REACHED,{bufferEnd:s});const o=this.tracks[i];if((n=this.details)!=null&&n.live)this.hls.trigger(g.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(o!=null&&o.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(g.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const n=j.getBuffered(r),a=n.length;if(a<2)return;const o=n.start(a-1),l=n.end(a-1);if(s>o||e>=o&&e<=l)return;this.hls.trigger(g.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const a=Math.max(0,t.fragmentStart);return{duration:1/0,start:a,end:Math.max(a,i)}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return N(r)?{duration:r}:null;const n=this.media.duration;return i>(N(s.duration)?s.duration:0)&&i>n||!N(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(N(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ie(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(g.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,a=e[n];if(this.isPending(a)){const o=this.getTrackCodec(a,n),l=`${a.container};codecs=${o}`;a.codec=o,this.log(`creating sourceBuffer(${l})${this.currentOp(n)?" Queued":""} ${ie(a)}`);try{const h=s.addSourceBuffer(l),c=ws(n);t[c]=[n,h],a.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(n),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[n],this.hls.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:n,mimeType:l,parent:a.id});return}this.trackSourceBuffer(n,a)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&Dt(s,"video")&&(i=uo(i,s));const r=jt(i,e.levelCodec);return r?t.slice(0,5)==="audio"?ns(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,n)=>{const a=n.removedRanges;a!=null&&a.length&&this.hls.trigger(g.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,n){const a=t-e.timestampOffset;Math.abs(a)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],a=n?.buffer;if(!i||!r||!a){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const o=N(i.duration)?i.duration:1/0,l=N(r.duration)?r.duration:1/0,h=Math.max(0,t),c=Math.min(s,o,l);c>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${c}] from the ${e} SourceBuffer`),a.remove(h,c)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s?.buffer;if(!i)throw new Sh(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map(r=>this.appendBlocker(r));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(r=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}};function Cr(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(s=>{e.removeChild(s)})}function Ih(e,t){const s=self.document.createElement("source");s.type="video/mp4",s.src=t,e.appendChild(s)}function ws(e){return e==="audio"?1:0}var Lh=class na{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(g.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(g.MANIFEST_PARSED,this.onManifestParsed,this),t.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(g.BUFFER_CODECS,this.onBufferCodecs,this),t.on(g.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(g.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(g.MANIFEST_PARSED,this.onManifestParsed,this),t.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(g.BUFFER_CODECS,this.onBufferCodecs,this),t.off(g.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,s){const i=this.hls.levels[s.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,s){this.media=s.media instanceof HTMLVideoElement?s.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,s){const i=this.hls;this.restrictedLevels=[],this.firstLevel=s.firstLevel,i.config.capLevelToPlayerSize&&s.video&&this.startCapping()}onLevelsUpdated(t,s){this.timer&&N(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,s){this.hls.config.capLevelToPlayerSize&&s.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const s=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&s.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),s.autoLevelCapping=i,s.autoLevelEnabled&&s.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=s.autoLevelCapping}}}getMaxLevel(t){const s=this.hls.levels;if(!s.length)return-1;const i=s.filter((r,n)=>this.isLevelAllowed(r)&&n<=t);return this.clientRect=null,na.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,s={width:0,height:0};if(t){const i=t.getBoundingClientRect();s.width=i.width,s.height=i.height,!s.width&&!s.height&&(s.width=i.right-i.left||t.width||0,s.height=i.bottom-i.top||t.height||0)}return this.clientRect=s,s}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(s=>t.bitrate===s.bitrate&&t.width===s.width&&t.height===s.height)}static getMaxLevelByMediaSize(t,s,i){if(!(t!=null&&t.length))return-1;const r=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let n=t.length-1;const a=Math.max(s,i);for(let o=0;o<t.length;o+=1){const l=t[o];if((l.width>=a||l.height>=a)&&r(l,t[o+1])){n=o;break}}return n}},ve={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Rh={HLS:"h"},st=class si{constructor(t,s){Array.isArray(t)&&(t=t.map(i=>i instanceof si?i:new si(i))),this.value=t,this.params=s}},bh="Dict";function Dh(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":typeof e=="object"?JSON.stringify(e):String(e)}function _h(e,t,s,i){return new Error(`failed to ${e} "${Dh(t)}" as ${s}`,{cause:i})}function Be(e,t,s){return _h("serialize",e,t,s)}var aa=class{constructor(e){this.description=e}},kr="Bare Item",Ph="Boolean";function Ch(e){if(typeof e!="boolean")throw Be(e,Ph);return e?"?1":"?0"}function kh(e){return btoa(String.fromCharCode(...e))}var wh="Byte Sequence";function Mh(e){if(ArrayBuffer.isView(e)===!1)throw Be(e,wh);return`:${kh(e)}:`}var Oh="Integer";function xh(e){return e<-999999999999999||999999999999999<e}function oa(e){if(xh(e))throw Be(e,Oh);return e.toString()}function Fh(e){return`@${oa(e.getTime()/1e3)}`}function la(e,t){if(e<0)return-la(-e,t);const s=Math.pow(10,t);if(Math.abs(e*s%1-.5)<Number.EPSILON){const i=Math.floor(e*s);return(i%2===0?i:i+1)/s}else return Math.round(e*s)/s}var Nh="Decimal";function Bh(e){const t=la(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Be(e,Nh);const s=t.toString();return s.includes(".")?s:`${s}.0`}var Uh="String",$h=/[\x00-\x1f\x7f]+/;function Gh(e){if($h.test(e))throw Be(e,Uh);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Kh(e){return e.description||e.toString().slice(7,-1)}var Vh="Token";function wr(e){const t=Kh(e);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Be(t,Vh);return t}function ii(e){switch(typeof e){case"number":if(!N(e))throw Be(e,kr);return Number.isInteger(e)?oa(e):Bh(e);case"string":return Gh(e);case"symbol":return wr(e);case"boolean":return Ch(e);case"object":if(e instanceof Date)return Fh(e);if(e instanceof Uint8Array)return Mh(e);if(e instanceof aa)return wr(e);default:throw Be(e,kr)}}var Hh="Key";function ri(e){if(/^[a-z*][a-z0-9\-_.*]*$/.test(e)===!1)throw Be(e,Hh);return e}function Pi(e){return e==null?"":Object.entries(e).map(([t,s])=>s===!0?`;${ri(t)}`:`;${ri(t)}=${ii(s)}`).join("")}function ha(e){return e instanceof st?`${ii(e.value)}${Pi(e.params)}`:ii(e)}function Yh(e){return`(${e.value.map(ha).join(" ")})${Pi(e.params)}`}function Wh(e,t={whitespace:!0}){if(typeof e!="object"||e==null)throw Be(e,bh);const s=e instanceof Map?e.entries():Object.entries(e),i=t?.whitespace?" ":"";return Array.from(s).map(([r,n])=>{n instanceof st||(n=new st(n));let a=ri(r);return n.value===!0?a+=Pi(n.params):(a+="=",Array.isArray(n.value)?a+=Yh(n):a+=ha(n)),a}).join(`,${i}`)}function ca(e,t){return Wh(e,t)}var Oe="CMCD-Object",ne="CMCD-Request",Xe="CMCD-Session",He="CMCD-Status",qh={br:Oe,ab:Oe,d:Oe,ot:Oe,tb:Oe,tpb:Oe,lb:Oe,tab:Oe,lab:Oe,url:Oe,pb:ne,bl:ne,tbl:ne,dl:ne,ltc:ne,mtp:ne,nor:ne,nrr:ne,rc:ne,sn:ne,sta:ne,su:ne,ttfb:ne,ttfbb:ne,ttlb:ne,cmsdd:ne,cmsds:ne,smrt:ne,df:ne,cs:ne,ts:ne,cid:Xe,pr:Xe,sf:Xe,sid:Xe,st:Xe,v:Xe,msd:Xe,bs:He,bsd:He,cdn:He,rtp:He,bg:He,pt:He,ec:He,e:He},jh={REQUEST:ne};function Xh(e){return Object.keys(e).reduce((t,s)=>{var i;return(i=e[s])===null||i===void 0||i.forEach(r=>t[r]=s),t},{})}function zh(e,t){const s={};if(!e)return s;const i=Object.keys(e),r=t?Xh(t):{};return i.reduce((n,a)=>{var o;const l=qh[a]||r[a]||jh.REQUEST,h=(o=n[l])!==null&&o!==void 0?o:n[l]={};return h[a]=e[a],n},s)}function Qh(e){return["ot","sf","st","e","sta"].includes(e)}function Zh(e){return typeof e=="number"?N(e):e!=null&&e!==""&&e!==!1}var ua="event";function Jh(e,t){const s=new URL(e),i=new URL(t);if(s.origin!==i.origin)return e;const r=s.pathname.split("/").slice(1),n=i.pathname.split("/").slice(1,-1);for(;r[0]===n[0];)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+s.search+s.hash}var es=e=>Math.round(e),ni=(e,t)=>Array.isArray(e)?e.map(s=>ni(s,t)):e instanceof st&&typeof e.value=="string"?new st(ni(e.value,t),e.params):(t.baseUrl&&(e=Jh(e,t.baseUrl)),t.version===1?encodeURIComponent(e):e),Gt=e=>es(e/100)*100,ec=(e,t)=>{let s=e;return t.version>=2&&(e instanceof st&&typeof e.value=="string"?s=new st([e]):typeof e=="string"&&(s=[e])),ni(s,t)},tc={br:es,d:es,bl:Gt,dl:Gt,mtp:Gt,nor:ec,rtp:Gt,tb:es},da="request",fa="response",Ci=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],sc=["e"],ic=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function ys(e){return ic.test(e)}function rc(e){return Ci.includes(e)||sc.includes(e)||ys(e)}var ga=["d","dl","nor","ot","rtp","su"];function nc(e){return Ci.includes(e)||ga.includes(e)||ys(e)}var ac=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function oc(e){return Ci.includes(e)||ga.includes(e)||ac.includes(e)||ys(e)}var lc=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function hc(e){return lc.includes(e)||ys(e)}var cc={[fa]:oc,[ua]:rc,[da]:nc};function ma(e,t={}){const s={};if(e==null||typeof e!="object")return s;const i=t.version||e.v||1,r=t.reportingMode||da,n=i===1?hc:cc[r];let a=Object.keys(e).filter(n);const o=t.filter;typeof o=="function"&&(a=a.filter(o));const l=r===fa||r===ua;l&&!a.includes("ts")&&a.push("ts"),i>1&&!a.includes("v")&&a.push("v");const h=te({},tc,t.formatters),c={version:i,reportingMode:r,baseUrl:t.baseUrl};return a.sort().forEach(u=>{let d=e[u];const f=h[u];if(typeof f=="function"&&(d=f(d,c)),u==="v"){if(i===1)return;d=i}u=="pr"&&d===1||(l&&u==="ts"&&!N(d)&&(d=Date.now()),Zh(d)&&(Qh(u)&&typeof d=="string"&&(d=new aa(d)),s[u]=d))}),s}function uc(e,t={}){const s={};if(!e)return s;const i=zh(ma(e,t),t?.customHeaderMap);return Object.entries(i).reduce((r,[n,a])=>{const o=ca(a,{whitespace:!1});return o&&(r[n]=o),r},s)}function dc(e,t,s){return te(e,uc(t,s))}var fc="CMCD";function gc(e,t={}){return e?ca(ma(e,t),{whitespace:!1}):""}function mc(e,t={}){if(!e)return"";const s=gc(e,t);return encodeURIComponent(s)}function pc(e,t={}){if(!e)return"";const s=mc(e,t);return`${fc}=${s}`}var Mr=/CMCD=[^&#]+/;function Ec(e,t,s){const i=pc(t,s);return i?Mr.test(e)?e.replace(Mr,i):`${e}${e.includes("?")?"&":"?"}${i}`:e}var yc=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:ve.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:r,part:n}=i,a=this.hls.levels[r.level],o=this.getObjectType(r),l={d:(n||r).duration*1e3,ot:o};(o===ve.VIDEO||o===ve.AUDIO||o==ve.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o));const h=n?this.getNextPart(n):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(l.nor=h.url),this.apply(i,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHED,this.onMediaDetached,this),e.on(g.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHED,this.onMediaDetached,this),e.off(g.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Rh.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){te(t,this.createData());const s=t.ot===ve.INIT||t.ot===ve.VIDEO||t.ot===ve.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((n,a)=>(i.includes(a)&&(n[a]=t[a]),n),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),dc(e.headers,t,r)):e.url=Ec(e.url,t,r)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:n}=i;for(let a=r.length-1;a>=0;a--){const o=r[a];if(o.index===s&&o.fragment.sn===n)return r[a+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return ve.TIMED_TEXT;if(e.sn==="initSegment")return ve.INIT;if(t==="audio")return ve.AUDIO;if(t==="main")return this.hls.audioTracks.length?ve.VIDEO:ve.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===ve.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,n=r>-1?r+1:i.levels.length;s=i.levels.slice(0,n)}return s.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===ve.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:j.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,a){t(r),this.loader.load(r,n,a)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,a){t(r),this.loader.load(r,n,a)}}}},vc=3e5,Tc=class extends _e{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(s?.action===ue.SendAlternateToPenaltyBox&&s.flags===Ie.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:a,pathwayId:o,type:l}=t.context;a&&i?n=this.getPathwayForGroupId(a,l,n):o&&(n=o)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==n),t.details===L.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${i&&i.length} priorities: ${ie(r)} penalized: ${ie(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>vc&&delete s[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in s)continue;if(n===this.pathwayId)return;const a=this.hls.nextLoadLevel,o=this.hls.levels[a];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,Mn(t),this.hls.trigger(g.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[a];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===X.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===X.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:n,"BASE-ID":a,"URI-REPLACEMENT":o}=r;if(t.some(h=>h.pathwayId===n))return;const l=this.getLevelsForPathway(a).map(h=>{const c=new ae(h.attrs);c["PATHWAY-ID"]=n;const u=c.AUDIO&&`${c.AUDIO}_clone_${n}`,d=c.SUBTITLES&&`${c.SUBTITLES}_clone_${n}`;u&&(s[c.AUDIO]=u,c.AUDIO=u),d&&(i[c.SUBTITLES]=d,c.SUBTITLES=d);const f=pa(h.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o),m=new Pt({attrs:c,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:f,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let p=1;p<h.audioGroups.length;p++)m.addGroupId("audio",`${h.audioGroups[p]}_clone_${n}`);if(h.subtitleGroups)for(let p=1;p<h.subtitleGroups.length;p++)m.addGroupId("text",`${h.subtitleGroups[p]}_clone_${n}`);return m});t.push(...l),Or(this.audioTracks,s,o,n),Or(this.subtitleTracks,i,o,n)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(h,c,u,d)=>{this.log(`Loaded steering manifest: "${i}"`);const f=h.data;if(f?.VERSION!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":E}=f;if(m)try{this.uri=new self.URL(m,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||u.url),p&&this.clonePathways(p);const y={steeringManifest:f,url:i.toString()};this.hls.trigger(g.STEERING_MANIFEST_LOADED,y),E&&this.updatePathwayPriority(E)},onError:(h,c,u,d)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${c.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let f=this.timeToLoad*1e3;if(h.code===429){const m=this.loader;if(typeof m?.getResponseHeader=="function"){const p=m.getResponseHeader("Retry-After");p&&(f=parseFloat(p)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,f)},onTimeout:(h,c,u)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,o,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Or(e,t,s,i){e&&Object.keys(t).forEach(r=>{const n=e.filter(a=>a.groupId===r).map(a=>{const o=te({},a);return o.details=void 0,o.attrs=new ae(o.attrs),o.url=o.attrs.URI=pa(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),o.groupId=o.attrs["GROUP-ID"]=t[r],o.attrs["PATHWAY-ID"]=i,o});e.push(...n)})}function pa(e,t,s,i){const{HOST:r,PARAMS:n,[s]:a}=i;let o;t&&(o=a?.[t],o&&(e=o));const l=new self.URL(e);return r&&!o&&(l.host=r),n&&Object.keys(n).sort().forEach(h=>{h&&l.searchParams.set(h,n[h])}),l.href}var Ea=class ts extends _e{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=ts.CDMCleanupPromise?[ts.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=s=>{const{initDataType:i,initData:r}=s,n=`"${s.type}" event: init data type: "${i}"`;if(this.debug(n),r!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=St(this.config));const o=a.map(Ls).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=zt(a);if(i!=="sinf"||o!==re.FAIRPLAY){this.log(`Ignoring "${s.type}" event with init data type: "${i}" for selected key-system ${o}`);return}let l;try{const f=le(new Uint8Array(r)),m=on(vi(JSON.parse(f).sinf));if(!m)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");l=new Uint8Array(m.subarray(8,24))}catch(f){this.warn(`${n} Failed to parse sinf: ${f}`);return}const h=fe(l),{keyIdToKeySessionPromise:c,mediaKeySessions:u}=this;let d=c[h];for(let f=0;f<u.length;f++){const m=u[f],p=m.decryptdata;if(!p.keyId)continue;const E=fe(p.keyId);if(cs(l,p.keyId)||p.uri.replace(/-/g,"").indexOf(h)!==-1){if(d=c[E],!d)continue;if(p.pssh)break;delete c[E],p.pssh=new Uint8Array(r),p.keyId=l,d=c[h]=d.then(()=>this.generateRequestWithPreferredKeySession(m,i,r,"encrypted-event-key-match")),d.catch(y=>this.handleError(y));break}}d||this.handleError(new Error(`Key ID ${h} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=s=>{this.log(`"${s.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(g.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(g.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(g.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(g.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(g.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(g.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:s,widevineLicenseUrl:i}=this.config,r=s?.[t];if(r)return r.licenseUrl;if(t===re.WIDEVINE&&i)return i}getLicenseServerUrlOrThrow(t){const s=this.getLicenseServerUrl(t);if(s===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return s}getServerCertificateUrl(t){const{drmSystems:s}=this.config,i=s?.[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const s=this.hls.levels,i=(a,o,l)=>!!a&&l.indexOf(a)===o,r=s.map(a=>a.audioCodec).filter(i),n=s.map(a=>a.videoCodec).filter(i);return r.length+n.length===0&&n.push("avc1.42e01e"),new Promise((a,o)=>{const l=h=>{const c=h.shift();this.getMediaKeysPromise(c,r,n).then(u=>a({keySystem:c,mediaKeys:u})).catch(u=>{h.length?l(h):u instanceof Ae?o(u):o(new Ae({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};l(t)})}requestMediaKeySystemAccess(t,s){const{requestMediaKeySystemAccessFunc:i}=this.config;if(typeof i!="function"){let r=`Configured requestMediaKeySystemAccess is not a function ${i}`;return Rn===null&&self.location.protocol==="http:"&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return i(t,s)}getMediaKeysPromise(t,s,i){var r;const n=tl(t,s,i,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[t],o=(r=a)==null?void 0:r.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${t}" key-system access with config: ${ie(n)}`),o=this.requestMediaKeySystemAccess(t,n);const l=a=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(h=>{this.log(`Failed to obtain access to key-system "${t}": ${h}`)}),o.then(h=>{this.log(`Access for key-system "${h.keySystem}" obtained`);const c=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const u=l.mediaKeys=h.createMediaKeys().then(d=>(this.log(`Media-keys created for "${t}"`),l.hasMediaKeys=!0,c.then(f=>f?this.setMediaKeysServerCertificate(d,t,f):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${t}"}: ${d}`)}),u})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:s,mediaKeys:i}){this.log(`Creating key-system session "${s}" keyId: ${fe(t.keyId||[])} keyUri: ${t.uri}`);const r={decryptdata:t,keySystem:s,mediaKeys:i,mediaKeysSession:i.createSession(),keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(t){const s=t.decryptdata;if(s.pssh){const i=this.createMediaKeySessionContext(t),r=Kt(s),n="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,n,s.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,s){const i=t.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${fe(t.decryptdata.keyId||[])}
} (data length: ${s.byteLength})`),i.update(s)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>Ls(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:s,mediaKeys:i})=>this.attemptSetMediaKeys(s,i))}selectKeySystem(t){return new Promise((s,i)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:r})=>{const n=Ls(r);n?s(n):i(new Error(`Unable to find format for key-system "${r}"`))}).catch(i)})}selectKeySystemFormat(t){const s=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)),this.keyFormatPromise}getKeyFormatPromise(t){const s=St(this.config),i=t.map(zt).filter(r=>!!r&&s.indexOf(r)!==-1);return this.selectKeySystem(i)}getKeyStatus(t){const{mediaKeySessions:s}=this;for(let i=0;i<s.length;i++){const r=Sc(t,s[i]);if(r)return r}}loadKey(t){const s=t.keyInfo.decryptdata,i=Kt(s),r=this.bannedKeyIds[i];if(r||this.getKeyStatus(s)==="internal-error"){const o=xr(r||"internal-error",s);return this.handleError(o,t.frag),Promise.reject(o)}const n=`(keyId: ${i} format: "${s.keyFormat}" method: ${s.method} uri: ${s.uri})`;this.log(`Starting session for key ${n}`);const a=this.keyIdToKeySessionPromise[i];if(!a){const o=this.getKeySystemForKeyPromise(s).then(({keySystem:l,mediaKeys:h})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${n}`),this.attemptSetMediaKeys(l,h).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:l,mediaKeys:h,decryptdata:s}))))).then(l=>{const h="cenc",c=s.pssh?s.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(l,h,c,"playlist-key")});return o.catch(l=>this.handleError(l,t.frag)),this.keyIdToKeySessionPromise[i]=o,o}return a.catch(o=>{if(o instanceof Ae){const l=J({},o.data);this.getKeyStatus(s)==="internal-error"&&(l.decryptdata=s);const h=new Ae(l,o.message);this.handleError(h,t.frag)}}),a}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,s){if(this.hls)if(t instanceof Ae){s&&(t.data.frag=s);const i=t.data.decryptdata;this.error(`${t.message}${i?` (${fe(i.keyId||[])})`:""}`),this.hls.trigger(g.ERROR,t.data)}else this.error(t.message),this.hls.trigger(g.ERROR,{type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const s=Kt(t),i=this.keyIdToKeySessionPromise[s];if(!i){const r=zt(t.keyFormat),n=r?[r]:St(this.config);return this.attemptKeySystemAccess(n)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=St(this.config)),t.length===0)throw new Ae({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ie({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,s){if(this.mediaResolved=void 0,this.mediaKeys===s)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const r=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(s):new Promise((n,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=s,this.media.setMediaKeys(s).then(n).catch(a)}}));return this.mediaKeys=s,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${t}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(n=>i.indexOf(n)===-1)})}generateRequestWithPreferredKeySession(t,s,i,r){var n;const a=(n=this.config.drmSystems)==null||(n=n[t.keySystem])==null?void 0:n.generateRequest;if(a)try{const m=a.call(this.hls,s,i,t);if(!m)throw new Error("Invalid response from configured generateRequest filter");s=m.initDataType,i=m.initData?m.initData:null,t.decryptdata.pssh=i?new Uint8Array(i):null}catch(m){if(this.warn(m.message),this.hls&&this.hls.config.debug)throw m}if(i===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const o=Kt(t.decryptdata),l=t.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${l} (init data type: ${s} length: ${i.byteLength})`);const h=new Si,c=t._onmessage=m=>{const p=t.mediaKeysSession;if(!p){h.emit("error",new Error("invalid state"));return}const{messageType:E,message:y}=m;this.log(`"${E}" message event for session "${p.sessionId}" message size: ${y.byteLength}`),E==="license-request"||E==="license-renewal"?this.renewLicense(t,y).catch(T=>{h.eventNames().length?h.emit("error",T):this.handleError(T)}):E==="license-release"?t.keySystem===re.FAIRPLAY&&this.updateKeySession(t,zs("acknowledged")).then(()=>this.removeSession(t)).catch(T=>this.handleError(T)):this.warn(`unhandled media key message type "${E}"`)},u=(m,p)=>{p.keyStatus=m;let E;m.startsWith("usable")?h.emit("resolved"):m==="internal-error"||m==="output-restricted"||m==="output-downscaled"?E=xr(m,p.decryptdata):m==="expired"?E=new Error(`key expired (keyId: ${o})`):m==="released"?E=new Error("key released"):m==="status-pending"||this.warn(`unhandled key status change "${m}" (keyId: ${o})`),E&&(h.eventNames().length?h.emit("error",E):this.handleError(E))},d=t._onkeystatuseschange=m=>{if(!t.mediaKeysSession){h.emit("error",new Error("invalid state"));return}const p=this.getKeyStatuses(t);if(!Object.keys(p).some(T=>p[T]!=="status-pending"))return;if(p[o]==="expired"){this.log(`Expired key ${ie(p)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let E=p[o];if(E)u(E,t);else{var y;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(y=t.keyStatusTimeouts)[o]||(y[o]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const v=this.getKeyStatus(t.decryptdata);if(v&&v!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${v} from other session.`),u(v,t);this.log(`key status for ${o} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),E="internal-error",u(E,t)},1e3)),this.log(`No status for keyId ${o} (${ie(p)}).`)}};ye(t.mediaKeysSession,"message",c),ye(t.mediaKeysSession,"keystatuseschange",d);const f=new Promise((m,p)=>{h.on("error",p),h.on("resolved",m)});return t.mediaKeysSession.generateRequest(s,i).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${l}`)}).catch(m=>{throw new Ae({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_NO_SESSION,error:m,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${m}`)}).then(()=>f).catch(m=>(h.removeAllListeners(),this.removeSession(t).then(()=>{throw m}))).then(()=>(h.removeAllListeners(),t))}getKeyStatuses(t){const s={};return t.mediaKeysSession.keyStatuses.forEach((i,r)=>{if(typeof r=="string"&&typeof i=="object"){const o=r;r=i,i=o}const n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(t.keySystem===re.PLAYREADY&&n.length===16){const o=fe(n);s[o]=i,In(n)}const a=fe(n);i==="internal-error"&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${t.mediaKeysSession.sessionId}"`),s[a]=i}),s}fetchServerCertificate(t){const s=this.config,i=s.loader,r=new i(s),n=this.getServerCertificateUrl(t);return n?(this.log(`Fetching server certificate for "${t}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:n},h=s.certLoadPolicy.default,c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(l,c,{onSuccess:(u,d,f,m)=>{a(u.data)},onError:(u,d,f,m)=>{o(new Ae({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:J({url:l.url,data:void 0},u)},`"${t}" certificate request failed (${n}). Status: ${u.code} (${u.text})`))},onTimeout:(u,d,f)=>{o(new Ae({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${n})`))},onAbort:(u,d,f)=>{o(new Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(t,s,i){return new Promise((r,n)=>{t.setServerCertificate(i).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${i.byteLength}) on "${s}"`),r(t)}).catch(a=>{n(new Ae({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(t,s){return this.requestLicense(t,new Uint8Array(s)).then(i=>this.updateKeySession(t,new Uint8Array(i)).catch(r=>{throw new Ae({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(t,s){const i=String.fromCharCode.apply(null,new Uint16Array(s.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),s;const r=new DOMParser().parseFromString(i,"application/xml"),n=r.querySelectorAll("HttpHeader");if(n.length>0){let c;for(let u=0,d=n.length;u<d;u++){var a,o;c=n[u];const f=(a=c.querySelector("name"))==null?void 0:a.textContent,m=(o=c.querySelector("value"))==null?void 0:o.textContent;f&&m&&t.setRequestHeader(f,m)}}const l=r.querySelector("Challenge"),h=l?.textContent;if(!h)throw new Error("Cannot find <Challenge> in key message");return zs(atob(h))}setupLicenseXHR(t,s,i,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return n.call(this.hls,t,s,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return t.open("POST",s,!0),n.call(this.hls,t,s,i,r)}).then(a=>(t.readyState||t.open("POST",s,!0),{xhr:t,licenseChallenge:a||r})):(t.open("POST",s,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,s){const i=this.config.keyLoadPolicy.default;return new Promise((r,n)=>{const a=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return n(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const h=this.config.licenseResponseCallback;if(h)try{l=h.call(this.hls,o,a,t)}catch(c){this.error(c)}r(l)}else{const l=i.errorRetry,h=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>h||o.status>=400&&o.status<500)n(new Ae({type:$.KEY_SYSTEM_ERROR,details:L.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const c=h-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} attempts left`),this.requestLicense(t,s).then(r,n)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,a,t,s).then(({xhr:l,licenseChallenge:h})=>{t.keySystem==re.PLAYREADY&&(h=this.unpackPlayReadyKeyMessage(l,h)),l.send(h)}).catch(n)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,s){if(!this.config.emeEnabled)return;const i=s.media;this.media=i,ye(i,"encrypted",this.onMediaEncrypted),ye(i,"waitingforkey",this.onWaitingForKey);const r=this.mediaResolved;r?r():this.mediaKeys=i.mediaKeys}onMediaDetached(){const t=this.media;t&&(Te(t,"encrypted",this.onMediaEncrypted),Te(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const s=this.mediaResolved;if(s&&s(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,ds.clearKeyUriToKeyIdMap();const n=r.length;ts.CDMCleanupPromise=Promise.all(r.map(a=>this.removeSession(a)).concat((i==null||(t=i.setMediaKeys(null))==null?void 0:t.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(g.ERROR,{type:$.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(g.ERROR,{type:$.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{n&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:s}){if(!(!s||!this.config.emeEnabled)&&!this.keyFormatPromise){const i=s.reduce((r,n)=>(r.indexOf(n.keyFormat)===-1&&r.push(n.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(t){const{mediaKeysSession:s,licenseXhr:i,decryptdata:r}=t;if(s){this.log(`Remove licenses and keys and close session "${s.sessionId}" keyId: ${fe(r?.keyId||[])}`),t._onmessage&&(s.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(s.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const n=this.mediaKeySessions.indexOf(t);n>-1&&this.mediaKeySessions.splice(n,1);const{keyStatusTimeouts:a}=t;a&&Object.keys(a).forEach(l=>self.clearTimeout(a[l]));const{drmSystemOptions:o}=this.config;return(il(o)?new Promise((l,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),s.remove().then(l).catch(h)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(g.ERROR,{type:$.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>s.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(g.ERROR,{type:$.OTHER_ERROR,details:L.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}};Ea.CDMCleanupPromise=void 0;function Kt(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return fe(e.keyId)}function Sc(e,t){if(e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId))return t.mediaKeysSession.keyStatuses.get(e.keyId);if(e.matches(t.decryptdata))return t.keyStatus}var Ae=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}};function xr(e,t){const s=e==="output-restricted",i=s?L.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:L.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ae({type:$.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},s?"HDCP level output restricted":`key status changed to "${e}"`)}var Ac=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(g.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(g.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,n=s-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*n/r,l=this.hls;if(l.trigger(g.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:s}),o>0&&n>l.config.fpsDroppedMonitoringThreshold*a){let h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=h)&&(h=h-1,l.trigger(g.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}};function ya(e,t){let s;try{s=new Event("addtrack")}catch{s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=e,t.dispatchEvent(s)}function va(e,t){const s=e.mode;if(s==="disabled"&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(i){ee.debug(`[texttrack-utils]: ${i}`);try{const r=new self.TextTrackCue(t.startTime,t.endTime,t.text);r.id=t.id,e.addCue(r)}catch(r){ee.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${r}`)}}s==="disabled"&&(e.mode=s)}function dt(e,t){const s=e.mode;if(s==="disabled"&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);s==="disabled"&&(e.mode=s)}function ai(e,t,s,i){const r=e.mode;if(r==="disabled"&&(e.mode="hidden"),e.cues&&e.cues.length>0){const n=Lc(e.cues,t,s);for(let a=0;a<n.length;a++)(!i||i(n[a]))&&e.removeCue(n[a])}r==="disabled"&&(e.mode=r)}function Ic(e,t){if(t<=e[0].startTime)return 0;const s=e.length-1;if(t>e[s].endTime)return-1;let i=0,r=s,n;for(;i<=r;)if(n=Math.floor((r+i)/2),t<e[n].startTime)r=n-1;else if(t>e[n].startTime&&i<s)i=n+1;else return n;return e[i].startTime-t<t-e[r].startTime?i:r}function Lc(e,t,s){const i=[],r=Ic(e,t);if(r>-1)for(let n=r,a=e.length;n<a;n++){const o=e[n];if(o.startTime>=t&&o.endTime<=s)i.push(o);else if(o.startTime>s)return i}return i}function ss(e){const t=[];for(let s=0;s<e.length;s++){const i=e[s];(i.kind==="subtitles"||i.kind==="captions")&&i.label&&t.push(e[s])}return t}var Rc=class extends _i{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=ss(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(g.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVEL_LOADING,this.onLevelLoading,this),e.off(g.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(g.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!i&&ss(s.textTracks).forEach(r=>{dt(r)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const a=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,a)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(n=>i?.indexOf(n)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(h=>h.default)&&(this.selectDefaultTrack=!1),n.forEach((h,c)=>{h.id=c});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const a=this.hls.config.subtitlePreference;if(!r&&a){this.selectDefaultTrack=!1;const h=Ne(a,n);if(h>-1)r=n[h];else{const c=Ne(a,this.tracks);r=this.tracks[c]}}let o=this.findTrackId(r);o===-1&&r&&(o=this.findTrackId(null));const l={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(g.SUBTITLE_TRACKS_UPDATED,l),o!==-1&&this.trackId===-1&&this.setSubtitleTrack(o)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||et(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(Mt(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(Mt(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(ti(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===X.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&et(e,s))return s;const i=Ne(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=Ne(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,a=n?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(g.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=ss(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>ti(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!N(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(g.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:a="",name:o,type:l,url:h}=i;this.hls.trigger(g.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:l,url:h});const c=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(c)}};function bc(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),s=t.toString();return URL.revokeObjectURL(t),s.slice(s.lastIndexOf("/")+1)}catch{let s=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const r=(s+Math.random()*16)%16|0;return s=Math.floor(s/16),(i=="x"?r:r&3|8).toString(16)})}}}function bt(e){let t=5381,s=e.length;for(;s;)t=t*33^e.charCodeAt(--s);return(t>>>0).toString()}var mt=.025,ms=(function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e})({});function Dc(e,t,s){return`${e.identifier}-${s+1}-${bt(t)}`}var _c=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Ms(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-Ms(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=N(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Ms(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<mt))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?ms.Range:ms.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return Pc(this)}};function Ms(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<mt)?t.start:t.start+t.duration}function Ta(e,t,s){const i=new self.URL(e,s);return i.protocol!=="data:"&&i.searchParams.set("_HLS_primary_id",t),i}function Os(e,t){for(;(s=e.assetList[++t])!=null&&s.error;)var s;return t}function Pc(e){return`["${e.identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function ct(e){const t=e.timelineStart,s=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+s).toFixed(2)}]`}var Cc=class{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(g.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(g.LEVEL_LOADED,n),r.once(g.AUDIO_TRACK_LOADED,n),r.once(g.SUBTITLE_TRACK_LOADED,n),r.on(g.MEDIA_ATTACHING,(a,{media:o})=>{this.removeMediaListeners(),this.mediaAttached=o,this.interstitial.playoutLimit&&(o.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(g.BUFFER_APPENDED,()=>{const l=this.bufferedEnd;this.reachedPlayout(l)&&(this._bufferedEosTime=l,r.trigger(g.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Ta(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=j.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=j.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${ct(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},Fr=.033,kc=class extends _e{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const n=s[r];if(!n.error){const a=n.timelineStart;if(t===a||t>a&&(t<a+(n.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},t),a=Object.keys(i),o=r?r.filter(l=>!a.includes(l.identifier)):[];n.length&&n.sort((l,h)=>{const c=l.cue.pre,u=l.cue.post,d=h.cue.pre,f=h.cue.post;if(c&&!d)return-1;if(d&&!c||u&&!f)return 1;if(f&&!u)return-1;if(!c&&!d&&!u&&!f){const m=l.startTime,p=h.startTime;if(m!==p)return m-p}return l.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=n,o.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,o)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(i,e);(s||t.length||r?.length!==n.length||n.some((a,o)=>Math.abs(a.playout.start-r[o].playout.start)>.005||Math.abs(a.playout.end-r[o].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const a=r[n],o=e[a];if(o.isInterstitial){let l=this.eventMap[a];l?l.setDateRange(o):(l=new _c(o,t),this.eventMap[a]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let n=0;if(e=e.filter(o=>!o.error&&!(o.cue.once&&o.hasPlayed)),e.length){this.resolveOffsets(e,t);let o=0,l=0;if(e.forEach((h,c)=>{const u=h.cue.pre,d=h.cue.post,f=e[c-1]||null,m=h.appendInPlace,p=d?r:h.startOffset,E=h.duration,y=h.timelineOccupancy===ms.Range?E:0,T=h.resumptionOffset,v=f?.startTime===p,S=p+h.cumulativeDuration;let R=m?S+E:p+T;if(u||!d&&p<=0){const I=l;l+=y,h.timelineStart=S;const D=n;n+=E,s.push({event:h,start:S,end:R,playout:{start:D,end:n},integrated:{start:I,end:l}})}else if(p<=r){if(!v){const P=p-o;if(P>Fr){const _=o,M=l;l+=P;const B=n;n+=P;const x={previousEvent:e[c-1]||null,nextEvent:h,start:_,end:_+P,playout:{start:B,end:n},integrated:{start:M,end:l}};s.push(x)}else P>0&&f&&(f.cumulativeDuration+=P,s[s.length-1].end=p)}d&&(R=S),h.timelineStart=S;const I=l;l+=y;const D=n;n+=E,s.push({event:h,start:S,end:R,playout:{start:D,end:n},integrated:{start:I,end:l}})}else return;const A=h.resumeTime;d||A>r?o=r:o=A}),o<r){var a;const h=o,c=l,u=r-o;l+=u;const d=n;n+=u,s.push({previousEvent:((a=s[s.length-1])==null?void 0:a.event)||null,nextEvent:null,start:o,end:h+u,playout:{start:d,end:n},integrated:{start:c,end:l}})}this.setDurations(r,n,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((a,o)=>{const l=a.cue.pre,h=a.cue.post,c=l?0:h?i:a.startTime;this.updateAssetDurations(a),n===c?a.cumulativeDuration=r:(r=0,n=c),!h&&a.snapOptions.in&&(a.resumeAnchor=tt(null,s.fragments,a.startOffset+a.resumptionOffset,0,0)||void 0),a.appendInPlace&&!a.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(a,t)||(a.appendInPlace=!1)),!a.appendInPlace&&o+1<e.length&&e[o+1].startTime-e[o].resumeTime<Fr&&(e[o+1].appendInPlace=!1,e[o+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${a}`));const u=N(a.resumeOffset)?a.resumeOffset:a.duration;r+=u})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>mt?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(r=>{const n=t[r].details,a=n.edge;if(s>=a)return this.log(`"${e.identifier}" resumption ${s} past ${r} playlist end ${a}`),!1;const o=tt(null,n.fragments,s);if(!o)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${r} playlist (${n.fragStart}-${n.fragmentEnd})`),!0;const l=r==="audio"?.175:0;return Math.abs(o.start-s)<mt+l||Math.abs(o.end-s)<mt+l?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${r} fragment bounds (${o.start}-${o.end} sn: ${o.sn} cc: ${o.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const a=e.assetList[n],o=t+s;a.startOffset=s,a.timelineStart=o,i||(i=a.duration===null),r||(r=!!a.error);const l=a.error?0:a.duration||0;s+=l}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Ce(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}var wc=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Ta(s,this.hls.sessionId,e.baseUrl)}catch(c){const u=this.assignAssetListError(e,L.ASSET_LIST_LOAD_ERROR,c,s);this.hls.trigger(g.ERROR,u);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=r.loader,a=new n(r),o={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return a.load(o,h,{onSuccess:(c,u,d,f)=>{const m=c.data,p=m?.ASSETS;if(!Array.isArray(p)){const E=this.assignAssetListError(e,L.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),d.url,u,f);this.hls.trigger(g.ERROR,E);return}e.assetListResponse=m,this.hls.trigger(g.ASSET_LIST_LOADED,{event:e,assetListResponse:m,networkDetails:f})},onError:(c,u,d,f)=>{const m=this.assignAssetListError(e,L.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${c.code} ${c.text} (${u.url})`),u.url,f,d);this.hls.trigger(g.ERROR,m)},onTimeout:(c,u,d)=>{const f=this.assignAssetListError(e,L.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${u.url})`),u.url,c,d);this.hls.trigger(g.ERROR,f)}}),this.hls.trigger(g.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:$.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}};function Nr(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function lt(e,t){return`[${e}] Advancing timeline position to ${t}`}var Mc=class extends _e{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const r=i<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=s,this.bufferedPos=s;const n=this.playingItem;if(!n){this.checkBuffer();return}if(r&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),r&&s<n.start||s>=n.end){var a;const u=this.findItemIndex(n);let d=this.schedule.findItemIndexAtTime(s);if(d===-1&&(d=u+(r?-1:1),this.log(`seeked ${r?"back ":""}to position not covered by schedule ${s} (resolving from ${u} to ${d})`)),!this.isInterstitial(n)&&(a=this.media)!=null&&a.paused&&(this.shouldPlay=!1),!r&&d>u){const f=this.schedule.findJumpRestrictedIndex(u+1,d);if(f>u){this.setSchedulePosition(f);return}}this.setSchedulePosition(d);return}const o=this.playingAsset;if(!o){if(this.playingLastItem&&this.isInterstitial(n)){const u=n.event.assetList[0];u&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,u))}return}const l=o.timelineStart,h=o.duration||0;if(r&&s<l||s>=l+h){var c;(c=n.event)!=null&&c.appendInPlace&&(this.clearAssetPlayers(n.event,n),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,o)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const n=this.findItemIndex(i);this.setSchedulePosition(n+1)}const r=this.playingAsset;r&&s>=r.timelineStart+(r.duration||0)&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,a=r.events||[],o=r.items||[],l=r.durations,h=s.map(m=>m.identifier),c=!!(a.length||h.length);(c||i)&&this.log(`INTERSTITIALS_UPDATED (${a.length}): ${a}
Schedule: ${o.map(m=>Ce(m))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let u=null,d=null;n&&(u=this.updateItem(n,this.timelinePos),this.itemsMatch(n,u)?this.playingItem=u:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const f=this.bufferingItem;if(f&&(d=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,d)?this.bufferingItem=d:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),s.forEach(m=>{m.assetList.forEach(p=>{this.clearAssetPlayer(p.identifier,null)})}),this.playerQueue.forEach(m=>{if(m.interstitial.appendInPlace){const p=m.assetItem.timelineStart,E=m.timelineOffset-p;if(E)try{m.timelineOffset=p}catch(y){Math.abs(E)>mt&&this.warn(`${y} ("${m.assetId}" ${m.timelineOffset}->${p})`)}}}),c||i){if(this.hls.trigger(g.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:o.slice(0),durations:l,removedIds:h}),this.isInterstitial(n)&&h.includes(n.event.identifier)){this.warn(`Interstitial "${n.event.identifier}" removed while playing`),this.primaryFallback(n.event);return}n&&this.trimInPlace(u,n),f&&d!==u&&this.trimInPlace(d,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new wc(e),this.schedule=new kc(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(g.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(g.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(g.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(g.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(g.BUFFER_APPENDED,this.onBufferAppended,this),e.on(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(g.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(g.MEDIA_ENDED,this.onMediaEnded,this),e.on(g.ERROR,this.onError,this),e.on(g.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(g.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(g.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(g.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(g.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(g.BUFFER_CODECS,this.onBufferCodecs,this),e.off(g.BUFFER_APPENDED,this.onBufferAppended,this),e.off(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(g.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(g.MEDIA_ENDED,this.onMediaEnded,this),e.off(g.ERROR,this.onError,this),e.off(g.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Te(e,"play",this.onPlay),Te(e,"pause",this.onPause),Te(e,"seeking",this.onSeeking),Te(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;ye(s,"seeking",this.onSeeking),ye(s,"timeupdate",this.onTimeupdate),ye(s,"play",this.onPlay),ye(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=c=>c&&e.getAssetPlayer(c.identifier),i=(c,u,d,f,m)=>{if(c){let p=c[u].start;const E=c.event;if(E){if(u==="playout"||E.timelineOccupancy!==ms.Point){const y=s(d);y?.interstitial===E&&(p+=y.assetItem.startOffset+y[m])}}else{const y=f==="bufferedPos"?n():e[f];p+=y-c.start}return p}return 0},r=(c,u)=>{var d;if(c!==0&&u!=="primary"&&(d=e.schedule)!=null&&d.length){var f;const m=e.schedule.findItemIndexAtTime(c),p=(f=e.schedule.items)==null?void 0:f[m];if(p)return c+(p[u].start-p.start)}return c},n=()=>{const c=e.bufferedPos;return c===Number.MAX_VALUE?a("primary"):Math.max(c,0)},a=c=>{var u,d;return(u=e.primaryDetails)!=null&&u.live?e.primaryDetails.edge:((d=e.schedule)==null?void 0:d.durations[c])||0},o=(c,u)=>{var d,f;const m=e.effectivePlayingItem;if(m!=null&&(d=m.event)!=null&&d.restrictions.skip||!e.schedule)return;e.log(`seek to ${c} "${u}"`);const p=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(c,u),y=(f=e.schedule.items)==null?void 0:f[E],T=e.getBufferingPlayer(),v=T?.interstitial,S=v?.appendInPlace,R=p&&e.itemsMatch(p,y);if(p&&(S||R)){const A=s(e.playingAsset),I=A?.media||e.primaryMedia;if(I){const D=u==="primary"?I.currentTime:i(p,u,e.playingAsset,"timelinePos","currentTime"),P=c-D,_=(S?D:I.currentTime)+P;if(_>=0&&(!A||S||_<=A.duration)){I.currentTime=_;return}}}if(y){let A=c;if(u!=="primary"){const D=c-y[u].start;A=y.start+D}const I=!e.isInterstitial(y);if((!e.isInterstitial(p)||p.event.appendInPlace)&&(I||y.event.appendInPlace)){const D=e.media||(S?T?.media:null);D&&(D.currentTime=A)}else if(p){const D=e.findItemIndex(p);if(E>D){const _=e.schedule.findJumpRestrictedIndex(D+1,E);if(_>D){e.setSchedulePosition(_);return}}let P=0;if(I)e.timelinePos=A,e.checkBuffer();else{const _=y.event.assetList,M=c-(y[u]||y).start;for(let B=_.length;B--;){const x=_[B];if(x.duration&&M>=x.startOffset&&M<x.startOffset+x.duration){P=B;break}}}e.setSchedulePosition(E,P)}}},l=()=>{const c=e.effectivePlayingItem;if(e.isInterstitial(c))return c;const u=t();return e.isInterstitial(u)?u:null},h={get bufferedEnd(){const c=t(),u=e.bufferingItem;if(u&&u===c){var d;return i(u,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-u.playout.start||((d=e.bufferingAsset)==null?void 0:d.startOffset)||0}return 0},get currentTime(){const c=l(),u=e.effectivePlayingItem;return u&&u===c?i(u,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-u.playout.start:0},set currentTime(c){const u=l(),d=e.effectivePlayingItem;d&&d===u&&o(c+d.playout.start,"playout")},get duration(){const c=l();return c?c.playout.end-c.playout.start:0},get assetPlayers(){var c;const u=(c=l())==null?void 0:c.event.assetList;return u?u.map(d=>e.getAssetPlayer(d.identifier)):[]},get playingIndex(){var c;const u=(c=l())==null?void 0:c.event;return u&&e.effectivePlayingAsset?u.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var c;return((c=e.schedule)==null||(c=c.events)==null?void 0:c.slice(0))||[]},get schedule(){var c;return((c=e.schedule)==null||(c=c.items)==null?void 0:c.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const c=t();return e.findItemIndex(c)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const c=e.effectivePlayingItem;return e.findItemIndex(c)},primary:{get bufferedEnd(){return n()},get currentTime(){const c=e.timelinePos;return c>0?c:0},set currentTime(c){o(c,"primary")},get duration(){return a("primary")},get seekableStart(){var c;return((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(c){o(c,"integrated")},get duration(){return a("integrated")},get seekableStart(){var c;return r(((c=e.primaryDetails)==null?void 0:c.fragmentStart)||0,"integrated")}},skip:()=>{const c=e.effectivePlayingItem,u=c?.event;if(u&&!u.restrictions.skip){const d=e.findItemIndex(c);if(u.appendInPlace){const f=c.playout.start+c.event.duration;o(f+.001,"playout")}else e.advanceAfterAssetEnded(u,d,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!N(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ie(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const n=this.hls,a=e!==n,o=a&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource;let h;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const f=this.getBufferingPlayer();f?(r=f.transferMedia(),h=`${f}`):h="detached MediaSource"}else h="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ie(r)}`);else if(!this.detachedData||n.media===t){const f=this.playerQueue;f.length>1&&f.forEach(m=>{if(a&&m.interstitial.appendInPlace!==o){const p=m.interstitial;this.clearInterstitial(m.interstitial,null),p.appendInPlace=!1,p.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${p}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const c=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",u=c&&r?r:t;this.log(`${c?"transfering MediaSource":"attaching media"} to ${a?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const d=this.schedule;if(u===r&&d){const f=a&&e.assetId===d.assetIdAtEnd;u.overrides={duration:d.duration,endOfStream:!a||f,cueRemoval:!a}}e.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){const r=this.hls.startPosition;if(this.timelinePos=r,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(lt("checkStart (preroll)",r));const n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){this.log(lt("checkStart",r));const n=this.timelinePos=r>0?r:0,a=e.findItemIndexAtTime(n);this.setSchedulePosition(a)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(i&&!this.playingItem){this.log(lt("checkStart (playing item)",i.start));const r=e.findItemIndex(i);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const s=e.event,i=Os(s,s.findAssetIndex(t));if(!s.isAssetPastPlayoutLimit(i))this.bufferedToEvent(e,i);else if(this.schedule){var r;const n=(r=this.schedule.items)==null?void 0:r[this.findItemIndex(e)+1];n&&this.bufferedToItem(n)}}advanceAfterAssetEnded(e,t,s){const i=Os(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const r=this.schedule.items;if(r){const n=t+1;if(n>=r.length){this.setSchedulePosition(-1);return}const a=e.resumeTime;this.timelinePos<a&&(this.log(lt("advanceAfterAssetEnded",a)),this.timelinePos=a,e.appendInPlace&&this.advanceInPlace(a),this.checkBuffer(this.bufferedPos<a)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){const r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const n=s.findEventIndex(i),a=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,n,a-1)}}setSchedulePosition(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Ce(r)}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(n)){const h=n.event,c=this.playingAsset,u=c?.identifier,d=u?this.getAssetPlayer(u):null;if(d&&u&&(!this.eventItemsMatch(n,r)||t!==void 0&&u!==h.assetList[t].identifier)){var o;const f=h.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${f+1}/${h.assetList.length} ${ct(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(g.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:f,event:h,schedule:i.slice(0),scheduleIndex:e,player:d}),n!==this.playingItem){this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),f);return}this.retreiveMediaSource(u,r),d.media&&!((o=this.detachedData)!=null&&o.mediaSource)&&d.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${Ce(n)}`),h.hasPlayed=!0,this.hls.trigger(g.INTERSTITIAL_ENDED,{event:h,schedule:i.slice(0),scheduleIndex:e}),h.cue.once)){var l;this.updateSchedule();const f=(l=this.schedule)==null?void 0:l.items;if(r&&f){const m=this.findItemIndex(r);this.advanceSchedule(m,f,t,n,a)}return}}this.advanceSchedule(e,i,t,n,a)}advanceSchedule(e,t,s,i,r){const n=this.schedule;if(!n)return;const a=t[e]||null,o=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(h=>{const c=h.interstitial,u=n.findEventIndex(c.identifier);(u<e||u>e+1)&&this.clearInterstitial(c,a)}),this.isInterstitial(a)){this.timelinePos=Math.min(Math.max(this.timelinePos,a.start),a.end);const h=a.event;if(s===void 0){s=n.findAssetIndex(h,this.timelinePos);const f=Os(h,s-1);if(h.isAssetPastPlayoutLimit(f)||h.appendInPlace&&this.timelinePos===a.end){this.advanceAfterAssetEnded(h,e,s);return}s=f}const c=this.waitingItem;this.assetsBuffered(a,o)||this.setBufferingItem(a);let u=this.preloadAssets(h,s);if(this.eventItemsMatch(a,c||i)||(this.waitingItem=a,this.log(`INTERSTITIAL_STARTED ${Ce(a)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(g.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!o){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=a;const d=h.assetList[s];if(!d){this.advanceAfterAssetEnded(h,e,s||0);return}if(u||(u=this.getAssetPlayer(d.identifier)),u===null||u.destroyed){const f=h.assetList.length;this.warn(`asset ${s+1}/${f} player destroyed ${h}`),u=this.createAssetPlayer(h,d,s),u.loadSource()}if(!this.eventItemsMatch(a,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(d))return;this.startAssetPlayer(u,s,t,e,o),this.shouldPlay&&Nr(u.media)}else a?(this.resumePrimary(a,e,i),this.shouldPlay&&Nr(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var i,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Ce(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let a=this.timelinePos;(a<e.start||a>=e.end)&&(a=this.getPrimaryResumption(e,t),this.log(lt("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)}if(!s)return;const n=(r=this.schedule)==null?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ce(e)}`),this.hls.trigger(g.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:j.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(lt("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(g.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(g.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const i=J(J({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=J(J({},this.altSelection),{},{audio:s});return}const r=J(J({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=J(J({},this.altSelection),{},{subtitles:s});return}const r=J(J({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=Wi(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Wi(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const r=t[i];if(r.cue.post){var s;const n=this.schedule.findEventIndex(r.identifier),a=(s=this.schedule.items)==null?void 0:s[n];this.isInterstitial(a)&&this.eventItemsMatch(a,this.bufferingItem)&&this.bufferedToItem(a,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;return e&&i&&i[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(r.identifier,null)});const s=e.end+.25,i=j.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Ce(e)} (was ${Ce(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const i=j.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const n=this.playingItem,a=this.findItemIndex(n);let o=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const h=this.findItemIndex(r),c=Math.min(h+1,t.length-1),u=t[c];if((o===-1&&r&&e>=r.end||(l=u.event)!=null&&l.appendInPlace&&e+.01>=u.start)&&(o=c),this.isInterstitial(r)){const d=r.event;if(c-a>1&&d.appendInPlace===!1||d.assetList.length===0&&d.assetListLoader)return}if(this.bufferedPos=e,o>h&&o>a)this.bufferedToItem(u);else{const d=this.primaryDetails;this.primaryLive&&d&&e>d.edge-d.targetduration&&u.start<d.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(u)&&this.preloadAssets(u.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(t[o]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(s=>{const i=this.getAssetPlayer(s.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const n=this.isInterstitial(e),a=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const o=a?a.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ce(e)}`+(t?` (${o.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,c)=>{const u=this.getAssetPlayer(h.identifier);u&&(c===l&&u.loadSource(),u.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(g.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const n=this.preloadAssets(s,t);if(n!=null&&n.interstitial.appendInPlace){const a=this.primaryMedia;a&&this.bufferAssetPlayer(n,a)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,n=e.cue.once;if(r){const o=e.timelineStart;if(e.appendInPlace){var a;const u=this.playingItem;!this.isInterstitial(u)&&(u==null||(a=u.nextEvent)==null?void 0:a.identifier)===e.identifier&&this.flushFrontBuffer(o+.25)}let l,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){const u=h-o;u>0&&(l=Math.round(u*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${h} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,o,e.duration,s);const c=this.assetListLoader.loadAssetList(e,l);c&&(e.assetListLoader=c)}else if(!n&&i){for(let l=t;l<i;l++){const h=e.assetList[l],c=this.getAssetPlayerQueueIndex(h.identifier);(c===-1||this.playerQueue[c].destroyed)&&!h.error&&this.createAssetPlayer(e,h,l)}const o=e.assetList[t];if(o){const l=this.getAssetPlayer(o.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;t&&(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(s=>{this.hls.trigger(g.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:s})}))}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,n){const a={parentIdentifier:e.identifier,identifier:Dc(e,n,t),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(e,a,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig;let n=r.videoPreference;const a=i.loadLevelObj||i.levels[i.currentLevel];(n||a)&&(n=te({},n),a.videoCodec&&(n.videoCodec=a.videoCodec),a.videoRange&&(n.allowedVideoRanges=[a.videoRange]));const o=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const v=this.timelinePos-t.timelineStart;if(v>1){const S=t.duration;S&&v<S&&(h=v)}}const c=t.identifier,u=J(J({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:c,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:o||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(u.timelineOffset=t.timelineStart));const d=u.cmcd;d!=null&&d.sessionId&&d.contentId&&(u.cmcd=te({},d,{contentId:bt(t.uri)})),this.getAssetPlayer(c)&&this.warn(`Duplicate date range identifier ${e} and asset ${c}`);const f=new Cc(this.HlsPlayerClass,u,e,t);this.playerQueue.push(f),e.assetList[s]=t;let m=!0;const p=v=>{if(v.live){var S;const I=new Error(`Interstitials MUST be VOD assets ${e}`),D={fatal:!0,type:$.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},P=((S=this.schedule)==null?void 0:S.findEventIndex(e.identifier))||-1;this.handleAssetItemError(D,e,P,s,I.message);return}const R=v.edge-v.fragmentStart,A=t.duration;(m||A===null||R>A)&&(m=!1,this.log(`Interstitial asset "${c}" duration change ${A} > ${R}`),t.duration=R,this.updateSchedule())};f.on(g.LEVEL_UPDATED,(v,{details:S})=>p(S)),f.on(g.LEVEL_PTS_UPDATED,(v,{details:S})=>p(S)),f.on(g.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const E=(v,S)=>{const R=this.getAssetPlayer(c);if(R&&S.tracks){R.off(g.BUFFER_CODECS,E),R.tracks=S.tracks;const A=this.primaryMedia;this.bufferingAsset===R.assetItem&&A&&!R.media&&this.bufferAssetPlayer(R,A)}};f.on(g.BUFFER_CODECS,E);const y=()=>{var v;const S=this.getAssetPlayer(c);if(this.log(`buffered to end of asset ${S}`),!S||!this.schedule)return;const R=this.schedule.findEventIndex(e.identifier),A=(v=this.schedule.items)==null?void 0:v[R];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};f.on(g.BUFFERED_TO_END,y);const T=v=>()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;this.shouldPlay=!0;const S=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,S,v)};return f.once(g.MEDIA_ENDED,T(s)),f.once(g.PLAYOUT_LIMIT_REACHED,T(1/0)),f.on(g.ERROR,(v,S)=>{if(!this.schedule)return;const R=this.getAssetPlayer(c);if(S.details===L.BUFFER_STALLED_ERROR){if(R!=null&&R.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(S,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${S.error} ${e}`)}),f.on(g.DESTROYING,()=>{if(!this.getAssetPlayer(c)||!this.schedule)return;const v=new Error(`Asset player destroyed unexpectedly ${c}`),S={fatal:!0,type:$.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:v};this.handleAssetItemError(S,e,this.schedule.findEventIndex(e.identifier),s,v.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ct(t)}`),this.hls.trigger(g.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&Ce(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:n,assetItem:a,assetId:o}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=a,(!h||h.identifier!==o)&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${ct(a)}`),this.hls.trigger(g.INTERSTITIAL_ASSET_STARTED,{asset:a,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,a=this.schedule.findEventIndex(r.identifier),o=(s=this.schedule.items)==null?void 0:s[a];if(!o)return;e.loadSource(),this.setBufferingItem(o),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const h=r.appendInPlace;if(h&&l?.interstitial.appendInPlace===!1)return;const c=l?.tracks||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!Qr(c,e.tracks)){const u=new Error(`Asset ${ct(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),d={fatal:!0,type:$.OTHER_ERROR,details:L.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},f=r.findAssetIndex(n);this.handleAssetItemError(d,r,a,f,u.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),n=e.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||i-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${e} (media.currentTime: ${i})`),o&&(l/s.playbackRate<.5||a.bufferedInPlaceToEnd(s))&&a.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===L.BUFFER_STALLED_ERROR)return;const n=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n&&ct(n)} ${e.error}`),!this.schedule)return;const a=n?.identifier||"",o=this.getAssetPlayerQueueIndex(a),l=this.playerQueue[o]||null,h=this.schedule.items,c=te({},e,{fatal:!1,errorAction:ft(!0),asset:n,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(g.INTERSTITIAL_ASSET_ERROR,c),!e.fatal)return;const u=this.playingAsset,d=this.bufferingAsset,f=new Error(r);if(n&&(this.clearAssetPlayer(a,null),n.error=f),!t.assetList.some(m=>!m.error))t.error=f;else for(let m=i;m<t.assetList.length;m++)this.resetAssetPlayer(t.assetList[m].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):u&&u.identifier===a?this.advanceAfterAssetEnded(t,s,i):d&&d.identifier===a&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,d)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${Ce(s)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);const n=this.updateItem(s,i);this.itemsMatch(s,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var s,i;const r=t.event,n=r.identifier,a=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(n)))return;const o=r.timelineStart,l=r.duration;let h=0;a.forEach((m,p)=>{const E=parseFloat(m.DURATION);this.createAsset(r,p,h,o+h,E,m.URI),h+=E}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const c=this.waitingItem,u=c?.event.identifier===n;this.updateSchedule();const d=(i=this.bufferingItem)==null?void 0:i.event;if(u){var f;const m=this.schedule.findEventIndex(n),p=(f=this.schedule.items)==null?void 0:f[m];if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==m){r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(p)}this.setSchedulePosition(m)}else if(d?.identifier===n){const m=r.assetList[0];if(m){const p=this.getAssetPlayer(m.identifier);if(d.appendInPlace){const E=this.primaryMedia;p&&E&&this.bufferAssetPlayer(p,E)}else p&&p.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case L.ASSET_LIST_PARSING_ERROR:case L.ASSET_LIST_LOAD_ERROR:case L.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case L.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},Br=500,Oc=class extends Ti{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",U.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(g.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(g.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(g.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(g.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=C.IDLE,this.setInterval(Br),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(this.fragContextChanged(s)||(oe(s)&&(this.fragPrevious=s),this.state=C.IDLE),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const a=s.start;for(let l=0;l<r.length;l++)if(a>=r[l].start&&a<=r[l].end){n=r[l];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(n=>{for(let a=0;a<n.length;){if(n[a].end<=r){n.shift();continue}else if(n[a].start<r)n[a].start=r;else break;a++}}),this.fragmentTracker.removeFragmentsInRange(s,r,U.SUBTITLE)}}onError(e,t){const s=t.frag;s?.type===U.SUBTITLE&&(t.details===L.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==C.STOPPED&&(this.state=C.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&ia(this.levels,t)){this.levels=t.map(s=>new Pt(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new Pt(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,U.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==C.STOPPED&&this.setInterval(Br)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:a}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${a}`);return}const o=r[a];if(a>=r.length||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||(s=o.details)!=null&&s.live){if(n.deltaUpdateFailed)return;const c=this.mainDetails;if(!c){this.startFragRequested=!1;return}const u=c.fragments[0];if(!o.details)n.hasProgramDateTime&&c.hasProgramDateTime?(fs(n,c),l=n.fragmentStart):u&&(l=u.start,Zs(n,l));else{var h;l=this.alignPlaylists(n,o.details,(h=this.levelLastLoaded)==null?void 0:h.details),l===0&&u&&(l=u.start,Zs(n,l))}c&&!this.startFragRequested&&this.setStartPosition(c,l)}o.details=n,this.levelLastLoaded=o,a===i&&(this.hls.trigger(g.SUBTITLE_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===C.IDLE&&(tt(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&>(i.method)){const n=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,yi(i.method)).catch(a=>{throw r.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t}),a}).then(a=>{const o=performance.now();r.trigger(g.FRAG_DECRYPTED,{frag:t,payload:a,stats:{tstart:n,tdecrypt:o}})}).catch(a=>{this.warn(`${a.name}: ${a.message}`),this.state=C.IDLE})}}doTick(){if(!this.media){this.state=C.IDLE;return}if(this.state===C.IDLE){const{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),{end:n,len:a}=j.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),o=s.details;if(a>this.hls.maxBufferLength+o.levelTargetDuration)return;const l=o.fragments,h=l.length,c=o.edge;let u=null;const d=this.fragPrevious;if(n<c){const m=i.maxFragLookUpTolerance,p=n>c-m?0:m;u=tt(d,l,Math.max(l[0].start,n),p),!u&&d&&d.start<l[0].start&&(u=l[0])}else u=l[h-1];if(u=this.filterReplacedPrimary(u,s.details),!u)return;const f=l[u.sn-o.startSN-1];if(f&&f.cc===u.cc&&this.fragmentTracker.getState(f)===he.NOT_LOADED&&(u=f),this.fragmentTracker.getState(u)===he.NOT_LOADED){const m=this.mapToInitFragWhenRequired(u);m&&this.loadFragment(m,s,n)}}}loadFragment(e,t,s){oe(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new xc(this.tracksBuffered[this.currentTrackId]||[])}},xc=class{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}},Fc={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Sa=e=>String.fromCharCode(Fc[e]||e),ze=15,$e=100,Nc={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Bc={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Uc={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},$c={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Gc=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Kc=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;ee.log(`${this.time} [${e}] ${s}`)}}},Qe=function(t){const s=[];for(let i=0;i<t.length;i++)s.push(t[i].toString(16));return s},Aa=class{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},Vc=class{constructor(){this.uchar=" ",this.penState=new Aa}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}},Hc=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Aa,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<$e;t++)this.chars.push(new Vc);this.logger=e}equals(e){for(let t=0;t<$e;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<$e;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<$e;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>$e&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=$e)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Sa(e);if(this.pos>=$e){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<$e;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<$e;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},xs=class{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<ze;t++)this.rows.push(new Hc(e));this.logger=e}reset(){for(let e=0;e<ze;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let s=0;s<ze;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<ze;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<ze;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ie(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let a=0;a<ze;a++)this.rows[a].clear();const r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const a=n.rows[r].cueStartTime,o=this.logger.time;if(a!==null&&o!==null&&a<o)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(n.rows[r+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,n=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[n].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ie(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<ze;r++){const n=this.rows[r].getTextString();n&&(i=r+1,e?t.push("Row "+i+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
`)),s}getTextAndFormat(){return this.rows}},Ur=class{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new xs(s),this.nonDisplayedMemory=new xs(s),this.lastOutputScreen=new xs(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};t.underline=e%2===1,t.italics=e>=46,t.italics?t.foreground="white":t.foreground=["white","green","blue","cyan","red","yellow","magenta"][Math.floor(e/2)-16],this.logger.log(2,"MIDROW: "+ie(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},$r=class{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Wc(),this.logger=void 0;const i=this.logger=new Kc;this.channels=[null,new Ur(e,t,i),new Ur(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let n=!1,a=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+Qe([t[s],t[s+1]])+"] -> ("+Qe([i,r])+")");const o=this.cmdHistory;if(i>=16&&i<=31){if(Yc(i,r,o)){Vt(null,null,o),this.logger.log(3,()=>"Repeated command ("+Qe([i,r])+") is dropped");continue}Vt(i,r,this.cmdHistory),n=this.parseCmd(i,r),n||(n=this.parseMidrow(i,r)),n||(n=this.parsePAC(i,r)),n||(n=this.parseBackgroundAttributes(i,r))}else Vt(null,null,o);if(!n&&(a=this.parseChars(i,r),a)){const l=this.currentChannel;l&&l>0?this.channels[l].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!a&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Qe([i,r])+" orig: "+Qe([t[s],t[s+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;const s=e===20||e===21||e===23?1:2,i=this.channels[s];return e===20||e===21||e===28||e===29?t===32?i.ccRCL():t===33?i.ccBS():t===34?i.ccAOF():t===35?i.ccAON():t===36?i.ccDER():t===37?i.ccRU(2):t===38?i.ccRU(3):t===39?i.ccRU(4):t===40?i.ccFON():t===41?i.ccRDC():t===42?i.ccTR():t===43?i.ccRTD():t===44?i.ccEDM():t===45?i.ccCR():t===46?i.ccENM():t===47&&i.ccEOC():i.ccTO(t-32),this.currentChannel=s,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Qe([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;const i=e<=23?1:2;t>=64&&t<=95?s=i===1?Nc[e]:Uc[e]:s=i===1?Bc[e]:$c[e];const r=this.channels[i];return r?(r.setPAC(this.interpretPAC(s,t)),this.currentChannel=i,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let n;r===17?n=t+80:r===18?n=t+112:n=t+144,this.logger.log(2,()=>"Special char '"+Sa(n)+"' in channel "+s),i=[n]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+Qe(i).join(",")),i}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let s;const i={};e===16||e===24?(s=Math.floor((t-32)/2),i.background=Gc[s],t%2===1&&(i.background=i.background+"_semi")):t===45?i.background="transparent":(i.foreground="black",t===47&&(i.underline=!0));const r=e<=23?1:2;return this.channels[r].setBkgData(i),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Vt(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}};function Vt(e,t,s){s.a=e,s.b=t}function Yc(e,t,s){return s.a===e&&s.b===t}function Wc(){return{a:null,b:null}}var ki=(function(){if(us!=null&&us.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function s(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const h=l.toLowerCase();return~o.indexOf(h)?h:!1}function i(o){return s(e,o)}function r(o){return s(t,o)}function n(o,...l){let h=1;for(;h<arguments.length;h++){const c=arguments[h];for(const u in c)o[u]=c[u]}return o}function a(o,l,h){const c=this,u={enumerable:!0};c.hasBeenReset=!1;let d="",f=!1,m=o,p=l,E=h,y=null,T="",v=!0,S="auto",R="start",A=50,I="middle",D=50,P="middle";Object.defineProperty(c,"id",n({},u,{get:function(){return d},set:function(_){d=""+_}})),Object.defineProperty(c,"pauseOnExit",n({},u,{get:function(){return f},set:function(_){f=!!_}})),Object.defineProperty(c,"startTime",n({},u,{get:function(){return m},set:function(_){if(typeof _!="number")throw new TypeError("Start time must be set to a number.");m=_,this.hasBeenReset=!0}})),Object.defineProperty(c,"endTime",n({},u,{get:function(){return p},set:function(_){if(typeof _!="number")throw new TypeError("End time must be set to a number.");p=_,this.hasBeenReset=!0}})),Object.defineProperty(c,"text",n({},u,{get:function(){return E},set:function(_){E=""+_,this.hasBeenReset=!0}})),Object.defineProperty(c,"region",n({},u,{get:function(){return y},set:function(_){y=_,this.hasBeenReset=!0}})),Object.defineProperty(c,"vertical",n({},u,{get:function(){return T},set:function(_){const M=i(_);if(M===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=M,this.hasBeenReset=!0}})),Object.defineProperty(c,"snapToLines",n({},u,{get:function(){return v},set:function(_){v=!!_,this.hasBeenReset=!0}})),Object.defineProperty(c,"line",n({},u,{get:function(){return S},set:function(_){if(typeof _!="number"&&_!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");S=_,this.hasBeenReset=!0}})),Object.defineProperty(c,"lineAlign",n({},u,{get:function(){return R},set:function(_){const M=r(_);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");R=M,this.hasBeenReset=!0}})),Object.defineProperty(c,"position",n({},u,{get:function(){return A},set:function(_){if(_<0||_>100)throw new Error("Position must be between 0 and 100.");A=_,this.hasBeenReset=!0}})),Object.defineProperty(c,"positionAlign",n({},u,{get:function(){return I},set:function(_){const M=r(_);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");I=M,this.hasBeenReset=!0}})),Object.defineProperty(c,"size",n({},u,{get:function(){return D},set:function(_){if(_<0||_>100)throw new Error("Size must be between 0 and 100.");D=_,this.hasBeenReset=!0}})),Object.defineProperty(c,"align",n({},u,{get:function(){return P},set:function(_){const M=r(_);if(!M)throw new SyntaxError("An invalid or illegal string was specified.");P=M,this.hasBeenReset=!0}})),c.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})(),qc=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function Ia(e){function t(i,r,n,a){return(i|0)*3600+(r|0)*60+(n|0)+parseFloat(a||0)}const s=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?t(s[2],s[3],0,s[4]):t(s[1],s[2],s[3],s[4]):null}var jc=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}};function La(e,t,s,i){const r=i?e.split(i):[e];for(const n in r){if(typeof r[n]!="string")continue;const a=r[n].split(s);if(a.length!==2)continue;const o=a[0],l=a[1];t(o,l)}}var oi=new ki(0,0,""),Ht=oi.align==="middle"?"middle":"center";function Xc(e,t,s){const i=e;function r(){const o=Ia(e);if(o===null)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),o}function n(o,l){const h=new jc;La(o,function(d,f){let m;switch(d){case"region":for(let p=s.length-1;p>=0;p--)if(s[p].id===f){h.set(d,s[p].region);break}break;case"vertical":h.alt(d,f,["rl","lr"]);break;case"line":m=f.split(","),h.integer(d,m[0]),h.percent(d,m[0])&&h.set("snapToLines",!1),h.alt(d,m[0],["auto"]),m.length===2&&h.alt("lineAlign",m[1],["start",Ht,"end"]);break;case"position":m=f.split(","),h.percent(d,m[0]),m.length===2&&h.alt("positionAlign",m[1],["start",Ht,"end","line-left","line-right","auto"]);break;case"size":h.percent(d,f);break;case"align":h.alt(d,f,["start",Ht,"end","left","right"])}},/:/,/\s/),l.region=h.get("region",null),l.vertical=h.get("vertical","");let c=h.get("line","auto");c==="auto"&&oi.line===-1&&(c=-1),l.line=c,l.lineAlign=h.get("lineAlign","start"),l.snapToLines=h.get("snapToLines",!0),l.size=h.get("size",100),l.align=h.get("align",Ht);let u=h.get("position","auto");u==="auto"&&oi.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=r(),a(),e.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+i);e=e.slice(3),a(),t.endTime=r(),a(),n(e,t)}function Ra(e){return e.replace(/<br(?: \/)?>/gi,`
`)}var zc=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new qc,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let r=t.buffer,n=0;for(r=Ra(r);n<r.length&&r[n]!=="\r"&&r[n]!==`
`;)++n;const a=r.slice(0,n);return r[n]==="\r"&&++n,r[n]===`
`&&++n,t.buffer=r.slice(n),a}function i(r){La(r,function(n,a){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const a=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(a!=null&&a[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new ki(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Xc(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const a=r.indexOf("-->")!==-1;if(!r||a&&(n=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},Qc=/\r\n|\n\r|\n|\r/g,Fs=function(t,s,i=0){return t.slice(i,i+s.length)===s},Zc=function(t){let s=parseInt(t.slice(-3));const i=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!N(s)||!N(i)||!N(r)||!N(n))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return s+=1e3*i,s+=6e4*r,s+=36e5*n,s};function wi(e,t,s){return bt(e.toString())+bt(t.toString())+bt(s)}var Jc=function(t,s,i){let r=t[s],n=t[r.prevCC];if(!n||!n.new&&r.new){t.ccOffset=t.presentationOffset=r.start,r.new=!1;return}for(;(a=n)!=null&&a.new;){var a;t.ccOffset+=r.start-n.start,r.new=!1,r=n,n=t[r.prevCC]}t.presentationOffset=i};function eu(e,t,s,i,r,n,a){const o=new zc,l=be(new Uint8Array(e)).trim().replace(Qc,`
`).split(`
`),h=[],c=t?oh(t.baseTime,t.timescale):0;let u="00:00.000",d=0,f=0,m,p=!0;o.oncue=function(E){const y=s[i];let T=s.ccOffset;const v=(d-c)/9e4;if(y!=null&&y.new&&(f!==void 0?T=s.ccOffset=y.start:Jc(s,i,v)),v){if(!t){m=new Error("Missing initPTS for VTT MPEGTS");return}T=v-s.presentationOffset}const S=E.endTime-E.startTime,R=Le((E.startTime+T-f)*9e4,r*9e4)/9e4;E.startTime=Math.max(R,0),E.endTime=Math.max(R+S,0);const A=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(A)),E.id||(E.id=wi(E.startTime,E.endTime,A)),E.endTime>0&&h.push(E)},o.onparsingerror=function(E){m=E},o.onflush=function(){if(m){a(m);return}n(h)},l.forEach(E=>{if(p)if(Fs(E,"X-TIMESTAMP-MAP=")){p=!1,E.slice(16).split(",").forEach(y=>{Fs(y,"LOCAL:")?u=y.slice(6):Fs(y,"MPEGTS:")&&(d=parseInt(y.slice(7)))});try{f=Zc(u)/1e3}catch(y){m=y}return}else E===""&&(p=!1);o.parse(E+`
`)}),o.flush()}var Ns="stpp.ttml.im1t",ba=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Da=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,tu={left:"start",center:"center",right:"end",start:"start",end:"end"};function Gr(e,t,s,i){const r=q(new Uint8Array(e),["mdat"]);if(r.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=r.map(o=>be(o)),a=ah(t.baseTime,1,t.timescale);try{n.forEach(o=>s(su(o,a)))}catch(o){i(o)}}function su(e,t){const s=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},r=Object.keys(i).reduce((h,c)=>(h[c]=s.getAttribute(`ttp:${c}`)||i[c],h),{}),n=s.getAttribute("xml:space")!=="preserve",a=Kr(Bs(s,"styling","style")),o=Kr(Bs(s,"layout","region")),l=Bs(s,"body","[begin]");return[].map.call(l,h=>{const c=_a(h,n);if(!c||!h.hasAttribute("begin"))return null;const u=$s(h.getAttribute("begin"),r),d=$s(h.getAttribute("dur"),r);let f=$s(h.getAttribute("end"),r);if(u===null)throw Vr(h);if(f===null){if(d===null)throw Vr(h);f=u+d}const m=new ki(u-t,f-t,c);m.id=wi(m.startTime,m.endTime,m.text);const p=o[h.getAttribute("region")],E=a[h.getAttribute("style")],y=iu(p,E,a),{textAlign:T}=y;if(T){const v=tu[T];v&&(m.lineAlign=v),m.align=T}return te(m,y),m}).filter(h=>h!==null)}function Bs(e,t,s){const i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(s)):[]}function Kr(e){return e.reduce((t,s)=>{const i=s.getAttribute("xml:id");return i&&(t[i]=s),t},{})}function _a(e,t){return[].slice.call(e.childNodes).reduce((s,i,r)=>{var n;return i.nodeName==="br"&&r?s+`
`:(n=i.childNodes)!=null&&n.length?_a(i,t):t?s+i.textContent.trim().replace(/\s+/g," "):s+i.textContent},"")}function iu(e,t,s){const i="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=e!=null&&e.hasAttribute("style")?e.getAttribute("style"):null;return a&&s.hasOwnProperty(a)&&(r=s[a]),n.reduce((o,l)=>{const h=Us(t,i,l)||Us(e,i,l)||Us(r,i,l);return h&&(o[l]=h),o},{})}function Us(e,t,s){return e&&e.hasAttributeNS(t,s)?e.getAttributeNS(t,s):null}function Vr(e){return new Error(`Could not parse ttml timestamp ${e}`)}function $s(e,t){if(!e)return null;let s=Ia(e);return s===null&&(ba.test(e)?s=ru(e,t):Da.test(e)&&(s=nu(e,t))),s}function ru(e,t){const s=ba.exec(e),i=(s[4]|0)+(s[5]|0)/t.subFrameRate;return(s[1]|0)*3600+(s[2]|0)*60+(s[3]|0)+i/t.frameRate}function nu(e,t){const s=Da.exec(e),i=Number(s[1]);switch(s[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}var Yt=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},au=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yr(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(g.FRAG_LOADING,this.onFragLoading,this),e.on(g.FRAG_LOADED,this.onFragLoaded,this),e.on(g.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(g.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(g.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(g.FRAG_LOADING,this.onFragLoading,this),e.off(g.FRAG_LOADED,this.onFragLoaded,this),e.off(g.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(g.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(g.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(g.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Yt(this,"textTrack1"),t=new Yt(this,"textTrack2"),s=new Yt(this,"textTrack3"),i=new Yt(this,"textTrack4");this.cea608Parser1=new $r(1,e,t),this.cea608Parser2=new $r(3,s,i)}addCues(e,t,s,i,r){let n=!1;for(let a=r.length;a--;){const o=r[a],l=ou(o[0],o[1],t,s);if(l>=0&&(o[0]=Math.min(o[0],t),o[1]=Math.max(o[1],s),n=!0,l/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const a=this.captionsTracks[e];this.Cues.newCue(a,t,s,i)}else{const a=this.Cues.newCue(null,t,s,i);this.hls.trigger(g.CUES_PARSED,{type:"captions",cues:a,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){const{unparsedVttFrags:a}=this;s===U.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r,trackId:n}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.initPTS[o.frag.cc]?this.onFragLoaded(g.FRAG_LOADED,o):this.hls.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:o.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Hr(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=t[e],a=this.getExistingTrack(r,n);if(a)s[e]=a,dt(s[e]),ya(s[e],i);else{const o=this.createTextTrack("captions",r,n);o&&(o[e]=!0,s[e]=o)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s={_id:e,label:t.label,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(g.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(r=>{dt(i[r]),delete i[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yr(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)dt(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===Ns);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(ia(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const r=this.media,n=r?ss(r.textTracks):null;if(this.tracks.forEach((a,o)=>{let l;if(n){let h=null;for(let c=0;c<n.length;c++)if(n[c]&&Hr(n[c],a)){h=n[c],n[c]=null;break}h&&(l=h)}if(l)dt(l);else{const h=Pa(a);l=this.createTextTrack(h,a.name,a.lang),l&&(l.mode="disabled")}l&&this.textTracks.push(l)}),n!=null&&n.length){const a=n.filter(o=>o!==null).map(o=>o.label);a.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${a.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const r=this.tracks.map(n=>({label:n.name,kind:n.type.toLowerCase(),default:n.default,subtitleTrack:n}));this.hls.trigger(g.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:r})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,n=this.captionsProperties[r];n&&(n.label=s.name,s.lang&&(n.languageCode=s.lang),n.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===U.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:n,lastSn:a}=this,{cc:o,sn:l}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&n&&(l!==a+1||l===a&&h!==this.lastPartIndex+1||o!==this.lastCc)&&(r.reset(),n.reset()),this.lastCc=o,this.lastSn=l,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===U.SUBTITLE)if(i.byteLength){const r=s.decryptdata,n="stats"in t;if(r==null||!r.encrypted||n){const a=this.tracks[s.level],o=this.vttCCs;o[s.cc]||(o[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),a&&a.textCodec===Ns?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;Gr(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:n}=this,a=r.length-1;if(!r[s.cc]&&a===-1){n.push(e);return}const o=this.hls;eu((t=s.initSegment)!=null&&t.data?De(s.initSegment.data,new Uint8Array(i)).buffer:i,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,l=>{this._appendCues(l,s.level),o.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},l=>{const h=l.message==="Missing initPTS for VTT MPEGTS";h?n.push(e):this._fallbackToIMSC1(s,i),o.logger.log(`Failed to parse VTT cue: ${l}`),!(h&&a>s.cc)&&o.trigger(g.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:l})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||Gr(t,this.initPTS[e.cc],()=>{s.textCodec=Ns,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>va(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(g.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===U.SUBTITLE&&this.onFragLoaded(g.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===U.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const n=i[r].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();const a=this.extractCea608Data(n);this.cea608Parser1.addData(i[r].pts,a[0]),this.cea608Parser2.addData(i[r].pts,a[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(!(!n||n.currentTime<s)){if(!r||r==="video"){const{captionsTracks:a}=this;Object.keys(a).forEach(o=>ai(a[o],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:a}=this;Object.keys(a).forEach(o=>ai(a[o],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const n=e[i++],a=127&e[i++],o=127&e[i++];if(!(a===0&&o===0)&&(4&n)!==0){const l=3&n;(l===0||l===1)&&(t[l].push(a),t[l].push(o))}}return t}};function Pa(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Hr(e,t){return!!e&&e.kind===Pa(t)&&ti(t,e)}function ou(e,t,s,i){return Math.min(t,i)-Math.max(e,s)}function Yr(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var lu=/\s/,hu={newCue(e,t,s,i){const r=[];let n,a,o,l,h;const c=self.VTTCue||self.TextTrackCue;for(let d=0;d<i.rows.length;d++)if(n=i.rows[d],o=!0,l=0,h="",!n.isEmpty()){var u;for(let p=0;p<n.chars.length;p++)lu.test(n.chars[p].uchar)&&o?l++:(h+=n.chars[p].uchar,o=!1);n.cueStartTime=t,t===s&&(s+=1e-4),l>=16?l--:l++;const f=Ra(h.trim()),m=wi(t,s,f);e!=null&&(u=e.cues)!=null&&u.getCueById(m)||(a=new c(t,s,f),a.id=m,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),r.push(a))}return e&&r.length&&(r.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),r.forEach(d=>va(e,d))),r}};function cu(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var uu=/(\d+)-(\d+)\/(\d+)/,Wr=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||mu,this.controller=new self.AbortController,this.stats=new ui}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=du(e,this.controller.signal),n=e.responseType==="arraybuffer",a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&N(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(wt(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var c;this.response=this.loader=h;const u=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(u-i.loading.start)),!h.ok){const{status:f,statusText:m}=h;throw new pu(m||"fetch, bad network response",f,h)}i.loading.first=u,i.total=gu(h.headers)||i.total;const d=(c=this.callbacks)==null?void 0:c.onProgress;return d&&N(t.highWaterMark)?this.loadProgressively(h,i,e,t.highWaterMark,d):n?h.arrayBuffer():e.responseType==="json"?h.json():h.text()}).then(h=>{var c,u;const d=this.response;if(!d)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const f=h[a];f&&(i.loaded=i.total=f);const m={url:d.url,data:h,code:d.status},p=(c=this.callbacks)==null?void 0:c.onProgress;p&&!N(t.highWaterMark)&&p(i,e,h,d),(u=this.callbacks)==null||u.onSuccess(m,i,e,d)}).catch(h=>{var c;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const u=h&&h.code||0,d=h?h.message:null;(c=this.callbacks)==null||c.onError({code:u,text:d},e,h?h.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const n=new Fn,a=e.body.getReader(),o=()=>a.read().then(l=>{if(l.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=l.value,c=h.length;return t.loaded+=c,c<i||n.dataLength?(n.push(h),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,h.buffer,e),o()}).catch(()=>Promise.reject());return o()}};function du(e,t){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(te({},e.headers))};return e.rangeEnd&&s.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),s}function fu(e){const t=uu.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function gu(e){const t=e.get("Content-Range");if(t){const i=fu(t);if(N(i))return i}const s=e.get("Content-Length");if(s)return parseInt(s)}function mu(e,t){return new self.Request(e.url,t)}var pu=class extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}},Eu=/^age:\s*[\d.]+\s*$/im,Ca=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new ui,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(n=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(n=>{var a;(a=this.callbacks)==null||a.onError({code:s.status,text:n.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const a in i)e.setRequestHeader(a,i[a]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&N(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,h=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const d=h??t.response;if(d!=null){var n,a;s.loading.end=Math.max(self.performance.now(),s.loading.first),s.loaded=s.total=t.responseType==="arraybuffer"?d.byteLength:d.length,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const f=(n=this.callbacks)==null?void 0:n.onProgress;f&&f(s,e,d,t);const m={url:t.responseURL,data:d,code:l};(a=this.callbacks)==null||a.onSuccess(m,s,e,t);return}}const c=r.loadPolicy.errorRetry,u=s.retry;if(hs(c,u,!1,{url:e.url,data:void 0,code:l}))this.retry(c);else{var o;ee.error(`${l} while loading ${e.url}`),(o=this.callbacks)==null||o.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(hs(e,t,!0))this.retry(e);else{var s;ee.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=mi(e,s.retry),s.retry++,ee.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Eu.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},yu=J(J({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:Ca,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:wo,bufferController:Ah,capLevelController:Lh,errorController:No,fpsController:Ac,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:Rn,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},vu()),{},{subtitleStreamController:Oc,subtitleTrackController:Rc,timelineController:au,audioStreamController:yh,audioTrackController:vh,emeController:Ea,cmcdController:yc,contentSteeringController:Tc,interstitialsController:Mc});function vu(){return{cueHandler:hu,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Tu(e,t,s){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const i=li(e),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,l=t[o]===void 0,h=[];n.forEach(c=>{const u=`${a}Loading${c}`,d=t[u];if(d!==void 0&&l){h.push(u);const f=i[o].default;switch(t[o]={default:f},c){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d}}}),h.length&&s.warn(`hls.js config: "${h.join('", "')}" setting(s) are deprecated, use "${o}": ${ie(t[o])}`)}),J(J({},i),t)}function li(e){return e&&typeof e=="object"?Array.isArray(e)?e.map(li):Object.keys(e).reduce((t,s)=>(t[s]=li(e[s]),t),{}):e}function Su(e,t){const s=e.loader;s!==Wr&&s!==Ca?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):cu()&&(e.loader=Wr,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var is=2,Au=.1,Iu=.05,Lu=100,Ru=class extends vn{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(g.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Lu),this.mediaSource=t.mediaSource;const s=this.media=t.media;ye(s,"playing",this.onMediaPlaying),ye(s,"waiting",this.onMediaWaiting),ye(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Te(s,"playing",this.onMediaPlaying),Te(s,"waiting",this.onMediaWaiting),Te(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:a}=n,o=this.seeking&&!a,l=!this.seeking&&a,h=n.paused&&!a||n.ended||n.playbackRate===0;if(this.seeking=a,e!==t){t&&(this.ended=0),this.moved=!0,a||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||o){o&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(g.MEDIA_ENDED,{stalled:!1}));return}if(!j.getBuffered(n).length){this.nudgeRetry=0;return}const c=j.bufferInfo(n,e,0),u=c.nextStart||0,d=this.fragmentTracker;if(a&&d&&this.hls){const R=qr(this.hls.inFlightFragments,e),A=c.len>is,I=!u||R||u-e>is&&!d.getPartialFragment(e);if(A||I)return;this.moved=!1}const f=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&d){if(!(c.len>0)&&!u)return;const R=Math.max(u,c.start||0)-e,A=f!=null&&f.live?f.targetduration*2:is,I=Wt(e,d);if(R>0&&(R<=A||I)){n.paused||this._trySkipBufferHole(I);return}}const m=r.detectStallWithCurrentTimeMs,p=self.performance.now(),E=this.waiting;let y=this.stalled;if(y===null)if(E>0&&p-E<m)y=this.stalled=E;else{this.stalled=p;return}const T=p-y;if(!a&&(T>=m||E)&&this.hls){var v;if(((v=this.mediaSource)==null?void 0:v.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(e-(f?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(g.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}const S=j.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(S,T,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(g.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const r=j.bufferedInfo(j.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const n=j.timeRangesToArray(i),a=j.bufferedInfo(n,t,0).bufferedIndex;if(a>-1&&a<n.length-1){const o=j.bufferedInfo(n,e,0).bufferedIndex,l=n[a].end,h=n[a+1].start;if((o===-1||o>a)&&h-l<1&&e-l<2){const c=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${h} buffered index: ${o}`);this.warn(c.message),this.media.currentTime+=1e-6;let u=Wt(e,this.fragmentTracker);u&&"fragment"in u?u=u.fragment:u||(u=void 0);const d=j.bufferInfo(this.media,e,0);this.hls.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:c,reason:c.message,frag:u,buffer:d.len,bufferInfo:d})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:a}=this,o=(i=this.hls)==null?void 0:i.config;if(!a||!n||!o)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,h=Wt(s,n);if((h||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const c=e.buffered,u=this.adjacentTraversal(e,s);(c&&c.length>1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-s<o.maxBufferHole||u))&&(t>o.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const r=s.getFragAtPos(t,U.MAIN),n=s.getFragAtPos(i,U.MAIN);if(r&&n)return n.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;const n=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ie(e)})`);this.warn(n.message),t.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=(t=this.hls)==null?void 0:t.config;if(!i||!s||!r)return 0;const n=i.currentTime,a=j.bufferInfo(i,n,0),o=n<a.start?a.start:a.nextStart;if(o&&this.hls){const h=a.len<=r.maxBufferHole,c=a.len>0&&a.len<1&&i.readyState<3,u=o-n;if(u>0&&(h||c)){if(u>r.maxBufferHole){let f=!1;if(n===0){const m=s.getAppendedFrag(0,U.MAIN);m&&o<m.end&&(f=!0)}if(!f&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||qr(this.hls.inFlightFragments,o))return 0;let m=!1,p=e.end;for(;p<o;){const E=Wt(p,s);if(E)p+=E.duration;else{m=!0;break}}if(m)return 0}}const d=Math.max(o+Iu,n+Au);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${d}`),this.moved=!0,i.currentTime=d,!(e!=null&&e.gap)){const f=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${d}`),m={type:$.MEDIA_ERROR,details:L.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:f,reason:f.message,buffer:a.len,bufferInfo:a};e&&("fragment"in e?m.part=e:m.frag=e),this.hls.trigger(g.ERROR,m)}return d}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=t?.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const a=n+(i+1)*r.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(o.message),s.currentTime=a,t.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1,buffer:e.len,bufferInfo:e})}else{const a=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(a.message),t.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.BUFFER_STALLED_ERROR,error:a,fatal:!0,buffer:e.len,bufferInfo:e})}}};function qr(e,t){const s=jr(e.main);if(s&&s.start<=t)return s;const i=jr(e.audio);return i&&i.start<=t?i:null}function jr(e){if(!e)return null;switch(e.state){case C.IDLE:case C.STOPPED:case C.ENDED:case C.ERROR:return null}return e.frag}function Wt(e,t){return t.getAppendedFrag(e,U.MAIN)||t.getPartialFragment(e)}var bu=.25;function hi(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Gs(e,t,s,i,r){let n=new e(t,s,"");try{n.value=i,r&&(n.type=r)}catch{n=new e(t,s,ie(r?J({type:r},i):i))}return n}var qt=(()=>{const e=hi();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),Du=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(g.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(g.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(g.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&dt(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return ya(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=hi();if(n)for(let a=0;a<r.length;a++){const o=r[a].type;if(o===Re.emsg&&!s||!i)continue;const l=Vn(r[a].data),h=r[a].pts;let c=h+r[a].duration;c>qt&&(c=qt),c-h<=0&&(c=h+bu);for(let u=0;u<l.length;u++){const d=l[u];if(!Hn(d)){this.updateId3CueEnds(h,o);const f=Gs(n,h,c,d,o);f&&this.id3Track.addCue(f)}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const n=i[r];n.type===t&&n.startTime<e&&n.endTime===qt&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let l;i==="audio"?l=h=>h.type===Re.audioId3&&o:i==="video"?l=h=>h.type===Re.emsg&&a:l=h=>h.type===Re.audioId3&&o||h.type===Re.emsg&&a,ai(r,t,s,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const a=hi();if(s&&i&&!n){const{fragmentStart:m,fragmentEnd:p}=e;let E=this.assetCue;E?(E.startTime=m,E.endTime=p):a&&(E=this.assetCue=Gs(a,m,p,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:o}=this,{dateRanges:l}=e,h=Object.keys(l);let c=this.dateRangeCuesAppended;if(o&&t){var u;if((u=o.cues)!=null&&u.length){const m=Object.keys(c).filter(p=>!h.includes(p));for(let p=m.length;p--;){var d;const E=m[p],y=(d=c[E])==null?void 0:d.cues;delete c[E],y&&Object.keys(y).forEach(T=>{const v=y[T];if(v){v.removeEventListener("enter",this.onEventCueEnter);try{o.removeCue(v)}catch{}}})}}else c=this.dateRangeCuesAppended={}}const f=e.fragments[e.fragments.length-1];if(!(h.length===0||!N(f?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m<h.length;m++){const p=h[m],E=l[p],y=E.startTime,T=c[p],v=T?.cues||{};let S=T?.durationKnown||!1,R=qt;const{duration:A,endDate:I}=E;if(I&&A!==null)R=y+A,S=!0;else if(E.endOnNext&&!S){const P=h.reduce((_,M)=>{if(M!==E.id){const B=l[M];if(B.class===E.class&&B.startDate>E.startDate&&(!_||E.startDate<_.startDate))return B}return _},null);P&&(R=P.startTime,S=!0)}const D=Object.keys(E.attr);for(let P=0;P<D.length;P++){const _=D[P];if(!zo(_))continue;const M=v[_];if(M)S&&!(T!=null&&T.durationKnown)?M.endTime=R:Math.abs(M.startTime-y)>.01&&(M.startTime=y,M.endTime=R);else if(a){let B=E.attr[_];Qo(_)&&(B=Zr(B));const x=Gs(a,y,R,{key:_,data:B},Re.dateRange);x&&(x.id=p,this.id3Track.addCue(x),v[_]=x,n&&(_==="X-ASSET-LIST"||_==="X-ASSET-URL")&&x.addEventListener("enter",this.onEventCueEnter))}}c[p]={cues:v,dateRange:E,durationKnown:S}}}}},_u=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!s.live)return;const a=this.targetLatency;if(a===null)return;const o=i-a;if(o<Math.min(this.maxLatency,a+s.targetduration)&&o>.05&&this.forwardBufferLength>1){const l=Math.min(2,Math.max(1,n)),h=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20,c=Math.min(l,Math.max(1,h));this.changeMediaPlaybackRate(t,c)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||t;(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const s=this.levelDetails;if(s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,a=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(g.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(g.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(g.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(g.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===L.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},Pu=class extends _i{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this),e.on(g.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this),e.off(g.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let a=!1,o=!1,l=!1;t.levels.forEach(h=>{const c=h.attrs;let{audioCodec:u,videoCodec:d}=h;u&&(h.audioCodec=u=ns(u,s)||void 0),d&&(d=h.videoCodec=fo(d));const{width:f,height:m,unknownCodecs:p}=h,E=p?.length||0;if(a||(a=!!(f&&m)),o||(o=!!d),l||(l=!!u),E||u&&!this.isAudioSupported(u)||d&&!this.isVideoSupported(d)){this.log(`Some or all CODECS not supported "${c.CODECS}"`);return}const{CODECS:y,"FRAME-RATE":T,"HDCP-LEVEL":v,"PATHWAY-ID":S,RESOLUTION:R,"VIDEO-RANGE":A}=c,I=`${`${S||"."}-`}${h.bitrate}-${R}-${T}-${y}-${A}-${v}`;if(r[I])if(r[I].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const D=n[I]+=1;h.attrs["PATHWAY-ID"]=new Array(D+1).join(".");const P=this.createLevel(h);r[I]=P,i.push(P)}else r[I].addGroupId("audio",c.AUDIO),r[I].addGroupId("text",c.SUBTITLES);else{const D=this.createLevel(h);r[I]=D,n[I]=1,i.push(D)}}),this.filterAndSortMediaOptions(i,t,a,o,l)}createLevel(e){const t=new Pt(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=un(i,[])}return t}isAudioSupported(e){return Dt(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Dt(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var n;let a=[],o=[],l=e;const h=((n=t.stats)==null?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:y,videoRange:T,width:v,height:S})=>(!!y||!!(v&&S))&&Io(T))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let y="no level with compatible codecs found in manifest",T=y;t.levels.length&&(T=`one or more CODECS in variant not supported: ${ie(t.levels.map(S=>S.attrs.CODECS).filter((S,R,A)=>A.indexOf(S)===R))}`,this.warn(T),y+=` (${T})`);const v=new Error(y);this.hls.trigger(g.ERROR,{type:$.MEDIA_ERROR,details:L.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:v,reason:T})}}),h.end=performance.now();return}t.audioTracks&&(a=t.audioTracks.filter(y=>!y.audioCodec||this.isAudioSupported(y.audioCodec)),Xr(a)),t.subtitles&&(o=t.subtitles,Xr(o));const c=l.slice(0);l.sort((y,T)=>{if(y.attrs["HDCP-LEVEL"]!==T.attrs["HDCP-LEVEL"])return(y.attrs["HDCP-LEVEL"]||"")>(T.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&y.height!==T.height)return y.height-T.height;if(y.frameRate!==T.frameRate)return y.frameRate-T.frameRate;if(y.videoRange!==T.videoRange)return as.indexOf(y.videoRange)-as.indexOf(T.videoRange);if(y.videoCodec!==T.videoCodec){const v=$i(y.videoCodec),S=$i(T.videoCodec);if(v!==S)return S-v}if(y.uri===T.uri&&y.codecSet!==T.codecSet){const v=rs(y.codecSet),S=rs(T.codecSet);if(v!==S)return S-v}return y.averageBitrate!==T.averageBitrate?y.averageBitrate-T.averageBitrate:0});let u=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let y=0;y<c.length;y++)if(c[y].pathwayId===l[0].pathwayId){u=c[y];break}}this._levels=l;for(let y=0;y<l.length;y++)if(l[y]===u){var d;this._firstLevel=y;const T=u.bitrate,v=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${T}`),((d=this.hls.userConfig)==null?void 0:d.abrEwmaDefaultEstimate)===void 0){const S=Math.min(T,this.hls.config.abrEwmaDefaultEstimateMax);S>v&&v===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=S)}break}const f=r&&!i,m=this.hls.config,p=!!(m.audioStreamController&&m.audioTrackController),E={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:p&&!f&&a.some(y=>!!y.url)};h.end=performance.now(),this.hls.trigger(g.MANIFEST_PARSED,E)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(g.ERROR,{type:$.OTHER_ERROR,details:L.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:h,reason:h.message}),c)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===a)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${s}${r?" with Pathway "+r:""}`);const o={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(g.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const h=this.switchParams(n.uri,i?.details,l);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===X.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===U.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;if(!n){var a;this.warn(`Invalid level index ${i}`),(a=t.deliveryDirectives)!=null&&a.skip&&(r.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){n.fragmentError===0&&(n.loadError=0);let o=n.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(i,t,o)}else(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,a=n?.age;this.log(`Loading level index ${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(g.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(a=>a.level=-1)),!1));Mn(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(g.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(g.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}};function Xr(e){const t={};e.forEach(s=>{const i=s.groupId||"";s.id=t[i]=t[i]||0,t[i]++})}function ka(){return self.SourceBuffer||self.WebKitSourceBuffer}function wa(){if(!We())return!1;const e=ka();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Cu(){if(!wa())return!1;const e=We();return typeof e?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(_t(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(_t(t,"audio"))))}function ku(){var e;const t=ka();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)=="function"}var wu=100,Mu=class extends Ti{constructor(e,t,s){super(e,t,s,"stream-controller",U.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,r=i?i.currentTime:null;if(r===null||!N(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const n=this.getFwdBufferInfoAtPos(i,r,U.MAIN,0);if(n===null||n.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${n?n.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(g.MANIFEST_PARSED,this.onManifestParsed,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.LEVEL_LOADED,this.onLevelLoaded,this),e.on(g.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(g.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(g.BUFFER_CREATED,this.onBufferCreated,this),e.on(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(g.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(g.MANIFEST_PARSED,this.onManifestParsed,this),e.off(g.LEVEL_LOADED,this.onLevelLoaded,this),e.off(g.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(g.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(g.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(g.BUFFER_CREATED,this.onBufferCreated,this),e.off(g.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(g.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(wu),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=C.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=C.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case C.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e?.[t],i=s?.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=C.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=C.IDLE;break}break}case C.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===C.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const n=s[r],a=this.getMainFwdBufferInfo();if(a===null)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const m={};this.altAudio===2&&(m.type="video"),this.hls.trigger(g.BUFFER_EOS,m),this.state=C.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===C.WAITING_LEVEL||this.waitForLive(n)){this.level=r,this.state=C.WAITING_LEVEL,this.startFragRequested=!1;return}const h=a.len,c=this.getMaxBufferLength(n.maxBitrate);if(h>=c)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let d=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&d&&oe(d)&&this.fragmentTracker.getState(d)!==he.OK){var f;const m=((f=this.backtrackFragment)!=null?f:d).sn-l.startSN,p=l.fragments[m-1];p&&d.cc===p.cc&&(d=p,this.fragmentTracker.removeFragment(p))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(d&&this.isLoopLoading(d,u)){if(!d.gap){const m=this.audioOnly&&!this.altAudio?se.AUDIO:se.VIDEO,p=(m===se.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;p&&this.afterBufferFlushed(p,m,U.MAIN)}d=this.getNextFragmentLoopLoading(d,l,a,U.MAIN,c)}d&&(this.exceedsMaxBuffer(a,c,d)||(d.initSegment&&!d.initSegment.data&&!this.bitrateTest&&(d=d.initSegment),this.loadFragment(d,n,u)))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===he.NOT_LOADED||i===he.PARTIAL?oe(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,U.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const a=this.getMainFwdBufferInfo();if(!a||a.len<r.targetduration*2)return}if(!t.paused&&e){const a=e[this.hls.nextLoadLevel],o=this.fragLastKbps;o&&this.fragCurrent?s=this.fragCurrent.duration*a.maxBitrate/(1e3*o)+1:s=0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const a=this.followingBufferedFrag(n);if(a){this.abortCurrentFrag();const o=a.maxStartPTS?a.maxStartPTS:a.start,l=a.duration,h=Math.max(n.end,o+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case C.KEY_LOADING:case C.FRAG_LOADING:case C.FRAG_LOADING_WAITING_RETRY:case C.PARSING:case C.PARSED:this.state=C.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;ye(s,"playing",this.onMediaPlaying),ye(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Te(s,"playing",this.onMediaPlaying),Te(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(g.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const n=t.levels[r].audioCodec;n&&(s=s||n.indexOf("mp4a.40.2")!==-1,i=i||n.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!ku(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==C.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=C.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,a=t.details,o=a.totalduration;if(!i){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=t.levelInfo,h=this.fragCurrent;h&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let c=0;if(a.live||(s=l.details)!=null&&s.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,r||this.setStartPosition(a,c),this.hls.trigger(g.LEVEL_UPDATED,{details:a,level:n}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=C.IDLE}r&&a.live&&this.synchronizeToLiveEdge(a),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,a=e.edge,o=r>=n-t.maxFragLookUpTolerance&&r<=a;if(i!==null&&s.duration>i&&(r<i||!o)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!o&&s.readyState<4||r<a-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const c=j.bufferInfo(s,i,0);if(!((l=c.buffered)!=null&&l.length)){s.currentTime=i;return}if(c.start<=r){s.currentTime=i;return}const{nextStart:u}=j.bufferedInfo(c.buffered,r,0);u&&(s.currentTime=u)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const a=n[s.level];if(!a){this.warn(`Level ${s.level} not found on progress`);return}const o=a.details;if(!o){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const l=a.videoCodec,h=o.PTSKnown||!o.live,c=(t=s.initSegment)==null?void 0:t.data,u=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new sa(this.hls,U.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,m=f!==-1,p=new Ei(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,m),E=this.initPTS[s.cc];d.push(r,c,u,l,s,i,o.totalduration,h,p,E)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==0;if(os(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const r=this.fragCurrent;r&&(this.log("Switching to main audio track, cancel main fragment load"),r.abortRequests(),this.fragmentTracker.removeFragment(r)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(g.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(g.AUDIO_TRACK_SWITCHED,t)}),s.trigger(g.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(g.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=os(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const a in s){const o=s[a];if(o.id==="main"){if(r=a,i=o,a==="video"){const l=s[a];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===U.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===C.PARSED&&(this.state=C.IDLE);return}const a=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),oe(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&j.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case L.FRAG_GAP:case L.FRAG_PARSING_ERROR:case L.FRAG_DECRYPT_ERROR:case L.FRAG_LOAD_ERROR:case L.FRAG_LOAD_TIMEOUT:case L.KEY_LOAD_ERROR:case L.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(U.MAIN,t);break;case L.LEVEL_LOAD_ERROR:case L.LEVEL_LOAD_TIMEOUT:case L.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===X.LEVEL&&(this.state=C.IDLE);break;case L.BUFFER_ADD_CODEC_ERROR:case L.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case L.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case L.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=C.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==se.AUDIO||!this.altAudio){const s=(t===se.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,U.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=j.getBuffered(e),a=n.length?n.start(0):0,o=a-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),s+=o,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${a}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this,r=s?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=C.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=r.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(g.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n){this.resetWhenMissingContext(r);return}const{frag:a,part:o,level:l}=n,{video:h,text:c,id3:u,initSegment:d}=i,{details:f}=l,m=this.altAudio?void 0:i.audio;if(this.fragContextChanged(a)){this.fragmentTracker.removeFragment(a);return}if(this.state=C.PARSING,d){const p=d.tracks;if(p){const v=a.initSegment||a;if(this.unhandledEncryptionError(d,a))return;this._bufferInitSegment(l,p,v,r),s.trigger(g.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:t,tracks:p})}const E=d.initPTS,y=d.timescale,T=this.initPTS[a.cc];if(N(E)&&(!T||T.baseTime!==E||T.timescale!==y)){const v=d.trackId;this.initPTS[a.cc]={baseTime:E,timescale:y,trackId:v},s.trigger(g.INIT_PTS_FOUND,{frag:a,id:t,initPTS:E,timescale:y,trackId:v})}}if(h&&f){m&&h.type==="audiovideo"&&this.logMuxedErr(a);const p=f.fragments[a.sn-1-f.startSN],E=a.sn===f.startSN,y=!p||a.cc>p.cc;if(i.independent!==!1){const{startPTS:T,endPTS:v,startDTS:S,endDTS:R}=h;if(o)o.elementaryStreams[h.type]={startPTS:T,endPTS:v,startDTS:S,endDTS:R};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!y&&(this.couldBacktrack=!0),h.dropped&&h.independent){const A=this.getMainFwdBufferInfo(),I=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,D=h.firstKeyFramePTS?h.firstKeyFramePTS:T;if(!E&&I<D-this.config.maxBufferHole&&!y){this.backtrack(a);return}else y&&(a.gap=!0);a.setElementaryStreamInfo(h.type,a.start,v,a.start,R,!0)}else E&&T-(f.appliedTimelineOffset||0)>is&&(a.gap=!0);a.setElementaryStreamInfo(h.type,T,v,S,R),this.backtrackFragment&&(this.backtrackFragment=a),this.bufferFragmentData(h,a,o,r,E||y)}else if(E||y)a.gap=!0;else{this.backtrack(a);return}}if(m){const{startPTS:p,endPTS:E,startDTS:y,endDTS:T}=m;o&&(o.elementaryStreams[se.AUDIO]={startPTS:p,endPTS:E,startDTS:y,endDTS:T}),a.setElementaryStreamInfo(se.AUDIO,p,E,y,T),this.bufferFragmentData(m,a,o,r)}if(f&&u!=null&&u.samples.length){const p={id:t,frag:a,details:f,samples:u.samples};s.trigger(g.FRAG_PARSING_METADATA,p)}if(f&&c){const p={id:t,frag:a,details:f,samples:c.samples};s.trigger(g.FRAG_PARSING_USERDATA,p)}}logMuxedErr(e){this.warn(`${oe(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==C.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:a}=t;if(r){const l=e.audioCodec;let h=jt(r.codec,l);h==="mp4a"&&(h="mp4a.40.5");const c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const u=r.metadata;u&&"channelCount"in u&&(u.channelCount||1)!==1&&c.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),l&&l!==h&&this.log(`Swapping manifest audio codec "${l}" for "${h}"`),r.levelCodec=h,r.id=U.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${l||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=U.MAIN;const l=n.codec;if(l?.length===4)switch(l){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${n.codec!==l?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}a&&(this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${e.codecs}/${a.codec}]`),delete t.video,delete t.audio);const o=Object.keys(t);if(o.length){if(this.hls.trigger(g.BUFFER_CODECS,t),!this.hls)return;o.forEach(l=>{const h=t[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(g.BUFFER_APPENDING,{type:l,data:h,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,U.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=C.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(j.isBuffered(e,s)?t=this.getAppendedFrag(s):j.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(g.FRAG_CHANGED,{frag:t}),(!i||i.level!==r)&&this.hls.trigger(g.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return N(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(N(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?tt(null,s.fragments,t):null);if(i){const r=i.programDateTime;if(r!==null){const n=r+(t-i.start)*1e3;return new Date(n)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},Ou=class extends _e{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=L.KEY_LOAD_ERROR,s,i,r){return new Ge({type:$.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const n=t[i];if(e.cc<=n.cc&&(!oe(e)||!oe(n)||e.sn<n.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(n).then(a=>{if(!this.emeController)return;n.setKeyFormat(a);const o=zt(a);if(o)return this.emeController.getKeySystemAccess([o])})}if(this.config.requireKeySystemAccessOnStart){const i=St(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,L.KEY_LOAD_ERROR,l))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,L.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const a=Ks(r);let o=this.keyIdToKeyInfo[a];if((s=o)!=null&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if(this.emeController&&(i=o)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(o.decryptdata)){case"usable":case"usable-in-future":return o.keyLoadPromise.then(l=>{const{keyInfo:h}=l;return r.key=h.decryptdata.key,{frag:e,keyInfo:h}})}switch(this.log(`${this.keyIdToKeyInfo[a]?"Rel":"L"}oading${r.keyId?" keyId: "+fe(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),o=this.keyIdToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,L.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=t.initSegment)!=null&&i.data){const r=eo(t.initSegment.data);if(r.length){let n=r[0];n.some(a=>a!==0)?(this.log(`Using keyId found in init segment ${fe(n)}`),ds.setKeyIdForUri(e.decryptdata.uri,n)):(n=ds.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${fe(n)}`)),e.decryptdata.keyId=n}}return!e.decryptdata.keyId&&!oe(t)?Promise.resolve(s):(e.keyLoadPromise=this.emeController.loadKey(s).then(r=>(e.mediaKeySessionContext=r,s))).catch(r=>{throw e.keyLoadPromise=null,"data"in r&&(r.data.frag=t),r})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,a)=>{const o={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(o,h,{onSuccess:(c,u,d,f)=>{const{frag:m,keyInfo:p}=d,E=Ks(p.decryptdata);if(!m.decryptdata||p!==this.keyIdToKeyInfo[E])return a(this.createKeyLoadError(m,L.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),f));p.decryptdata.key=m.decryptdata.key=new Uint8Array(c.data),m.keyLoader=null,p.loader=null,n({frag:m,keyInfo:p})},onError:(c,u,d,f)=>{this.resetLoader(u),a(this.createKeyLoadError(t,L.KEY_LOAD_ERROR,new Error(`HTTP Error ${c.code} loading key ${c.text}`),d,J({url:o.url,data:void 0},c)))},onTimeout:(c,u,d)=>{this.resetLoader(u),a(this.createKeyLoadError(t,L.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),d))},onAbort:(c,u,d)=>{this.resetLoader(u),a(this.createKeyLoadError(t,L.INTERNAL_ABORTED,new Error("key loading aborted"),d))}})})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const n=Ks(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}};function Ks(e){if(e.keyFormat!==ge.FAIRPLAY){const t=e.keyId;if(t)return fe(t)}return e.uri}function zr(e){const{type:t}=e;switch(t){case X.AUDIO_TRACK:return U.AUDIO;case X.SUBTITLE_TRACK:return U.SUBTITLE;default:return U.MAIN}}function Vs(e,t){let s=e.url;return(s===void 0||s.indexOf("data:")===0)&&(s=t.url),s}var xu=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(g.MANIFEST_LOADING,this.onManifestLoading,this),e.on(g.LEVEL_LOADING,this.onLevelLoading,this),e.on(g.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(g.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(g.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(g.MANIFEST_LOADING,this.onManifestLoading,this),e.off(g.LEVEL_LOADING,this.onLevelLoading,this),e.off(g.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(g.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(g.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=new(s||i)(t);return this.loaders[e.type]=r,r}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:X.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:X.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:X.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:X.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(e,t){const s=this.loaders[X.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[X.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const o=this.hls.logger,l=i.context;if(l&&l.levelOrTrack===e.levelOrTrack&&(l.url===e.url||l.deliveryDirectives&&!e.deliveryDirectives)){l.url===e.url?o.log(`[playlist-loader]: ignore ${e.url} ongoing request`):o.log(`[playlist-loader]: ignore ${e.url} in favor of ${l.url}`);return}o.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===X.MANIFEST?r=s.manifestLoadPolicy.default:r=te({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),N((t=e.deliveryDirectives)==null?void 0:t.part)){let o;if(e.type===X.LEVEL&&e.level!==null?o=this.hls.levels[e.level].details:e.type===X.AUDIO_TRACK&&e.id!==null?o=this.hls.audioTracks[e.id].details:e.type===X.SUBTITLE_TRACK&&e.id!==null&&(o=this.hls.subtitleTracks[e.id].details),o){const l=o.partTarget,h=o.targetduration;if(l&&h){const c=Math.max(l*3,h*.8)*1e3;r=te({},r,{maxTimeToFirstByteMs:Math.min(c,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0};i.load(e,a,{onSuccess:(o,l,h,c)=>{const u=this.getInternalLoader(h);this.resetInternalLoader(h.type);const d=o.data;l.parsing.start=performance.now(),At.isMediaPlaylist(d)||h.type!==X.MANIFEST?this.handleTrackOrLevelPlaylist(o,l,h,c||null,u):this.handleMasterPlaylist(o,l,h,c)},onError:(o,l,h,c)=>{this.handleNetworkError(l,h,!1,o,c)},onTimeout:(o,l,h)=>{this.handleNetworkError(l,h,!0,void 0,o)}})}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,a=Vs(e,s),o=At.parseMasterPlaylist(n,a);if(o.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,o.playlistParsingError,i,t);return}const{contentSteering:l,levels:h,sessionData:c,sessionKeys:u,startTimeOffset:d,variableList:f}=o;this.variableList=f,h.forEach(y=>{const{unknownCodecs:T}=y;if(T){const{preferManagedMediaSource:v}=this.hls.config;let{audioCodec:S,videoCodec:R}=y;for(let A=T.length;A--;){const I=T[A];Dt(I,"audio",v)?(y.audioCodec=S=S?`${S},${I}`:I,pt.audio[S.substring(0,4)]=2,T.splice(A,1)):Dt(I,"video",v)&&(y.videoCodec=R=R?`${R},${I}`:I,pt.video[R.substring(0,4)]=2,T.splice(A,1))}}});const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":E}=At.parseMasterPlaylistMedia(n,a,o);m.length&&!m.some(y=>!y.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 ae({}),bitrate:0,url:""})),r.trigger(g.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:p,captions:E,contentSteering:l,url:a,stats:t,networkDetails:i,sessionData:c,sessionKeys:u,startTimeOffset:d,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:a,level:o,type:l}=s,h=Vs(e,s),c=N(o)?o:N(a)?a:0,u=zr(s),d=At.parseLevelPlaylist(e.data,h,c,u,0,this.variableList);if(l===X.MANIFEST){const f={attrs:new ae({}),bitrate:0,details:d,name:"",url:h};d.requestScheduled=t.loading.start+Cn(d,0),n.trigger(g.MANIFEST_LOADED,{levels:[f],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=d,this.handlePlaylistLoaded(d,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(g.ERROR,{type:$.NETWORK_ERROR,details:L.MANIFEST_PARSING_ERROR,fatal:t.type===X.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===X.LEVEL?n+=`: ${e.level} id: ${e.id}`:(e.type===X.AUDIO_TRACK||e.type===X.SUBTITLE_TRACK)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);const a=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let o=L.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case X.MANIFEST:o=s?L.MANIFEST_LOAD_TIMEOUT:L.MANIFEST_LOAD_ERROR,l=!0;break;case X.LEVEL:o=s?L.LEVEL_LOAD_TIMEOUT:L.LEVEL_LOAD_ERROR,l=!1;break;case X.AUDIO_TRACK:o=s?L.AUDIO_TRACK_LOAD_TIMEOUT:L.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case X.SUBTITLE_TRACK:o=s?L.SUBTITLE_TRACK_LOAD_TIMEOUT:L.SUBTITLE_LOAD_ERROR,l=!1}h&&this.resetInternalLoader(e.type);const c={type:$.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:h,context:e,error:a,networkDetails:t,stats:r};i&&(c.response=J({url:t?.url||e.url,data:void 0},i)),this.hls.trigger(g.ERROR,c)}handlePlaylistLoaded(e,t,s,i,r,n){const a=this.hls,{type:o,level:l,levelOrTrack:h,id:c,groupId:u,deliveryDirectives:d}=i,f=Vs(t,i),m=zr(i);let p=typeof i.level=="number"&&m===U.MAIN?l:void 0;const E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!a.config.ignorePlaylistParsingErrors){a.trigger(g.ERROR,{type:$.NETWORK_ERROR,details:L.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:t,context:i,level:p,parent:m,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const y=e.playlistParsingError=new Error("No Segments found in Playlist");a.trigger(g.ERROR,{type:$.NETWORK_ERROR,details:L.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:i,level:p,parent:m,networkDetails:r,stats:s});return}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),o){case X.MANIFEST:case X.LEVEL:if(p){if(!h)p=0;else if(h!==a.levels[p]){const y=a.levels.indexOf(h);y>-1&&(p=y)}}a.trigger(g.LEVEL_LOADED,{details:e,levelInfo:h||a.levels[0],level:p||0,id:c||0,stats:s,networkDetails:r,deliveryDirectives:d,withoutMultiVariant:o===X.MANIFEST});break;case X.AUDIO_TRACK:a.trigger(g.AUDIO_TRACK_LOADED,{details:e,track:h,id:c||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:d});break;case X.SUBTITLE_TRACK:a.trigger(g.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:c||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:d})}}},Ma=class ut{static get version(){return Ct}static isMSESupported(){return wa()}static isSupported(){return Cu()}static getMediaSource(){return We()}static get Events(){return g}static get MetadataSchema(){return Re}static get ErrorTypes(){return $}static get ErrorDetails(){return L}static get DefaultConfig(){return ut.defaultConfig?ut.defaultConfig:yu}static set DefaultConfig(t){ut.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Si,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 s=this.logger=Ka(t.debug||!1,"Hls instance",t.assetPlayerId),i=this.config=Tu(ut.DefaultConfig,t,s);this.userConfig=t,i.progressive&&Su(i,s);const{abrController:r,bufferController:n,capLevelController:a,errorController:o,fpsController:l}=i,h=new o(this),c=this.abrController=new r(this),u=new Bo(this),d=i.interstitialsController,f=d?this.interstitialsController=new d(this,ut):null,m=this.bufferController=new n(this,u),p=this.capLevelController=new a(this),E=new l(this),y=new xu(this),T=i.contentSteeringController,v=T?new T(this):null,S=this.levelController=new Pu(this,v),R=new Du(this),A=new Ou(this.config,this.logger),I=this.streamController=new Mu(this,u,A),D=this.gapController=new Ru(this,u);p.setStreamController(I),E.setStreamController(I);const P=[y,S,I];f&&P.splice(1,0,f),v&&P.splice(1,0,v),this.networkControllers=P;const _=[c,m,D,p,E,R,u];this.audioTrackController=this.createController(i.audioTrackController,P);const M=i.audioStreamController;M&&P.push(this.audioStreamController=new M(this,u,A)),this.subtitleTrackController=this.createController(i.subtitleTrackController,P);const B=i.subtitleStreamController;B&&P.push(this.subtititleStreamController=new B(this,u,A)),this.createController(i.timelineController,_),A.emeController=this.emeController=this.createController(i.emeController,_),this.cmcdController=this.createController(i.cmcdController,_),this.latencyController=this.createController(_u,_),this.coreComponents=_,P.push(h);const x=h.onErrorOut;typeof x=="function"&&this.on(g.ERROR,x,h),this.on(g.MANIFEST_LOADED,y.onManifestLoaded,y)}createController(t,s){if(t){const i=new t(this);return s&&s.push(i),i}return null}on(t,s,i=this){this._emitter.on(t,s,i)}once(t,s,i=this){this._emitter.once(t,s,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,s,i=this,r){this._emitter.off(t,s,i,r)}listeners(t){return this._emitter.listeners(t)}emit(t,s,i){return this._emitter.emit(t,s,i)}trigger(t,s){if(this.config.debug)return this.emit(t,t,s);try{return this.emit(t,t,s)}catch(i){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const r=t===g.ERROR;this.trigger(g.ERROR,{type:$.OTHER_ERROR,details:L.INTERNAL_EXCEPTION,fatal:r,event:t,error:i}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(g.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(s=>s.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(s=>s.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 n=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(g.ERROR,{type:$.OTHER_ERROR,details:L.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const s="media"in t,i=s?t.media:t,r=s?t:{media:i};this._media=i,this.trigger(g.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(g.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(g.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const s=this.media,i=this._url,r=this._url=ci.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),s&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),this.trigger(g.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,s){this.logger.log(`startLoad(${t+(s?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,s),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!(this.started||!this.networkControllers));t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[U.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[U.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[U.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,s=t?.currentTime;this.detachMedia(),t&&(this.attachMedia(t),s&&this.startLoad(s))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=bc()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const s=!!t;s!==this.config.capLevelToPlayerSize&&(s?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){Ao(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:s}}=this;if(!t)return 0;const i=t.length;for(let r=0;r<i;r++)if(t[r].maxBitrate>=s)return r;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:s,maxHdcpLevel:i}=this;let r;if(s===-1&&t!=null&&t.length?r=t.length-1:r=s,i)for(let n=r;n--;){const a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return r}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 s;return((s=this.audioTrackController)==null?void 0:s.setAudioOption(t))||null}setSubtitleOption(t){var s;return((s=this.subtitleTrackController)==null?void 0:s.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 s=this.audioTrackController;s&&(s.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 s=this.subtitleTrackController;s&&(s.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const s=this.subtitleTrackController;s&&(s.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){var t;return((t=this.interstitialsController)==null?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,s=this.allAudioTracks){return dn(t,gn(s),navigator.mediaCapabilities)}};Ma.defaultConfig=void 0;exports.default=Ma;