@collective-intelligence/ui-react 0.1.8 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -0
- package/THIRD-PARTY-NOTICES.md +104 -0
- package/dist/components/icons/index.js +1 -1
- package/dist/components/illustrations/index.js +1 -1
- package/dist/components/ui/index.d.ts +24 -6
- package/dist/components/ui/index.js +2 -2
- package/dist/components/ui-extensions/atoms/ThemeToggle/index.js +1 -1
- package/dist/components/ui-extensions/hooks/use-mobile.js +1 -1
- package/dist/components/ui-extensions/index.d.ts +10 -3
- package/dist/components/ui-extensions/index.js +5 -5
- package/dist/components/ui-extensions/molecules/VideoPlayer/index.d.ts +31 -0
- package/dist/components/ui-extensions/molecules/VideoPlayer/index.js +3 -0
- package/dist/hls.light-dtzc3f2q.js +27 -0
- package/dist/hooks/index.js +1 -1
- package/dist/hooks/operations.js +1 -1
- package/dist/hooks/use-debounced-callback.js +1 -1
- package/dist/hooks/use-mount-action.js +1 -1
- package/dist/{index-1hg2mydq.js → index-1ckm293n.js} +2 -2
- package/dist/index-38vag578.js +2 -0
- package/dist/{index-k79cbjh7.js → index-38vsn5nv.js} +2 -2
- package/dist/index-3eqse77d.js +6 -0
- package/dist/index-3me0m2fg.js +2 -0
- package/dist/index-7z26q7c0.js +42 -0
- package/dist/index-c5j7wr0c.js +2 -0
- package/dist/{index-vs10z2rc.js → index-cxjzg167.js} +2 -2
- package/dist/{index-42q094m7.js → index-dhysnhdt.js} +2 -2
- package/dist/{index-9nkdbb33.js → index-dt6f1hvx.js} +2 -2
- package/dist/index-er3rvnn2.js +2 -0
- package/dist/{index-x6g6brsv.js → index-fwsd4nes.js} +2 -2
- package/dist/index-gzn19hjr.js +2 -0
- package/dist/index-jqw3cf33.js +2 -0
- package/dist/index-k2h122pf.js +2 -0
- package/dist/{index-24awe3d6.js → index-r4k327de.js} +2 -2
- package/dist/index-t67ch826.js +2 -0
- package/dist/{index-q2bgrvjz.js → index-vrj20h57.js} +2 -2
- package/dist/{index-ycc4mvy6.js → index-y2h3pwvb.js} +2 -2
- package/dist/index-zk28jg41.js +2 -0
- package/dist/index.js +1 -1
- package/dist/resources.js +1 -1
- package/dist/tokens/theme.js +1 -1
- package/dist/utils/cn.js +1 -1
- package/package.json +10 -2
- package/dist/index-1kd3e9cz.js +0 -2
- package/dist/index-75cf149h.js +0 -2
- package/dist/index-87bxrmfq.js +0 -42
- package/dist/index-ckt9z566.js +0 -2
- package/dist/index-db7hx21g.js +0 -2
- package/dist/index-prdzy412.js +0 -6
- package/dist/index-rgye3pe5.js +0 -2
- package/dist/index-s7dyqth2.js +0 -2
- package/dist/index-whabarfn.js +0 -2
- package/dist/index-z3yjnfyn.js +0 -2
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
var V=Number.isFinite||function(t){return typeof t==="number"&&isFinite(t)},jn=Number.isSafeInteger||function(t){return typeof t==="number"&&Math.abs(t)<=qn},qn=Number.MAX_SAFE_INTEGER||9007199254740991,q=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),R=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",t.UNKNOWN="unknown",t}({}),v=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});function hr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var si={exports:{}},ls;function zn(){if(ls)return si.exports;return ls=1,function(t,e){(function(i){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,l={buildAbsoluteURL:function(o,u,d){if(d=d||{},o=o.trim(),u=u.trim(),!u){if(!d.alwaysNormalize)return o;var c=l.parseURL(o);if(!c)throw Error("Error trying to parse base URL.");return c.path=l.normalizePath(c.path),l.buildURLFromParts(c)}var h=l.parseURL(u);if(!h)throw Error("Error trying to parse relative URL.");if(h.scheme){if(!d.alwaysNormalize)return u;return h.path=l.normalizePath(h.path),l.buildURLFromParts(h)}var f=l.parseURL(o);if(!f)throw Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=r.exec(f.path);f.netLoc=g[1],f.path=g[2]}if(f.netLoc&&!f.path)f.path="/";var m={scheme:f.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc){if(m.netLoc=f.netLoc,h.path[0]!=="/")if(!h.path){if(m.path=f.path,!h.params){if(m.params=f.params,!h.query)m.query=f.query}}else{var E=f.path,y=E.substring(0,E.lastIndexOf("/")+1)+h.path;m.path=l.normalizePath(y)}}if(m.path===null)m.path=d.alwaysNormalize?l.normalizePath(h.path):h.path;return l.buildURLFromParts(m)},parseURL:function(o){var u=s.exec(o);if(!u)return null;return{scheme:u[1]||"",netLoc:u[2]||"",path:u[3]||"",params:u[4]||"",query:u[5]||"",fragment:u[6]||""}},normalizePath:function(o){o=o.split("").reverse().join("").replace(n,"");while(o.length!==(o=o.replace(a,"")).length);return o.split("").reverse().join("")},buildURLFromParts:function(o){return o.scheme+o.netLoc+o.path+o.params+o.query+o.fragment}};t.exports=l})()}(si),si.exports}var Bi=zn();class Ui{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var J=function(t){return t.MANIFEST="manifest",t.LEVEL="level",t.AUDIO_TRACK="audioTrack",t.SUBTITLE_TRACK="subtitleTrack",t.MEDIA_FRAGMENT="media-fragment",t.KEY="key",t.STEERING_MANIFEST="steering-manifest",t.SERVER_CERTIFICATE="server-certificate",t.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",t}({}),Q=function(t){return t.MAIN="main",t.AUDIO="audio",t.SUBTITLE="subtitle",t}({}),rt={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Gi{constructor(t){if(this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof t==="string")t={url:t};this.base=t,Xn(this,"stats")}setByteRange(t,e){let i=t.split("@",2),s;if(i.length===1)s=(e==null?void 0:e.byteRangeEndOffset)||0;else s=parseInt(i[1]);this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){if(this._byteRange===null)return[];return this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){if(this._streams===null)this._streams={[rt.AUDIO]:null,[rt.VIDEO]:null,[rt.AUDIOVIDEO]:null};return this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){if(this._stats===null)this._stats=new Ui;return this._stats}set stats(t){this._stats=t}get url(){if(!this._url&&this.relurl)this._url=Bi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0});return this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){let{elementaryStreams:t}=this;t[rt.AUDIO]=null,t[rt.VIDEO]=null,t[rt.AUDIOVIDEO]=null,this.url=null}}function St(t){return t.sn!=="initSegment"}function Le(t,e){return t.sn===(e==null?void 0:e.sn)&&t.level===e.level}function xi(t,e){return t.sn===(e==null?void 0:e.sn)&&t.level===e.level&&t.cc===e.cc}class ue extends Gi{constructor(t,e){super(e);this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get byteLength(){if(this.hasStats){let t=this.stats.total;if(t)return t}if(this.byteRange.length){let t=this.byteRange[0],e=this.byteRange[1];if(V(t)&&V(e))return e-t}return null}get bitrate(){if(this.byteLength)return this.byteLength*8/this.duration;if(this._bitrate)return this._bitrate;return null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;let{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity){if(!this._decryptdata)this._decryptdata=e.identity.getDecryptData(this.sn)}else if(!((t=this._decryptdata)!=null&&t.keyId)){let i=Object.keys(e);if(i.length===1){let s=this._decryptdata=e[i[0]]||null;if(s)this._decryptdata=s.getDecryptData(this.sn,e)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let t=!V(this.duration)?0:this.duration;return this.programDateTime+t*1000}get encrypted(){var t;if((t=this._decryptdata)!=null&&t.encrypted)return!0;else if(this.levelkeys){var e;let i=Object.keys(this.levelkeys),s=i.length;if(s>1||s===1&&(e=this.levelkeys[i[0]])!=null&&e.encrypted)return!0}return!1}get programDateTime(){if(this._programDateTime===null&&this.rawProgramDateTime)this.programDateTime=Date.parse(this.rawProgramDateTime);return this._programDateTime}set programDateTime(t){if(!V(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){if(!St(this))return null;if(!this._ref)this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime};return this._ref}addStart(t){this.setStart(this.start+t)}setStart(t){if(this.start=t,this._ref)this._ref.start=t}setDuration(t){if(this.duration=t,this._ref)this._ref.duration=t}setKeyFormat(t){let e=this.levelkeys;if(e){var i;let s=e[t];if(s&&!((i=this._decryptdata)!=null&&i.keyId))this._decryptdata=s.getDecryptData(this.sn,e)}}abortRequests(){var t,e;(t=this.loader)==null||t.abort(),(e=this.keyLoader)==null||e.abort()}setElementaryStreamInfo(t,e,i,s,r,n=!1){let{elementaryStreams:a}=this,l=a[t];if(!l){a[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:r,partial:n};return}l.startPTS=Math.min(l.startPTS,e),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,r)}}class fr extends Gi{constructor(t,e,i,s,r){super(i);this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=s;let n=t.enumeratedString("BYTERANGE");if(n)this.setByteRange(n,r);if(r)this.fragOffset=r.fragOffset+r.duration}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo||this.fragment.type===Q.SUBTITLE&&this.stats.loading.end>0)}}function gr(t,e){let i=Object.getPrototypeOf(t);if(i){let s=Object.getOwnPropertyDescriptor(i,e);if(s)return s;return gr(i,e)}}function Xn(t,e){let i=gr(t,e);if(i)i.enumerable=!0,Object.defineProperty(t,e,i)}function Qn(t,e,i){return(e=Jn(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function dt(){return dt=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var s in i)({}).hasOwnProperty.call(i,s)&&(t[s]=i[s])}return t},dt.apply(null,arguments)}function us(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,s)}return i}function Tt(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?us(Object(i),!0).forEach(function(s){Qn(t,s,i[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):us(Object(i)).forEach(function(s){Object.defineProperty(t,s,Object.getOwnPropertyDescriptor(i,s))})}return t}function Zn(t,e){if(typeof t!="object"||!t)return t;var i=t[Symbol.toPrimitive];if(i!==void 0){var s=i.call(t,e);if(typeof s!="object")return s;throw TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Jn(t){var e=Zn(t,"string");return typeof e=="symbol"?e:e+""}function Ge(t){switch(t.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:case R.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function mr(t){return t.details.startsWith("key")}function pr(t){return mr(t)&&!!t.frag&&!t.frag.decryptdata}function ds(t,e){let i=Ge(e);return t.default[`${i?"timeout":"error"}Retry`]}function Vi(t,e){let i=t.backoff==="linear"?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function cs(t){return Tt(Tt({},t),{errorRetry:null,timeoutRetry:null})}function me(t,e,i,s){if(!t)return!1;let r=s==null?void 0:s.code,n=e<t.maxNumRetry&&(ta(r)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,s,n):n}function ta(t){return pe(t)||!!t&&(t<400||t>499)}function pe(t){return t===0&&navigator.onLine===!1}function Er(t,e){return e>0&&t.loadError>0&&t.loadErrorTime!==0&&self.performance.now()-t.loadErrorTime>e}class Qt{constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(0.5)/t):0,this.estimate_=e,this.totalWeight_=i}sample(t,e){let i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class vr{constructor(t,e,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=0.001,this.minDelayMs_=50,this.slow_=new Qt(t),this.fast_=new Qt(e),this.defaultTTFB_=s,this.ttfb_=new Qt(t)}update(t,e){let{slow_:i,fast_:s,ttfb_:r}=this;if(i.halfLife!==t)this.slow_=new Qt(t,i.getEstimate(),i.getTotalWeight());if(s.halfLife!==e)this.fast_=new Qt(e,s.getEstimate(),s.getTotalWeight());if(r.halfLife!==t)this.ttfb_=new Qt(t,r.getEstimate(),r.getTotalWeight())}sample(t,e){if(e<=0)return;let i=Math.min(this.minDelayMs_,e/1e5),s=8*e,r=Math.max(t,i)/1000,n=s/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(t){let e=t/1000,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){if(this.canEstimate())return Math.min(this.fast_.getEstimate(),this.slow_.getEstimate());else return this.defaultEstimate_}getEstimateTTFB(){if(this.ttfb_.getTotalWeight()>=this.minWeight_)return this.ttfb_.getEstimate();else return this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class wt{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let i=`[${t}]:`;this.trace=Ht,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)}}var Ht=function(){},ea={trace:Ht,debug:Ht,log:Ht,warn:Ht,info:Ht,error:Ht};function Ai(){return dt({},ea)}function ia(t,e){let i=self.console[t];return i?i.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):Ht}function hs(t,e,i){return e[t]?e[t].bind(e):ia(t,i)}var Li=Ai();function sa(t,e,i){let s=Ai();if(typeof console==="object"&&t===!0||typeof t==="object"){let r=["debug","log","info","warn","error"];r.forEach((n)=>{s[n]=hs(n,t,i)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.7.3`)}catch(n){return Ai()}r.forEach((n)=>{Li[n]=hs(n,t)})}else dt(Li,s);return s}var st=Li,ri,fs;function ra(){if(fs)return ri;return fs=1,ri={},ri}var Gt=ra(),na=hr(Gt);function jt(t=!0){if(typeof self>"u")return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function aa(t){return typeof self<"u"&&t===self.ManagedMediaSource}function oa(t,e){let i=Object.keys(t),s=Object.keys(e),r=i.length,n=s.length;return!r||!n||r===n&&!i.some((a)=>s.indexOf(a)===-1)}function Ze(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}var la="utf-16",ni="utf-16be",gs="utf-16le",Fe="utf-8";function ua(t,e={}){let i;if(Ze(t))i=new DataView(t);else i=new DataView(t.buffer,t.byteOffset,t.byteLength);let s=0,{encoding:r}=e;if(!r){let u=i.getUint8(0),d=i.getUint8(1);if(u==239&&d==187&&i.getUint8(2)==191)r=Fe,s=3;else if(u==254&&d==255)r=ni,s=2;else if(u==255&&d==254)r=gs,s=2;else r=Fe}if(typeof TextDecoder<"u")return new TextDecoder(r).decode(i);let{byteLength:n}=i,a=r!==ni,l="",o;while(s<n){switch(r){case Fe:if(o=i.getUint8(s),o<128)s++;else if(o>=194&&o<=223)if(s+1<n){let u=i.getUint8(s+1);if(u>=128&&u<=191)o=(o&31)<<6|u&63,s+=2;else s++}else s++;else if(o>=224&&o<=239)if(s+2<=n-1){let u=i.getUint8(s+1),d=i.getUint8(s+2);if(u>=128&&u<=191&&d>=128&&d<=191)o=(o&15)<<12|(u&63)<<6|d&63,s+=3;else s++}else s++;else if(o>=240&&o<=244)if(s+3<=n-1){let u=i.getUint8(s+1),d=i.getUint8(s+2),c=i.getUint8(s+3);if(u>=128&&u<=191&&d>=128&&d<=191&&c>=128&&c<=191)o=(o&7)<<18|(u&63)<<12|(d&63)<<6|c&63,s+=4;else s++}else s++;else s++;break;case ni:case la:case gs:o=i.getUint16(s,a),s+=2;break}l+=String.fromCodePoint(o)}return l}function da(){try{return crypto.randomUUID()}catch(t){try{let e=URL.createObjectURL(new Blob),i=e.toString();return URL.revokeObjectURL(e),i.slice(i.lastIndexOf("/")+1)}catch(e){let i=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(s)=>{let r=(i+Math.random()*16)%16|0;return i=Math.floor(i/16),(s=="x"?r:r&3|8).toString(16)})}}}function Ki(t,e){if(e+10<=t.length){if(t[e]===73&&t[e+1]===68&&t[e+2]===51){if(t[e+3]<255&&t[e+4]<255){if(t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128)return!0}}}return!1}function Je(t,e){let i=0;return i=(t[e]&127)<<21,i|=(t[e+1]&127)<<14,i|=(t[e+2]&127)<<7,i|=t[e+3]&127,i}function ca(t,e){return Ki(t,e)&&Je(t,e+6)+10<=t.length-e}function yr(t,e){if(e+10<=t.length){if(t[e]===51&&t[e+1]===68&&t[e+2]===73){if(t[e+3]<255&&t[e+4]<255){if(t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128)return!0}}}return!1}function Ve(t,e){let i=e,s=0;while(Ki(t,e)){s+=10;let r=Je(t,e+6);if(s+=r,yr(t,e+10))s+=10;e+=s}if(s>0)return t.subarray(i,i+s)}function ha(t){if(Ze(t))return t;else{if(t.byteOffset==0&&t.byteLength==t.buffer.byteLength)return t.buffer;return new Uint8Array(t).buffer}}function ai(t,e=0,i=1/0){return fa(t,e,i,Uint8Array)}function fa(t,e,i,s){let r=ga(t),n=1;if("BYTES_PER_ELEMENT"in s)n=s.BYTES_PER_ELEMENT;let a=ma(t)?t.byteOffset:0,l=(a+t.byteLength)/n,o=(a+e)/n,u=Math.floor(Math.max(0,Math.min(o,l)));return new s(r,u,Math.floor(Math.min(u+Math.max(i,0),l))-u)}function ga(t){if(Ze(t))return t;else return t.buffer}function ma(t){return t&&Ze(t.buffer)&&t.byteLength!==void 0&&t.byteOffset!==void 0}function bt(t,e=!1){let i=e?t.indexOf(0):t.length,s=ua(new DataView(t.buffer,t.byteOffset,i),{encoding:Fe});return e?s:s.replace(/\0/g,"")}function pa(t){let e={key:t.type,description:"",data:"",mimeType:null,pictureType:null},i=3;if(t.size<2)return;if(t.data[0]!==3){console.log("Ignore frame with unrecognized character encoding");return}let s=t.data.subarray(1).indexOf(0);if(s===-1)return;let r=bt(ai(t.data,1,s)),n=t.data[2+s],a=t.data.subarray(3+s).indexOf(0);if(a===-1)return;let l=bt(ai(t.data,3+s,a)),o;if(r==="-->")o=bt(ai(t.data,4+s+a));else o=ha(t.data.subarray(4+s+a));return e.mimeType=r,e.pictureType=n,e.description=l,e.data=o,e}function Ea(t){if(t.size<2)return;let e=bt(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}function va(t){if(t.size<2)return;if(t.type==="TXXX"){let i=1,{data:s}=t,r=bt(s.subarray(i),!0);i+=r.length+1;let n=bt(s.subarray(i));return{key:t.type,info:r,data:n}}let e=bt(t.data.subarray(1));return{key:t.type,info:"",data:e}}function ya(t){if(t.type==="WXXX"){if(t.size<2)return;let i=1,s=bt(t.data.subarray(i),!0);i+=s.length+1;let r=bt(t.data.subarray(i));return{key:t.type,info:s,data:r}}let e=bt(t.data);return{key:t.type,info:"",data:e}}function Sa(t){if(t.type==="PRIV")return Ea(t);else if(t.type[0]==="W")return ya(t);else if(t.type==="APIC")return pa(t);return va(t)}function Ta(t){let e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=Je(t,4),s=10;return{type:e,size:i,data:t.subarray(10,10+i)}}var Re=10,xa=10;function Sr(t){let e=0,i=[];while(Ki(t,e)){let s=Je(t,e+6);if(t[e+5]>>6&1)e+=Re;e+=Re;let r=e+s;while(e+xa<r){let n=Ta(t.subarray(e)),a=Sa(n);if(a)i.push(a);e+=n.size+Re}if(yr(t,e))e+=Re}return i}function Tr(t){return t&&t.key==="PRIV"&&t.info==="com.apple.streaming.transportStreamTimestamp"}function Aa(t){if(t.data.byteLength===8){let e=new Uint8Array(t.data),i=e[3]&1,s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];if(s/=45,i)s+=47721858.84;return Math.round(s)}}function xr(t){let e=Sr(t);for(let i of e)if(Tr(i))return Aa(i)}function ee(t){let e="";for(let i=0;i<t.length;i++){let s=t[i].toString(16);if(s.length<2)s="0"+s;e+=s}return e}function Ar(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function ce(t){return String.fromCharCode.apply(null,t)}var Ct=Math.pow(2,32)-1,X={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},Lr={video:1,audio:2,id3:3,text:4};function Rr(t,e){let i=t[e]<<8|t[e+1];return i<0?65536+i:i}function K(t,e){let i=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return i<0?4294967296+i:i}function ms(t,e){let i=K(t,e);return i*=Math.pow(2,32),i+=K(t,e+4),i}function be(t,e){let i="";for(let s=e;s<t.length;s++)if(i+=String.fromCharCode(t[s]),t[s]===0)return i;return null}function Ri(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function Zt(t,e,i){t[e]=i>>24,t[e+1]=i>>16&255,t[e+2]=i>>8&255,t[e+3]=i&255}function La(t,e){let i=t.byteLength;for(let s=0;s<i;){let r=K(t,s);if(r>8&&K(t,s+4)===X[e])return!0;s=r>1?s+r:i}return!1}function et(t,e){let i=[];if(!e.length)return i;return br(t,e,0,0,t.byteLength,i),i}function br(t,e,i,s,r,n){let a=e[i];if((a==null?void 0:a.length)!==4)return;let l=a.charCodeAt(0),o=a.charCodeAt(1),u=a.charCodeAt(2),d=a.charCodeAt(3),c=e.length-1;for(let h=s;h<r;){let f=h+8<=r,g=h+4<=r?t[h]*16777216+(t[h+1]<<16|t[h+2]<<8|t[h+3]):K(t,h),m=g>1?h+g:r;if(f&&t[h+4]===l&&t[h+5]===o&&t[h+6]===u&&t[h+7]===d){let E=Math.min(m,r);if(i===c)n.push(t.subarray(h+8,E));else br(t,e,i+1,h+8,E,n)}h=m}}function Ra(t){let e=[],i=t[0],s=8,r=K(t,s);s+=4;let n=0,a=0;if(i===0)n=K(t,s),a=K(t,s+4),s+=8;else n=ms(t,s),a=ms(t,s+8),s+=16;s+=2;let l=t.length+a,o=Rr(t,s);s+=2;for(let u=0;u<o;u++){let d=s,c=K(t,d);d+=4;let h=c&2147483647;if((c&2147483648)>>>31===1)return st.warn("SIDX has hierarchical references (not supported)"),null;let g=K(t,d);d+=4,e.push({referenceSize:h,subsegmentDuration:g,info:{duration:g/r,start:l,end:l+h-1}}),l+=h,d+=4,s=d}return{earliestPresentationTime:n,timescale:r,version:i,referencesCount:o,references:e}}function Ir(t){let e=[],i=et(t,["moov","trak"]);for(let r=0;r<i.length;r++){let n=i[r],a=et(n,["tkhd"])[0];if(a){let l=a[0],o=K(a,l===0?12:20),u=et(n,["mdia","mdhd"])[0];if(u){l=u[0];let d=K(u,l===0?12:20),c=et(n,["mdia","hdlr"])[0];if(c){let h=ce(c.subarray(8,12)),f={soun:rt.AUDIO,vide:rt.VIDEO}[h],g=et(n,["mdia","minf","stbl","stsd"])[0],m=ba(g);if(f)e[o]={timescale:d,type:f,stsd:m},e[f]=Tt({timescale:d,id:o},m);else e[o]={timescale:d,type:h,stsd:m}}}}}return et(t,["moov","mvex","trex"]).forEach((r)=>{let n=K(r,4),a=e[n];if(a)a.default={duration:K(r,12),sampleSize:K(r,16),flags:K(r,20)}}),e}function ba(t){let e=t.subarray(8),i=e.subarray(86),s=ce(e.subarray(4,8)),r=s,n,a=s==="enca"||s==="encv";if(a){let u=et(e,[s])[0].subarray(s==="enca"?28:78);et(u,["sinf"]).forEach((c)=>{let h=et(c,["schm"])[0];if(h){let f=ce(h.subarray(4,8));if(f==="cbcs"||f==="cenc"){let g=et(c,["frma"])[0];if(g)r=ce(g)}}})}let l=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{let o=et(i,["avcC"])[0];if(o&&o.length>3)r+="."+_e(o[1])+_e(o[2])+_e(o[3]),n=Ie(l==="avc1"?"dva1":"dvav",i);break}case"mp4a":{let o=et(e,[s])[0],u=et(o.subarray(28),["esds"])[0];if(u&&u.length>7){let d=4;if(u[d++]!==3)break;d=oi(u,d),d+=2;let c=u[d++];if(c&128)d+=2;if(c&64)d+=u[d++];if(u[d++]!==4)break;d=oi(u,d);let h=u[d++];if(h===64)r+="."+_e(h);else break;if(d+=12,u[d++]!==5)break;d=oi(u,d);let f=u[d++],g=(f&248)>>3;if(g===31)g+=1+((f&7)<<3)+((u[d]&224)>>5);r+="."+g}break}case"hvc1":case"hev1":{let o=et(i,["hvcC"])[0];if(o&&o.length>12){let u=o[1],d=["","A","B","C"][u>>6],c=u&31,h=K(o,2),f=(u&32)>>5?"H":"L",g=o[12],m=o.subarray(6,12);r+="."+d+c,r+="."+Ia(h).toString(16).toUpperCase(),r+="."+f+g;let E="";for(let y=m.length;y--;){let p=m[y];if(p||E)E="."+p.toString(16).toUpperCase()+E}r+=E}n=Ie(l=="hev1"?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{r=Ie(r,i)||r;break}case"vp09":{let o=et(i,["vpcC"])[0];if(o&&o.length>6){let u=o[4],d=o[5],c=o[6]>>4&15;r+="."+Pt(u)+"."+Pt(d)+"."+Pt(c)}break}case"av01":{let o=et(i,["av1C"])[0];if(o&&o.length>2){let u=o[1]>>>5,d=o[1]&31,c=o[2]>>>7?"H":"M",h=(o[2]&64)>>6,f=(o[2]&32)>>5,g=u===2&&h?f?12:10:h?10:8,m=(o[2]&16)>>4,E=(o[2]&8)>>3,y=(o[2]&4)>>2,p=o[2]&3,S=1,T=1,x=1,A=0;r+="."+u+"."+Pt(d)+c+"."+Pt(g)+"."+m+"."+E+y+p+"."+Pt(1)+"."+Pt(1)+"."+Pt(1)+".0",n=Ie("dav1",i)}break}}return{codec:r,encrypted:a,supplemental:n}}function Ie(t,e){let i=et(e,["dvvC"]),s=i.length?i[0]:et(e,["dvcC"])[0];if(s){let r=s[2]>>1&127,n=s[2]<<5&32|s[3]>>3&31;return t+"."+Pt(r)+"."+Pt(n)}}function Ia(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}function oi(t,e){let i=e+5;while(t[e++]&128&&e<i);return e}function _e(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Pt(t){return(t<10?"0":"")+t}function _a(t,e){if(!t||!e)return;let i=e.keyId;if((i==null?void 0:i.byteLength)===16&&e.isCommonEncryption)_r(t,(s,r)=>{let n=s.subarray(8,24);if(!n.some((a)=>a!==0))st.log(`[eme] Patching keyId in 'enc${r?"a":"v"}>sinf>>tenc' box: ${ee(n)} -> ${ee(i)}`),s.set(i,8)})}function Da(t){let e=[];return _r(t,(i)=>e.push(i.subarray(8,24))),e}function _r(t,e){et(t,["moov","trak"]).forEach((s)=>{let r=et(s,["mdia","minf","stbl","stsd"])[0];if(!r)return;let n=r.subarray(8),a=et(n,["enca"]),l=a.length>0;if(!l)a=et(n,["encv"]);a.forEach((o)=>{let u=l?o.subarray(28):o.subarray(78);et(u,["sinf"]).forEach((c)=>{let h=Ca(c);if(h)e(h,l)})})})}function Ca(t){let e=et(t,["schm"])[0];if(e){let i=ce(e.subarray(4,8));if(i==="cbcs"||i==="cenc"){let s=et(t,["schi","tenc"])[0];if(s)return s}}}var ps;function Pa(t){if(typeof TextDecoder>"u")return bt(t);return(ps||(ps=new TextDecoder("utf-8"))).decode(t).replace(/\0/g,"")}function ka(t){let e=t.byteLength,i=[];for(let s=0;s<e;){let r=s+8<=e,n=s+4<=e?t[s]*16777216+(t[s+1]<<16|t[s+2]<<8|t[s+3]):K(t,s),a=n>1?s+n:e;if(r&&t[s+4]===109&&t[s+5]===111&&t[s+6]===111&&t[s+7]===102){let l=Math.min(a,e);for(let o=s+8;o<l;){let u=o+8<=l,d=o+4<=l?t[o]*16777216+(t[o+1]<<16|t[o+2]<<8|t[o+3]):K(t,o),c=d>1?o+d:l;if(u&&t[o+4]===116&&t[o+5]===114&&t[o+6]===97&&t[o+7]===102){let h=Math.min(c,l),f,g,m=[];for(let E=o+8;E<h;){let y=E+8<=h,p=E+4<=h?t[E]*16777216+(t[E+1]<<16|t[E+2]<<8|t[E+3]):K(t,E),S=p>1?E+p:h;if(y&&t[E+4]===116){let T=Math.min(S,h);if(t[E+5]===102&&t[E+6]===104&&t[E+7]===100)g||(g=t.subarray(E+8,T));else if(t[E+5]===102&&t[E+6]===100&&t[E+7]===116)f||(f=t.subarray(E+8,T));else if(t[E+5]===114&&t[E+6]===117&&t[E+7]===110)m.push(t.subarray(E+8,T))}E=S}i.push({moofOffset:t.byteOffset+s,tfdt:f,tfhd:g,truns:m})}o=c}}s=a}return i}function Oa(t,e,i,s,r=!0){return Dr(t,e,s,r)}function wa(t,e,i,s,r=!1){let n=[],a=e.samples,l=Dr(a,i,s,r,{isHEVCFlavor:Hi(e.codec),samples:n,timeOffset:t,timescale:e.timescale,trackId:e.id});return{samples:n,sampleData:{includeSampleDetails:r,tracks:l}}}function Dr(t,e,i,s,r){let n={},a=!1,l=ka(t),o=t.byteLength;for(let c=0;c<l.length;c++){let{moofOffset:h,tfdt:f,tfhd:g,truns:m}=l[c],E=K(g,4),y=e[E];if(!y)continue;let p=n[E]||(n[E]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:y.timescale,type:y.type}),S;if(f){let U=f[0];if(S=K(f,4),U===1)if(S===Ct)i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time");else S*=Ct+1,S+=K(f,8);if(V(S)&&(!V(p.start)||S<p.start))p.start=S;if(r&&V(S))r.timeOffset=S/r.timescale}let T=(r==null?void 0:r.trackId)===E&&y.type===rt.VIDEO,x=y.default,A=K(g,0)&16777215,b=(x==null?void 0:x.duration)||0,I,L=(x==null?void 0:x.sampleSize)||0,_=8;if(A&1)_+=8;if(A&2)_+=4;if(A&8)b=K(g,_),I=g.byteOffset-t.byteOffset+_,_+=4;if(A&16)L=K(g,_);let P=0,O=(A&1)!==0,H=!O&&(A&131072)!==0;if(O)P=K(g,8),P*=Math.pow(2,32),P+=K(g,12);else if(H)P=h;let M=S||0,C=0,k=b;for(let U=0;U<m.length;U++){let D=m[U],G=K(D,4),F=p.sampleCount;p.sampleCount+=G;let N=D[3]&1,W=0,z=D[3]&4,Z=D[2]&1,Y=D[2]&2,at=D[2]&4,gt=D[2]&8,tt=8;if(N)W=Ri(D,tt),tt+=4;if(z){if(!(D[tt+1]&1)&&p.keyFrameIndex===void 0)p.keyFrameIndex=F;tt+=4}let it=P+W;if(!s&&D[1]===0&&D[2]===6&&D[3]===1){var u,d;let ot=M,Vt=it,xe=tt,Mt=-1,zt=0,ft=0,Jt=(u=r==null?void 0:r.timeOffset)!=null?u:0,ne=b/((d=r==null?void 0:r.timescale)!=null?d:1),ei=(r==null?void 0:r.isHEVCFlavor)===!0,Yn=ei?2:1;for(let Nt=0;Nt<G;Nt++){let $t=D[tt]===0?D[tt+1]<<16|D[tt+2]<<8|D[tt+3]:K(D,tt),ae=Mt===-1&&p.keyFrameIndex===void 0&&(D[tt+5]&1)===0;tt+=8;let Ae=it+$t;if(T){if($t>0){let Lt=it;do{let as=t[Lt]===0?t[Lt+1]<<16|t[Lt+2]<<8|t[Lt+3]:K(t,Lt);Lt+=4;let os=t[Lt],ii=ei?os>>1&63:os&31;if(ei?ii===39||ii===40:ii===6)Ke(t.subarray(Lt,Lt+as),Yn,Jt,r.samples);Lt+=as}while(Lt<Ae)}Jt+=ne}if(it=Ae,ae)Mt=Nt,zt=it}if(it<=o)ft=G;else{let Nt=Vt,$t=xe;for(let ae=0;ae<G;ae++){let Ae=D[$t]===0?D[$t+1]<<16|D[$t+2]<<8|D[$t+3]:K(D,$t);if(Nt+=Ae,Nt>o)break;ft=ae+1,$t+=8}}if(T)r.timeOffset=Jt;if(Mt!==-1&&zt<=o&&p.keyFrameIndex===void 0)p.keyFrameIndex=Mt,p.keyFrameStart=ot+Mt*b;if(ft){if(!V(p.ptsMin)||ot<p.ptsMin)p.ptsMin=ot;let Nt=ot+ft*b;if(!V(p.ptsMax)||Nt>p.ptsMax)p.ptsMax=Nt}let ns=b*G;M=ot+ns,C+=ns;continue}let xt,Ft;if(s){if(xt=[],Ft={sampleOffset:it,samples:xt,defaultSampleDurationOffset:I},it<=o)p.trun.push(Ft)}let Et;for(let ot=0;ot<G;ot++){let Vt;if(Z){if(s)Vt=D.byteOffset-t.byteOffset+tt;k=K(D,tt),tt+=4}else k=b;if(Y)Et=K(D,tt),tt+=4;else Et=L;let xe,Mt;if(at){if(Mt=D[tt+1]&1?1:0,s)xe={isNonSync:Mt,dependsOn:(D[tt]&3)===1?1:2};tt+=4}let zt=0;if(gt)zt=D[0]===0?K(D,tt):Ri(D,tt),tt+=4;if(T){let ft=it,Jt=0;while(Jt<Et){let ne=K(t,ft);if(ft+=4,Cr(r.isHEVCFlavor,t[ft]))Ke(t.subarray(ft,ft+ne),r.isHEVCFlavor?2:1,r.timeOffset+zt/r.timescale,r.samples);ft+=ne,Jt+=ne+4}r.timeOffset+=k/r.timescale}if(it+=Et,it<=o){if(Ft&&Vt!==void 0)Ft.lastSampleDurationOffset=Vt;if(Mt===0&&p.keyFrameIndex===void 0)p.keyFrameIndex=ot,p.keyFrameStart=M;let ft=M+zt;if(!V(p.ptsMin)||ft<p.ptsMin)p.ptsMin=ft;if(!V(p.ptsMax)||ft+k>p.ptsMax)p.ptsMax=ft+k;if(xt)xt[ot]={cts:zt,duration:k,flags:xe,size:Et}}M+=k,C+=k}if(!C&&b)C+=b*G}if(p.duration+=C,p.duration)a=!0}if(!a){let c=1/0,h=0,f=et(t,["sidx"]);for(let g=0;g<f.length;g++){let m=Ra(f[g]);if(m!=null&&m.references){c=Math.min(c,m.earliestPresentationTime/m.timescale);let E=m.references.reduce((y,p)=>y+p.info.duration||0,0);h=Math.max(h,E+m.earliestPresentationTime/m.timescale)}}if(h&&V(h))Object.keys(n).forEach((g)=>{if(!n[g].duration)n[g].duration=h*n[g].timescale-n[g].start})}return n}function Fa(t){let e={valid:null,remainder:null},i=et(t,["moof"]);if(i.length<2)return e.remainder=t,e;let s=i[i.length-1];return e.valid=t.slice(0,s.byteOffset-8),e.remainder=t.slice(s.byteOffset-8),e}function It(t,e){let i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function Ma(t,e){let i=[],{samples:s,timescale:r,id:n}=e,a=!1;return et(s,["moof"]).map((o)=>{let u=o.byteOffset-8;et(o,["traf"]).map((c)=>{let h=et(c,["tfdt"]).map((f)=>{let g=f[0],m=K(f,4);if(g===1)m*=Math.pow(2,32),m+=K(f,8);return m/r})[0];if(h!==void 0)t=h;return et(c,["tfhd"]).map((f)=>{let g=K(f,4),m=K(f,0)&16777215,E=(m&1)!==0,y=0,p=(m&2)!==0,S=(m&8)!==0,T=0,x=(m&16)!==0,A=0,b=(m&32)!==0,I=!E&&(m&131072)!==0,L=8;if(g===n){if(E)y=K(f,L),L+=4,y*=Math.pow(2,32),y+=K(f,L),L+=4;else if(I)y=u;if(p)L+=4;if(S)T=K(f,L),L+=4;if(x)A=K(f,L),L+=4;if(b)L+=4;if(e.type==="video")a=Hi(e.codec);et(c,["trun"]).map((_)=>{let P=_[0],O=K(_,0)&16777215,H=(O&1)!==0,M=0,C=(O&4)!==0,k=(O&256)!==0,U=0,D=(O&512)!==0,G=0,F=(O&1024)!==0,N=(O&2048)!==0,W=0,z=K(_,4),Z=8;if(H)M=K(_,Z),Z+=4;if(C)Z+=4;let Y=y+M;for(let at=0;at<z;at++){if(k)U=K(_,Z),Z+=4;else U=T;if(D)G=K(_,Z),Z+=4;else G=A;if(F)Z+=4;if(N){if(P===0)W=K(_,Z);else W=Ri(_,Z);Z+=4}if(e.type===rt.VIDEO){let gt=0;while(gt<G){let tt=K(s,Y);if(Y+=4,Cr(a,s[Y])){let it=s.subarray(Y,Y+tt);Ke(it,a?2:1,t+W/r,i)}Y+=tt,gt+=tt+4}}t+=U/r}})}})})}),i}function Hi(t){if(!t)return!1;let e=t.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Cr(t,e){if(t){let i=e>>1&63;return i===39||i===40}else return(e&31)===6}function Ke(t,e,i,s){let r=Pr(t),n=0;n+=e;let a=0,l=0,o=0;while(n<r.length){a=0;do{if(n>=r.length)break;o=r[n++],a+=o}while(o===255);l=0;do{if(n>=r.length)break;o=r[n++],l+=o}while(o===255);let u=r.length-n,d=n;if(l<u)n+=l;else if(l>u){st.error(`Malformed SEI payload. ${l} is too small, only ${u} bytes left to parse.`);break}if(a===4){if(r[d++]===181){let h=Rr(r,d);if(d+=2,h===49){let f=K(r,d);if(d+=4,f===1195456820){let g=r[d++];if(g===3){let m=r[d++],E=31&m,y=64&m,p=y?2+E*3:0,S=new Uint8Array(p);if(y){S[0]=m;for(let T=1;T<p;T++)S[T]=r[d++]}s.push({type:g,payloadType:a,pts:i,bytes:S})}}}}}else if(a===5){if(l>16){let c=[];for(let g=0;g<16;g++){let m=r[d++].toString(16);if(c.push(m.length==1?"0"+m:m),g===3||g===5||g===7||g===9)c.push("-")}let h=l-16,f=new Uint8Array(h);for(let g=0;g<h;g++)f[g]=r[d++];s.push({payloadType:a,pts:i,uuid:c.join(""),userData:Pa(f),userDataBytes:f})}}}}function Pr(t){let e=t.byteLength,i,s=t.indexOf(3,3);while(s!==-1){if(t[s-1]===0&&t[s-2]===0)(i||(i=[])).push(s);s=t.indexOf(3,s+1)}if(!i)return t;let r=e-i.length,n=new Uint8Array(r),a=0,l=0;for(let o=0;o<r;l++,o++){if(l===i[a])l++,a++;n[o]=t[l]}return n}function Na(t){let e=t[0],i="",s="",r=0,n=0,a,l=0,o=0,u=4;if(e===0){let c=be(t,u),h=c!==null?be(t,u+c.length):null;if(c!==null&&h!==null)i=c,s=h,u+=c.length+h.length,r=K(t,u),u+=4,n=K(t,u),u+=4,l=K(t,u),u+=4,o=K(t,u),u+=4;else st.warn(`Unterminated ${c===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),u=t.length}else if(e===1){r=K(t,u),u+=4;let c=K(t,u);u+=4;let h=K(t,u);if(u+=4,a=4294967296*c+h,!jn(a))a=Number.MAX_SAFE_INTEGER,st.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box");l=K(t,u),u+=4,o=K(t,u),u+=4;let f=be(t,u),g=f!==null?be(t,u+f.length):null;if(f!==null)i=f,u+=f.length;if(g!==null)s=g,u+=g.length;else st.warn(`Unterminated ${f===null?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${f===null?"strings and payload":"value and payload"}`),u=t.length}let d=t.subarray(u,t.byteLength);return{schemeIdUri:i,value:s,timeScale:r,presentationTime:a,presentationTimeDelta:n,eventDuration:l,id:o,payload:d}}var Te=kr("userAgent");kr("vendor");var li,ui,di;function kr(t){try{return navigator[t]||""}catch(e){}return""}function $a(){if(di===void 0){let t=Te.match(/Safari\/(\d+)/i);di=t?parseInt(t[1]):0}return di}function he(){if(li===void 0){let t=Te.match(/Chrome\/(\d+)/i);li=t?parseInt(t[1]):0}return li}function Ba(){if(ui===void 0){let t=Te.match(/Firefox\/(\d+)/i);ui=t?parseInt(t[1]):0}return ui}function Ua(){return/\(Windows.+Firefox\//i.test(Te)}function Ga(){return/Android/.test(Te)}var se={audio:{a3ds:1,"ac-3":0.95,"ac-4":1,alac:0.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":0.9,enca:1,fLaC:0.9,flac:0.9,FLAC:0.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:0.8,dav1:0.8,drac:1,dva1:1,dvav:1,dvh1:0.7,dvhe:0.7,encv:1,hev1:0.75,hvc1:0.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:0.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function Wi(t,e){let i=se[e];return!!i&&!!i[t.slice(0,4)]}function Ee(t,e,i=!0){return!t.split(",").some((s)=>!Yi(s,e,i))}function Yi(t,e,i=!0){var s;let r=jt(i);return(s=r==null?void 0:r.isTypeSupported(bi(t,e)))!=null?s:!1}function bi(t,e){return`${e}/mp4;codecs=${t}`}function Es(t){if(t){let e=t.substring(0,4);return se.video[e]}return 2}function He(t){let e=Ua();return t.split(",").reduce((i,s)=>{let n=e&&Hi(s)?9:se.video[s];if(n)return(n*2+i)/(i?3:2);return(se.audio[s]+i)/(i?2:1)},0)}var ci={};function Va(t,e=!0){if(ci[t])return ci[t];let i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<i.length;r++){var s;if(Yi(i[r],"audio",e))return ci[t]=i[r],i[r];else if(i[r]==="mp3"&&(s=jt(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return t}var Ka=/flac|opus|mp4a\.40\.34/i;function We(t,e=!0){return t.replace(Ka,(i)=>Va(i.toLowerCase(),e))}function Ha(t,e){let i=[];if(t){let s=t.split(",");for(let r=0;r<s.length;r++)if(!Wi(s[r],"video"))i.push(s[r])}if(e)i.push(e);return i.join(",")}function Me(t,e){if(t&&(t.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t)!==-1)){if(vs(t,"audio")||vs(t,"video"))return t}if(e){let i=e.split(",");if(i.length>1){if(t){for(let s=i.length;s--;)if(i[s].substring(0,4)===t.substring(0,4))return i[s]}return i[0]}}return e||t}function vs(t,e){return Wi(t,e)&&Yi(t,e)}function Wa(t){let e=t.split(",");for(let i=0;i<e.length;i++){let s=e[i].split(".");if(s.length>2&&s[0]==="avc1")e[i]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`}return e.join(",")}function ys(t){let e=jt(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1}}function Ya(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}function ie(t,e,i){let s=encodeURIComponent(e),r=`${s}=${encodeURIComponent(i)}`,n=!1,a=[];if(t.search.substring(1).split("&").forEach((l)=>{if(l===s||l.startsWith(s+"=")){if(!n)a.push(r),n=!0}else if(l)a.push(l)}),!n)a.push(r);t.search=a.join("&")}var Ii=["NONE","TYPE-0","TYPE-1",null];function ja(t){return Ii.indexOf(t)>-1}var Ye=["SDR","PQ","HLG"];function qa(t){return!!t&&Ye.indexOf(t)>-1}var Ne={No:"",Yes:"YES",v2:"v2"};function Ss(t){let{canSkipUntil:e,canSkipDateRanges:i,age:s}=t,r=s<e/2;if(e&&r){if(i)return Ne.v2;return Ne.Yes}return Ne.No}class _i{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}addDirectives(t){let e=new self.URL(t);if(this.msn!==void 0)ie(e,"_HLS_msn",this.msn.toString());if(this.part!==void 0)ie(e,"_HLS_part",this.part.toString());if(this.skip)ie(e,"_HLS_skip",this.skip);return e.href}}class ji{constructor(t){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details)this.details=t.details;if(this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,"imageCodec"in t)this.imageCodec=t.imageCodec;if(this.codecSet=[t.videoCodec,t.audioCodec].filter((i)=>!!i).map((i)=>i.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;let i=(e=t.supplemental)==null?void 0:e.videoCodec;if(i&&i!==t.videoCodec)this.codecSet+=`,${i.substring(0,4)}`}if("iframes"in t&&t.iframes)this.iframes=!0;else this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return Ts(this._audioGroups,t)}hasSubtitleGroup(t){return Ts(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(!e)return;if(t==="audio"){let i=this._audioGroups;if(!i)i=this._audioGroups=[];if(i.indexOf(e)===-1)i.push(e)}else if(t==="text"){let i=this._subtitleGroups;if(!i)i=this._subtitleGroups=[];if(i.indexOf(e)===-1)i.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return(t=this.audioGroups)==null?void 0:t[0]}get textGroupId(){var t;return(t=this.subtitleGroups)==null?void 0:t[0]}addFallback(){}}function Ts(t,e){if(!e||!t)return!1;return t.indexOf(e)!==-1}function za(){if(typeof matchMedia==="function"){let t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return t.matches===!0}return!1}function Xa(t,e){let i=!1,s=[];if(t)i=t!=="SDR",s=[t];if(e){s=e.allowedVideoRanges||Ye.slice(0);let r=s.join("")!=="SDR"&&!e.videoCodec;if(i=e.preferHDR!==void 0?e.preferHDR:r&&za(),!i)s=["SDR"]}return{preferHDR:i,allowedVideoRanges:s}}var Qa=(t)=>{let e=new WeakSet;return(i,s)=>{if(t)s=t(i,s);if(typeof s==="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},yt=(t,e)=>JSON.stringify(t,Qa(e));function Za(t,e,i,s,r){let n=Object.keys(t),a=s==null?void 0:s.channels,l=s==null?void 0:s.audioCodec,o=r==null?void 0:r.videoCodec,u=a&&parseInt(a)===2,d=!1,c=!1,h=1/0,f=1/0,g=1/0,m=1/0,E=0,y=[],{preferHDR:p,allowedVideoRanges:S}=Xa(e,r);for(let I=n.length;I--;){let L=t[n[I]];if(d||(d=L.channels[2]>0),h=Math.min(h,L.minHeight),f=Math.min(f,L.minFramerate),g=Math.min(g,L.minBitrate),S.filter((P)=>L.videoRanges[P]>0).length>0)c=!0}h=V(h)?h:0,f=V(f)?f:0;let T=Math.max(1080,h),x=Math.max(30,f);if(g=V(g)?g:i,i=Math.max(g,i),!c)e=void 0;let A=n.length>1;return{codecSet:n.reduce((I,L)=>{let _=t[L];if(L===I)return I;if(y=c?S.filter((P)=>_.videoRanges[P]>0):[],A){if(_.minBitrate>i)return _t(L,`min bitrate of ${_.minBitrate} > current estimate of ${i}`),I;if(!_.hasDefaultAudio)return _t(L,"no renditions with default or auto-select sound found"),I;if(l&&L.indexOf(l.substring(0,4))%5!==0)return _t(L,`audio codec preference "${l}" not found`),I;if(a&&!u){if(!_.channels[a])return _t(L,`no renditions with ${a} channel sound found (channels options: ${Object.keys(_.channels)})`),I}else if((!l||u)&&d&&_.channels["2"]===0)return _t(L,"no renditions with stereo sound found"),I;if(_.minHeight>T)return _t(L,`min resolution of ${_.minHeight} > maximum of ${T}`),I;if(_.minFramerate>x)return _t(L,`min framerate of ${_.minFramerate} > maximum of ${x}`),I;if(!y.some((P)=>_.videoRanges[P]>0))return _t(L,`no variants with VIDEO-RANGE of ${yt(y)} found`),I;if(o&&L.indexOf(o.substring(0,4))%5!==0)return _t(L,`video codec preference "${o}" not found`),I;if(_.maxScore<E)return _t(L,`max score of ${_.maxScore} < selected max of ${E}`),I}if(I&&(He(L)>=He(I)||_.fragmentError>t[I].fragmentError))return I;return m=_.minIndex,E=_.maxScore,L},void 0),videoRanges:y,preferHDR:p,minFramerate:f,minBitrate:g,minIndex:m}}function _t(t,e){st.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Or(t){return t.reduce((e,i)=>{let s=e.groups[i.groupId];if(!s)s=e.groups[i.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1};s.tracks.push(i);let r=i.channels||"2";if(s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||i.default,s.hasAutoSelect=s.hasAutoSelect||i.autoselect,s.hasDefault)e.hasDefaultAudio=!0;if(s.hasAutoSelect)e.hasAutoSelectAudio=!0;return e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Ja(t,e,i,s){return t.slice(i,s+1).reduce((r,n,a)=>{if(!n.codecSet)return r;let l=n.audioGroups,o=r[n.codecSet];if(!o)r[n.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{"2":0},hasDefaultAudio:!l,fragmentError:0};o.minBitrate=Math.min(o.minBitrate,n.bitrate);let u=Math.min(n.height,n.width);return o.minHeight=Math.min(o.minHeight,u),o.minFramerate=Math.min(o.minFramerate,n.frameRate),o.minIndex=Math.min(o.minIndex,a),o.maxScore=Math.max(o.maxScore,n.score),o.fragmentError+=n.fragmentError,o.videoRanges[n.videoRange]=(o.videoRanges[n.videoRange]||0)+1,r},{})}function xs(t,e){var i;return!!t&&t!==((i=e.loadLevelObj)==null?void 0:i.uri)}class wr extends wt{constructor(t){super("abr",t.logger);this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=(e)=>{var i;let{fragCurrent:s,partCurrent:r,hls:n}=this;if(!n)return;let{autoLevelEnabled:a,media:l}=n;if(!s||!l)return;let o=performance.now(),u=r?r.stats:s.stats,d=r?r.duration:s.duration,c=o-u.loading.start,h=n.minAutoLevel,f=s.level,g=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||f<=h){this.clearTimer(),this._nextAutoLevel=-1;return}if(!a)return;let m=g>-1&&g!==f,E=!!e||m;if(!E&&(l.paused||!l.playbackRate||!l.readyState))return;let y=n.mainForwardBufferInfo;if(!E&&y===null)return;let p=this.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(c<=Math.max(p,1000*(d/(S*2))))return;let T=y?y.len/S:0,x=u.loading.first?u.loading.first-u.loading.start:-1,A=u.loaded&&x>-1,b=this.getBwEstimate(),I=n.levels,L=I[f],_=Math.max(u.loaded,Math.round(d*(s.bitrate||L.averageBitrate)/8)),P=A?c-x:c;if(P<1&&A)P=Math.min(c,u.loaded*8/b);let O=A?u.loaded*1000/P:0,H=p/1000,M=O?(_-u.loaded)/O:_*8/b+H;if(M<=T)return;let C=O?O*8:b,k=((i=(e==null?void 0:e.details)||n.latestLevelDetails)==null?void 0:i.live)===!0,U=n.config.abrBandWidthUpFactor,D=Number.POSITIVE_INFINITY,G;for(G=f-1;G>h;G--){let z=I[G].maxBitrate,Z=!I[G].details||k;if(D=this.getTimeToLoadFrag(H,C,d*z,Z),D<Math.min(T,d+H))break}if(D>=M)return;if(D>d*10)return;if(A)this.bwEstimator.sample(c-Math.min(p,x),u.loaded);else this.bwEstimator.sampleTTFB(c);let F=I[G].maxBitrate;if(this.getBwEstimate()*U>F)this.firstAutoFloor=Math.min(G,n.firstLevel),this.resetEstimator(F);let N=this.findBestLevel(F,h,G,0,T,1,1);if(N>-1)G=N;this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${f} is loading too slowly;
|
|
2
|
+
Fragment duration: ${s.duration.toFixed(3)}
|
|
3
|
+
Time to underbuffer: ${T.toFixed(3)} s
|
|
4
|
+
Estimated load time for current fragment: ${M.toFixed(3)} s
|
|
5
|
+
Estimated load time for down switch fragment: ${D.toFixed(3)} s
|
|
6
|
+
TTFB estimate: ${x|0} ms
|
|
7
|
+
Current BW estimate: ${V(b)?b|0:"Unknown"} bps
|
|
8
|
+
New BW estimate: ${this.getBwEstimate()|0} bps
|
|
9
|
+
Switching to level ${G} @ ${F|0} bps`),n.nextLoadLevel=n.nextAutoLevel=G,this.clearTimer();let W=()=>{this.clearTimer();let z=this.hls;if(this.fragCurrent===s&&z.loadLevel===G&&G>0){let Z=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${G>0?"and switching down":""}
|
|
10
|
+
Fragment duration: ${s.duration.toFixed(3)} s
|
|
11
|
+
Time to underbuffer: ${Z.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,G>h){let Y=this.findBestLevel(z.levels[h].bitrate,h,G,0,Z,1,1);if(Y===-1)Y=h;z.nextLoadLevel=z.nextAutoLevel=Y,this.firstAutoFloor=Math.min(Y,z.firstLevel),this.resetEstimator(z.levels[Y].bitrate)}}};if(m||M>D*2)W();else this.timer=self.setInterval(W,D*1000);n.trigger(v.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:u})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){if(!this.hls)return;if(t)this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t;this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let t=this.hls.config;return new vr(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){let t=this.hls;t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.FRAG_LOADING,this.onFragLoading,this),t.on(v.FRAG_LOADED,this.onFragLoaded,this),t.on(v.FRAG_BUFFERED,this.onFragBuffered,this),t.on(v.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(v.LEVEL_LOADED,this.onLevelLoaded,this),t.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(v.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(v.ERROR,this.onError,this)}unregisterListeners(){let{hls:t}=this;if(!t)return;t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.FRAG_LOADING,this.onFragLoading,this),t.off(v.FRAG_LOADED,this.onFragLoaded,this),t.off(v.FRAG_BUFFERED,this.onFragBuffered,this),t.off(v.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(v.LEVEL_LOADED,this.onLevelLoaded,this),t.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(v.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(v.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){if(this.lastLoadedFragLevel>-1&&this.fragCurrent)this.lastLoadedFragLevel=this.fragCurrent.level;this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){let i=e.frag;if(this.ignoreFragment(i))return;if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=e.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(e.fatal)return;switch(e.details){case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:{let i=e.frag,{fragCurrent:s,partCurrent:r}=this;if(i&&xi(i,s)){let n=performance.now(),a=r?r.stats:i.stats,l=n-a.loading.start,o=a.loading.first?a.loading.first-a.loading.start:-1;if(a.loaded&&o>-1){let d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(d,o),a.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(t,e,i,s){let r=t+i/e,n=s?t+this.lastLevelLoadSec:0;return r+n}onLevelLoaded(t,e){let i=this.hls.config,{loading:s}=e.stats,r=s.end-s.first;if(V(r))this.lastLevelLoadSec=r/1000;if(e.details.live)this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive);else this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD);if(this.timer>-1)this._abandonRulesCheck(e.levelInfo)}onFragLoaded(t,e){var i;let{frag:s,part:r}=e,n=r?r.stats:s.stats;if(s.type===Q.MAIN)this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start);if(this.ignoreFragment(s))return;if(this.clearTimer(),s.level===this._nextAutoLevel)this._nextAutoLevel=-1;if(this.firstSelection=-1,(i=this.hls)!=null&&i.config.abrMaxWithRealBitrate){let a=r?r.duration:s.duration,l=this.hls.levels[s.level],o=(l.loaded?l.loaded.bytes:0)+n.loaded,u=(l.loaded?l.loaded.duration:0)+a;l.loaded={bytes:o,duration:u},l.realBitrate=Math.round(8*o/u)}if(s.bitrateTest){let a={stats:n,frag:s,part:r,id:s.type};this.onFragBuffered(v.FRAG_BUFFERED,a),s.bitrateTest=!1}else this.lastLoadedFragLevel=s.level}onFragBuffered(t,e){let{frag:i,part:s}=e,r=s!=null&&s.stats.loaded?s.stats:i.stats;if(r.aborted)return;if(this.ignoreFragment(i))return;let a=((i.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());if(this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest)this.bitrateTestDelay=a/1000;else if(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate())this.firstAutoFloor=-1}ignoreFragment(t){return t.type!==Q.MAIN||t.sn==="initSegment"}clearTimer(){if(this.timer>-1)self.clearInterval(this.timer),this.timer=-1}get firstAutoLevel(){let{hls:t}=this;if(!t)return 0;let{maxAutoLevel:e,minAutoLevel:i}=t,s=this.getBwEstimate(),r=this.getStarvationDelay(),n=t.config.maxStarvationDelay,a=this.findBestLevel(s,i,e,r/2,n,1,1);if(a>-1)return a;let l=t.firstLevel,o=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,u=Math.min(Math.max(l,i),e,o);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${u}`),u}get forcedAutoLevel(){if(this.nextAutoLevelKey)return-1;return this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;let t=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(t!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;let r=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){let n=this.hls.levels;if(n.length>Math.max(t,r)&&n[t].loadError<=n[r].loadError)return t}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:t,partCurrent:e,hls:i}=this;if(!i)return-1;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=e?e.duration:t?t.duration:0,l=this.getBwEstimate(),o=this.getStarvationDelay(),{abrBandWidthFactor:u,abrBandWidthUpFactor:d}=r;if(o){let m=this.findBestLevel(l,n,s,o,0,u,d);if(m>=0)return this.rebufferNotice=-1,m}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!o){let m=this.bitrateTestDelay;if(m)c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-m,this.info(`bitrate test took ${Math.round(1000*m)}ms, set first fragment max fetchDuration to ${Math.round(1000*c)} ms`),u=d=1}let h=this.findBestLevel(l,n,s,o,c,u,d);if(this.rebufferNotice!==h)this.rebufferNotice=h,this.info(`${o?"rebuffering expected":"buffer is empty"}, optimal quality level ${h}`);if(h>-1)return h;let f=i.levels[n],g=i.loadLevelObj;if(g&&(f==null?void 0:f.bitrate)<g.bitrate)return n;return i.loadLevel}getStarvationDelay(){let t=this.hls,e=t==null?void 0:t.media;if(!e)return 1/0;let i=e&&e.playbackRate!==0?Math.abs(e.playbackRate):1,s=t.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(t,e,i,s,r,n,a){let{hls:l,lastLoadedFragLevel:o,fragCurrent:u,partCurrent:d}=this;if(!l)return-1;let c=s+r,h=o===-1?l.firstLevel:o,{levels:f,allAudioTracks:g,loadLevel:m,latestLevelDetails:E,config:y}=l;if(f.length===1)return 0;let p=f[h],S=!!(E!=null&&E.live),T=m===-1||o===-1,x,A="SDR",b=(p==null?void 0:p.frameRate)||0,{audioPreference:I,videoPreference:L}=y,_=this.audioTracksByGroup||(this.audioTracksByGroup=Or(g)),P=-1;if(T){if(this.firstSelection!==-1)return this.firstSelection;let k=this.codecTiers||(this.codecTiers=Ja(f,_,e,i)),U=Za(k,A,t,I,L),{codecSet:D,videoRanges:G,minFramerate:F,minBitrate:N,minIndex:W,preferHDR:z}=U;P=W,x=D,A=z?G[G.length-1]:G[0],b=F,t=Math.max(t,N),this.log(`picked start tier ${yt(U)}`)}else x=p==null?void 0:p.codecSet,A=p==null?void 0:p.videoRange;let O=d?d.duration:u?u.duration:0,H=this.bwEstimator.getEstimateTTFB()/1000,M=[];for(let k=i;k>=e;k--){var C;let U=f[k],D=k>h;if(!U)continue;if(x&&U.codecSet!==x||A&&U.videoRange!==A||D&&b>U.frameRate||!D&&b>0&&b<U.frameRate||(C=U.supportedResult)!=null&&(C=C.decodingInfoResults)!=null&&C.some((Y)=>Y.smooth===!1)){if(!T||k!==P){M.push(k);continue}}let G=U.details,F=(d?G==null?void 0:G.partTarget:G==null?void 0:G.averagetargetduration)||O||1,N;if(!D)N=n*t;else N=a*t;let W=O&&s>=O*2&&r===0?U.averageBitrate:U.maxBitrate,z=this.getTimeToLoadFrag(H,N,W*F,!G||G.live);if(N>=W&&(k===o||U.loadError===0&&U.fragmentError===0||Er(U,y.errorPenaltyExpireMs))&&(z<=H||!V(z)||S&&!this.bitrateTestDelay||z<c)){let Y=this.forcedAutoLevel;if(k!==m&&(Y===-1||Y!==m)){if(M.length)this.trace(`Skipped level(s) ${M.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${f[M[0]].codecs}" ${f[M[0]].videoRange}; not compatible with "${x}" ${A}`);this.info(`switch candidate:${h}->${k} adjustedbw(${Math.round(N)})-bitrate=${Math.round(N-W)} ttfb:${H.toFixed(1)} avgDuration:${F.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${z.toFixed(1)} firstSelection:${T} codecSet:${U.codecSet} videoRange:${U.videoRange} hls.loadLevel:${m}`)}if(T)this.firstSelection=k;return k}}return-1}set nextAutoLevel(t){let e=this.deriveNextAutoLevel(t);if(this._nextAutoLevel!==e)this.nextAutoLevelKey="",this._nextAutoLevel=e}deriveNextAutoLevel(t){if(!this.hls)return-1;let{maxAutoLevel:e,minAutoLevel:i}=this.hls;return Math.min(Math.max(t,i),e)}}var Fr={search:function(t,e){let i=0,s=t.length-1,r=null,n=null;while(i<=s){r=(i+s)/2|0,n=t[r];let a=e(n);if(a>0)i=r+1;else if(a<0)s=r-1;else return n}return null}};function to(t,e,i){if(e===null||!Array.isArray(t)||!t.length||!V(e))return null;let s=t[0].programDateTime;if(e<(s||0))return null;let r=t[t.length-1].endProgramDateTime;if(e>=(r||0))return null;for(let n=0;n<t.length;++n){let a=t[n];if(io(e,i,a))return a}return null}function qi(t,e,i=0,s=0,r=0.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;let l=t.endDTS-i;if(l>0&&l<0.0000015)i+=0.0000015;if(n&&t.level!==n.level&&n.end<=t.end)n=e[2+t.sn-e[0].sn]||null}else if(i===0&&e[0].start===0)n=e[0];if(n&&((!t||t.level===n.level)&&As(i,s,n)===0||eo(n,t,Math.min(r,s))))return n;let a=Fr.search(e,As.bind(null,i,s));if(a&&(a!==t||!n))return a;return n}function eo(t,e,i){if((e==null?void 0:e.start)===0&&e.level<t.level&&(e.endPTS||0)>0){let s=e.tagList.reduce((r,n)=>{if(n[0]==="INF")r+=parseFloat(n[1]);return r},i);return t.start<=s}return!1}function As(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;let s=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));if(i.start+i.duration-s<=t)return 1;else if(i.start-s>t&&i.start)return-1;return 0}function io(t,e,i){let s=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0))*1000;return(i.endProgramDateTime||0)-s>t}function so(t,e,i){if(t){if(t.startCC<=e&&t.endCC>=e){let s=t.fragments,{fragmentHint:r}=t;if(r)s=s.concat(r);let n;return Fr.search(s,(a)=>{if(a.cc<e)return 1;if(a.cc>e)return-1;if(n=a,a.end<=i)return 1;if(a.start>i)return-1;return 0}),n||null}}return null}function ro(t,e){if(e===t.endSN&&t.fragmentHint)return t.fragmentHint;return t.fragments[1+e-t.startSN]||null}var ht={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ct={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};class Mr extends wt{constructor(t){super("error-controller",t.logger);this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){let t=this.hls;t.on(v.ERROR,this.onError,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let t=this.hls;if(!t)return;t.off(v.ERROR,this.onError,this),t.off(v.ERROR,this.onErrorOut,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.LEVEL_UPDATED,this.onLevelUpdated,this)}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){if((t==null?void 0:t.type)===Q.MAIN)return t.level;return this.getVariantIndex()}getVariantIndex(){var t;let e=this.hls,i=e.currentLevel;if((t=e.loadLevelObj)!=null&&t.details||i===-1)return e.loadLevel;return i}variantHasKey(t,e){if(t){var i;if((i=t.details)!=null&&i.hasKey(e))return!0;let s=t.audioGroups;if(s)return this.hls.allAudioTracks.filter((n)=>s.indexOf(n.groupId)>=0).some((n)=>{var a;return(a=n.details)==null?void 0:a.hasKey(e)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var i;if(e.fatal)return;let s=this.hls,r=e.context;switch(e.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:e.errorAction=this.getFragRetryOrSwitchAction(e);return;case R.FRAG_PARSING_ERROR:if((i=e.frag)!=null&&i.gap){e.errorAction=$e();return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{e.errorAction=this.getFragRetryOrSwitchAction(e),e.errorAction.action=ht.SendAlternateToPenaltyBox;return}case R.PLAYLIST_UNCHANGED_ERROR:case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var n;let a=e.parent===Q.MAIN?e.level:s.loadLevel;if(e.details===R.LEVEL_EMPTY_ERROR&&!!((n=e.context)!=null&&(n=n.levelDetails)!=null&&n.live))e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a);else e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,a)}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:if(typeof(r==null?void 0:r.level)==="number")e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.level);return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){let a=s.loadLevelObj;if(a&&(r.type===J.AUDIO_TRACK&&a.hasAudioGroup(r.groupId)||r.type===J.SUBTITLE_TRACK&&a.hasSubtitleGroup(r.groupId))){e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=ht.SendAlternateToPenaltyBox,e.errorAction.flags=ct.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:e.errorAction={action:ht.SendAlternateToPenaltyBox,flags:ct.MoveAllAlternatesMatchingHDCP};return;case R.KEY_SYSTEM_SESSION_UPDATE_FAILED:case R.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case R.KEY_SYSTEM_NO_SESSION:e.errorAction={action:ht.SendAlternateToPenaltyBox,flags:ct.MoveAllAlternatesMatchingKey};return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:if(!e.errorAction)e.errorAction=this.getLevelSwitchAction(e,e.level);return;case R.MEDIA_SOURCE_REQUIRES_RESET:if(!e.errorAction)e.errorAction=this.getLevelSwitchAction(e,e.level);e.errorAction.flags|=ct.ResetMediaSource|ct.SwitchToSDR;return;case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_APPEND_NO_PROGRESS:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:e.errorAction=$e();return}if(e.type===q.KEY_SYSTEM_ERROR)e.levelRetry=!1,e.errorAction=$e()}getPlaylistRetryOrSwitchAction(t,e){let i=this.hls,s=ds(i.config.playlistLoadPolicy,t),r=this.playlistError++;if(me(s,r,Ge(t),t.response))return{action:ht.RetryRequest,flags:ct.None,retryConfig:s,retryCount:r};let a=this.getLevelSwitchAction(t,e);if(s)a.retryConfig=s,a.retryCount=r;return a}getFragRetryOrSwitchAction(t){let e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:r,keyLoadPolicy:n}=e.config,a=ds(mr(t)?n:r,t),l=e.levels.reduce((u,d)=>u+d.fragmentError,0);if(s){if(t.details!==R.FRAG_GAP)s.fragmentError++;if(!pr(t)){if(me(a,l,Ge(t),t.response))return{action:ht.RetryRequest,flags:ct.None,retryConfig:a,retryCount:l}}}let o=this.getLevelSwitchAction(t,i);if(a)o.retryConfig=a,o.retryCount=l;return o}getLevelSwitchAction(t,e){let i=this.hls;if(e===null||e===void 0)e=i.loadLevel;let s=this.hls.levels[e];if(s){var r,n;let o=t.details;if(s.loadError++,s.loadErrorTime=self.performance.now(),o===R.BUFFER_APPEND_ERROR)s.fragmentError++;let u=-1,{levels:d,loadLevel:c,minAutoLevel:h,maxAutoLevel:f}=i;if(!i.autoLevelEnabled&&!i.config.preserveManualLevelOnError)i.loadLevel=-1;let g=(r=t.frag)==null?void 0:r.type,E=(g===Q.AUDIO&&o===R.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&Ls(t))&&d.some(({audioCodec:x})=>s.audioCodec!==x),p=t.sourceBufferName==="video"&&Ls(t)&&d.some(({codecSet:x,audioCodec:A})=>s.codecSet!==x&&s.audioCodec===A),{type:S,groupId:T}=(n=t.context)!=null?n:{};for(let x=d.length;x--;){let A=(x+c)%d.length;if(A!==c&&A>=h&&A<=f&&(d[A].loadError===0||Er(d[A],i.config.errorPenaltyExpireMs))){var a,l;let b=d[A];if(o===R.FRAG_GAP&&g===Q.MAIN&&t.frag){let I=d[A].details;if(I){let L=qi(t.frag,I.fragments,t.frag.start);if(L!=null&&L.gap)continue}}else if(S===J.AUDIO_TRACK&&b.hasAudioGroup(T)||S===J.SUBTITLE_TRACK&&b.hasSubtitleGroup(T))continue;else if(g===Q.AUDIO&&(a=s.audioGroups)!=null&&a.some((I)=>b.hasAudioGroup(I))||g===Q.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some((I)=>b.hasSubtitleGroup(I))||E&&s.audioCodec===b.audioCodec||p&&s.codecSet===b.codecSet||!E&&s.audioCodec!==b.audioCodec)continue;u=A;break}}if(u>-1&&i.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:ht.SendAlternateToPenaltyBox,flags:ct.None,nextAutoLevel:u}}return{action:ht.SendAlternateToPenaltyBox,flags:ct.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var i,s;switch((i=e.errorAction)==null?void 0:i.action){case ht.DoNothing:break;case ht.SendAlternateToPenaltyBox:if(this.sendAlternateToPenaltyBox(e),!e.errorAction.resolved&&e.details!==R.FRAG_GAP&&e.details!==R.PLAYLIST_UNCHANGED_ERROR&&!Nr(e))e.fatal=!0;break;case ht.RetryRequest:break}if((((s=e.errorAction)==null?void 0:s.flags)||0)&ct.ResetMediaSource)this.hls.recoverMediaError();if(e.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){let e=this.hls,i=t.errorAction;if(!i)return;let s=i.nextAutoLevel;if(i.flags===ct.None)this.switchLevel(t,s);else if(i.flags&ct.SwitchToSDR){let a=this.hls.levels,l=a.length;for(let o=l;o--;)if(a[o].videoRange!=="SDR")a[o].fragmentError++,a[o].loadError++;else if(s===void 0)s=o}else if(i.flags&ct.MoveAllAlternatesMatchingHDCP){let a=this.getVariantLevelIndex(t.frag),l=e.levels[a],o=l==null?void 0:l.attrs["HDCP-LEVEL"];i.hdcpLevel=o;let u=o==="NONE";if(o&&!u)e.maxHdcpLevel=Ii[Ii.indexOf(o)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`);else{if(u)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");i.flags|=ct.MoveAllAlternatesMatchingKey}}if(i.flags&ct.MoveAllAlternatesMatchingKey){let a=t.decryptdata;if(a){let l=this.hls.levels,o=l.length;for(let d=o;d--;)if(this.variantHasKey(l[d],a)){var r,n;this.log(`Banned key found in level ${d} (${l[d].bitrate}bps) or audio group "${(r=l[d].audioGroups)==null?void 0:r.join(",")}" (${(n=t.frag)==null?void 0:n.type} fragment) ${ee(a.keyId||[])}`),l[d].fragmentError++,l[d].loadError++,this.log(`Removing level ${d} with key error (${t.error})`),this.hls.removeLevel(d)}let u=t.frag;if(this.hls.levels.length<o)i.resolved=!0;else if(u&&u.type!==Q.MAIN){let d=u.decryptdata;if(d&&!a.matches(d))i.resolved=!0}}}if(!i.resolved)this.switchLevel(t,s)}switchLevel(t,e){if(e!==void 0&&t.errorAction){if(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===R.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&t.sourceBufferName!=="audiovideo"){let i=Ya(t.mimeType),s=this.hls.levels;for(let r=s.length;r--;)if(s[r][`${t.sourceBufferName}Codec`]===i)this.log(`Removing level ${r} for ${t.details} ("${i}" not supported)`),this.hls.removeLevel(r)}}}}function Ls(t){let e=t.details;if(e===R.BUFFER_ADD_CODEC_ERROR||e===R.MEDIA_SOURCE_REQUIRES_RESET)return!0;if(e===R.BUFFER_APPEND_ERROR){if(!Nr(t))return!0}return!1}function Nr(t){return t.details===R.BUFFER_APPEND_ERROR&&(t.error.name==="QuotaExceededError"||t.error.name==="InvalidStateError")}function $e(t){let e={action:ht.DoNothing,flags:ct.None};if(t)e.resolved=!0;return e}var no=/^(\d+)x(\d+)$/,Rs=/(.+?)=(".*?"|.*?)(?:,|$)/g;class nt{constructor(t,e){if(typeof t==="string")t=nt.parseAttrList(t,e);dt(this,t)}get clientAttrs(){return Object.keys(this).filter((t)=>t.substring(0,2)==="X-")}decimalInteger(t){let e=parseInt(this[t],10);if(e>Number.MAX_SAFE_INTEGER)return 1/0;return e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(e.length&1?"0":"")+e;let i=new Uint8Array(e.length/2);for(let s=0;s<e.length/2;s++)i[s]=parseInt(e.slice(s*2,s*2+2),16);return i}return null}hexadecimalIntegerAsNumber(t){let e=parseInt(this[t],16);if(e>Number.MAX_SAFE_INTEGER)return 1/0;return e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){let i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){let i=this[t];return(i?i.split(/[ ,]+/):[]).reduce((s,r)=>(s[r.toLowerCase()]=!0,s),e)}bool(t){return this[t]==="YES"}decimalResolution(t){let e=no.exec(this[t]);if(e===null)return;return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i,s={},r='"';Rs.lastIndex=0;while((i=Rs.exec(t))!==null){let n=i[1].trim(),a=i[2],l=a.indexOf('"')===0&&a.lastIndexOf('"')===a.length-1,o=!1;if(l)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(l||o));else if(!o&&!l)switch(n){case"CLOSED-CAPTIONS":if(a==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":st.warn(`${t}: attribute ${n} is missing quotes`)}s[n]=a}return s}}var ao="com.apple.hls.interstitial";function oo(t){return t!=="ID"&&t!=="CLASS"&&t!=="CUE"&&t!=="START-DATE"&&t!=="DURATION"&&t!=="END-DATE"&&t!=="END-ON-NEXT"}function lo(t){return t==="SCTE35-OUT"||t==="SCTE35-IN"||t==="SCTE35-CMD"}class zi{constructor(t,e,i=0){var s;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(e==null?void 0:e.tagAnchor)||null,this.tagOrder=(s=e==null?void 0:e.tagOrder)!=null?s:i,e){let r=e.attr;for(let n in r)if(Object.prototype.hasOwnProperty.call(t,n)&&t[n]!==r[n]){st.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=n;break}t=dt(new nt({}),r,t)}if(this.attr=t,e)this._startDate=e._startDate,this._cue=e._cue,this._endDate=e._endDate,this._dateAtEnd=e._dateAtEnd;else this._startDate=new Date(t["START-DATE"]);if("END-DATE"in t){let r=(e==null?void 0:e.endDate)||new Date(t["END-DATE"]);if(V(r.getTime()))this._endDate=r}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let t=this._cue;if(t===void 0)return this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1});return t}get startTime(){let{tagAnchor:t}=this;if(t===null||t.programDateTime===null)return st.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN;return t.start+(this.startDate.getTime()-t.programDateTime)/1000}get startDate(){return this._startDate}get endDate(){let t=this._endDate||this._dateAtEnd;if(t)return t;let e=this.duration;if(e!==null)return this._dateAtEnd=new Date(this._startDate.getTime()+e*1000);return null}get duration(){if("DURATION"in this.attr){let t=this.attr.decimalFloatingPoint("DURATION");if(V(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1000;return null}get plannedDuration(){if("PLANNED-DURATION"in this.attr)return this.attr.decimalFloatingPoint("PLANNED-DURATION");return null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===ao}get isValid(){return!!this.id&&!this._badValueForSameId&&V(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||("X-ASSET-URI"in this.attr)||("X-ASSET-LIST"in this.attr))}get invalidReason(){if(!this.id)return"Missing ID";if(this._badValueForSameId)return`Date range ${this._badValueForSameId} mismatch`;if(!V(this.startDate.getTime()))return"Date range invalid start date";if(this.isInterstitial&&!(("X-ASSET-URI"in this.attr)||("X-ASSET-LIST"in this.attr)))return"Interstitial Date range missing X-ASSET-(LIST|URI)";if(!this.isValid)return"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)";return null}}var $r=10;class Br{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}let e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;if(this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||e===0&&i>0,this.updated||this.advanced)this.misses=0;else this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some((e)=>{let i=e.decryptdata;if(!i)e.setKeyFormat(t.keyFormat),i=e.decryptdata;return!!i&&t.matches(i)})}get hasProgramDateTime(){if(this.fragments.length)return V(this.fragments[this.fragments.length-1].programDateTime);return!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||$r}get drift(){let t=this.driftEndTime-this.driftStartTime;if(t>0)return(this.driftEnd-this.driftStart)*1000/t;return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;if((t=this.partList)!=null&&t.length)return this.partList[this.partList.length-1].end;return this.fragmentEnd}get fragmentEnd(){if(this.fragments.length)return this.fragments[this.fragments.length-1].end;return 0}get fragmentStart(){if(this.fragments.length)return this.fragments[0].start;return 0}get age(){if(this.advancedDateTime)return Math.max(Date.now()-this.advancedDateTime,0)/1000;return 0}get lastPartIndex(){var t;if((t=this.partList)!=null&&t.length)return this.partList[this.partList.length-1].index;return-1}get maxPartIndex(){let t=this.partList;if(t){let e=this.lastPartIndex;if(e!==-1){for(let i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}get lastPartSn(){var t;if((t=this.partList)!=null&&t.length)return this.partList[this.partList.length-1].fragment.sn;return this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function Ur(t,e){if(t.length===e.length)return!t.some((i,s)=>i!==e[s]);return!1}function bs(t,e){if(!t&&!e)return!0;if(!t||!e)return!1;return Ur(t,e)}var qt={cbc:0,ctr:1};function fe(t){return t==="AES-128"||t==="AES-256"||t==="AES-256-CTR"}function Gr(t){switch(t){case"AES-128":case"AES-256":return qt.cbc;case"AES-256-CTR":return qt.ctr;default:throw Error(`invalid full segment method ${t}`)}}var De={};class ve{static clearKeyUriToKeyIdMap(){De={}}static setKeyIdForUri(t,e){De[t]=e}static addKeyIdForUri(t){let e=Object.keys(De).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,e),De[t]=i,i}constructor(t,e,i,s=[1],r=null,n){if(this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!fe(t),n!=null&&n.startsWith("0x"))this.keyId=new Uint8Array(Ar(n))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&Ur(t.keyFormatVersions,this.keyFormatVersions)&&bs(t.iv,this.iv)&&bs(t.keyId,this.keyId)}isSupported(){if(this.method){if(fe(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES"}return!1}getDecryptData(t,e){if(!this.encrypted||!this.uri)return null;if(fe(this.method)){let i=this.iv;if(!i){if(typeof t!=="number")st.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0;i=uo(t)}return new ve(this.method,this.uri,"identity",this.keyFormatVersions,i)}return this}}function uo(t){let e=new Uint8Array(16);for(let i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}var Is=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,_s=/#EXT-X-MEDIA:(.*)/g,co=/^#EXT(?:INF|-X-TARGETDURATION):/m,hi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ho=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Ot{static findGroup(t,e){for(let i=0;i<t.length;i++){let s=t[i];if(s.id===e)return s}}static resolve(t,e){return Bi.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return co.test(t)}static parseMasterPlaylist(t,e){let s={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},r=[];if(Is.lastIndex=0,!t.startsWith("#EXTM3U"))return s.playlistParsingError=Error("no EXTM3U delimiter"),s;let n;while((n=Is.exec(t))!=null)if(n[1]){let l=new nt(n[1],s),o=Ds(l,n[2],e,s,r);if(o)s.levels.push(o)}else if(n[3]){let l=n[3],o=n[4];switch(l){case"I-FRAME-STREAM-INF":{let u=new nt(o,s),d=Ds(u,u.URI,e,s,r,!0);if(d)s.iframeVariants.push(d)}break;case"SESSION-DATA":{let u=new nt(o,s),d=u["DATA-ID"];if(d){if(s.sessionData===null)s.sessionData={};s.sessionData[d]=u}break}case"SESSION-KEY":{let u=Cs(o,e,s);if(u.encrypted&&u.isSupported()){if(s.sessionKeys===null)s.sessionKeys=[];s.sessionKeys.push(u)}else st.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${o}"`);break}case"DEFINE":break;case"CONTENT-STEERING":{let u=new nt(o,s);s.contentSteering={uri:Ot.resolve(u["SERVER-URI"],e),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=Ps(o);break}}}let a=r.length>0&&r.length<s.levels.length;if(s.levels=a?r:s.levels,s.levels.length===0)s.playlistParsingError=Error("no levels found in manifest");return s}static parseMasterPlaylistMedia(t,e,i){let s,r={},n=i.levels,a={AUDIO:n.map((o)=>({id:o.attrs.AUDIO,audioCodec:o.audioCodec})),SUBTITLES:n.map((o)=>({id:o.attrs.SUBTITLES,textCodec:o.textCodec})),"CLOSED-CAPTIONS":[]},l=0;_s.lastIndex=0;while((s=_s.exec(t))!==null){let o=new nt(s[1],i),u=o.TYPE;if(u){let d=a[u],c=r[u]||[];r[u]=c;let h=o.LANGUAGE,f=o["ASSOC-LANGUAGE"],{CHANNELS:g,CHARACTERISTICS:m}=o,E=o["INSTREAM-ID"],y={attrs:o,bitrate:0,id:l++,groupId:o["GROUP-ID"]||"",name:o.NAME||h||"",type:u,default:o.bool("DEFAULT"),autoselect:o.bool("AUTOSELECT"),forced:o.bool("FORCED"),lang:h,url:o.URI?Ot.resolve(o.URI,e):""};if(f)y.assocLang=f;if(g)y.channels=g;if(m)y.characteristics=m;if(E)y.instreamId=E;if(d!=null&&d.length){let p=Ot.findGroup(d,y.groupId)||d[0];Os(y,p,"audioCodec"),Os(y,p,"textCodec")}c.push(y)}}return r}static parseLevelPlaylist(t,e,i,s,r,n){var a;let l={url:e},o=new Br(e),u=o.fragments,d=[],c=null,h=0,f=0,g=0,m=0,E=0,y=null,p=new ue(s,l),S,T,x,A=-1,b=!1,I=null,L;if(hi.lastIndex=0,o.m3u8=t,o.hasVariableRefs=!1,((a=hi.exec(t))==null?void 0:a[0])!=="#EXTM3U")return o.playlistParsingError=Error("Missing format identifier #EXTM3U"),o;while((S=hi.exec(t))!==null){if(b){if(b=!1,p=new ue(s,l),p.playlistOffset=g,p.setStart(g),p.sn=h,p.cc=m,E)p.bitrate=E;if(p.level=i,c){if(p.initSegment=c,c.rawProgramDateTime)p.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null;if(I)p.setByteRange(I),I=null}}let M=S[1];if(M){p.duration=parseFloat(M);let C=(" "+S[2]).slice(1);p.title=C||null,p.tagList.push(C?["INF",M,C]:["INF",M])}else if(S[3]){if(V(p.duration)){var _;if(p.playlistOffset=g,p.setStart(g),x)Fs(p,x,o);p.sn=h,p.level=i,p.cc=m;let C=(" "+S[3]).slice(1);p.relurl=C,Di(p,y,d),y=p,g+=p.duration,h++,f=0;let k=p.byteRange;if(k.length===2)p.bitrate=(k[1]-k[0])*8/p.duration|0;if(o.iframesOnly&&k[0]&&((_=c)==null?void 0:_.cc)!==m){let U=new ue(s,l);if(U.relurl=p.relurl,U.setByteRange(`${Math.min(k[0],1316)}@0`),U.level=i,U.sn="initSegment",x){if(U.levelkeys=x,x.identity)U._decryptdata=x.identity.getDecryptData(0)}c=U,p.initSegment=c}u.push(p),b=!0}}else{if(S=S[0].match(ho),!S){st.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T<S.length;T++)if(S[T]!==void 0)break;let C=(" "+S[T]).slice(1),k=(" "+S[T+1]).slice(1),U=S[T+2]?(" "+S[T+2]).slice(1):null;switch(C){case"BYTERANGE":if(y)p.setByteRange(k,y);else p.setByteRange(k);break;case"PROGRAM-DATE-TIME":if(p.rawProgramDateTime=k,p.tagList.push(["PROGRAM-DATE-TIME",k]),A===-1)A=u.length;break;case"PLAYLIST-TYPE":if(o.type)Bt(o,C,S);o.type=k.toUpperCase();break;case"MEDIA-SEQUENCE":if(o.startSN!==0)Bt(o,C,S);else if(y!==null)mo(o,C,S);o.startSN=parseInt(k),h=o.startSN+o.skippedSegments;break;case"SKIP":{if(o.skippedSegments)Bt(o,C,S);let D=new nt(k,o),G=D.decimalInteger("SKIPPED-SEGMENTS");if(V(G)){o.skippedSegments+=G;for(let N=G;N--;)u.push(null);h+=G}let F=D.enumeratedString("RECENTLY-REMOVED-DATERANGES");if(F)o.recentlyRemovedDateranges=(o.recentlyRemovedDateranges||[]).concat(F.split("\t"));break}case"TARGETDURATION":if(o.targetduration!==0)Bt(o,C,S);o.targetduration=Math.max(parseInt(k),1);break;case"VERSION":if(o.version!==null)Bt(o,C,S);o.version=parseInt(k);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":o.iframesOnly=!0;break;case"ENDLIST":if(!o.live)Bt(o,C,S);o.live=!1;break;case"#":if(k||U)p.tagList.push(U?[k,U]:[k]);break;case"DISCONTINUITY":m++,p.tagList.push(["DIS"]);break;case"GAP":p.gap=!0,p.tagList.push([C]);break;case"BITRATE":if(p.tagList.push([C,k]),E=parseInt(k)*1000,V(E))p.bitrate=E;else E=0;break;case"DATERANGE":{let D=new nt(k,o),G=new zi(D,o.dateRanges[D.ID],o.dateRangeTagCount);if(o.dateRangeTagCount++,G.isValid||o.skippedSegments)o.dateRanges[G.id]=G;else st.log(`Ignoring invalid DATERANGE tag: ${G.invalidReason}: ${k}`);p.tagList.push(["EXT-X-DATERANGE",k]);break}case"DEFINE":break;case"DISCONTINUITY-SEQUENCE":if(o.startCC!==0)Bt(o,C,S);o.startCC=m=parseInt(k),u.forEach((D)=>D&&(D.cc=m));break;case"KEY":{let D=Cs(k,e,o);if(D.isSupported()){if(D.method==="NONE"){x=void 0;break}if(!x)x={};let G=x[D.keyFormat];if(!(G!=null&&G.matches(D))){if(G)x=dt({},x);x[D.keyFormat]=D}}else st.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${k}" (light build)`);break}case"START":o.startTimeOffset=Ps(k);break;case"MAP":{let D=new nt(k,o);if(p.duration){let G=new ue(s,l);if(ws(G,D,i,x),c=G,p.initSegment=c,c.rawProgramDateTime&&!p.rawProgramDateTime)p.rawProgramDateTime=c.rawProgramDateTime}else{let G=p.byteRangeEndOffset;if(G){let F=p.byteRangeStartOffset;I=`${G-F}@${F}`}else I=null;ws(p,D,i,x),c=p,b=!0}c.cc=m;break}case"SERVER-CONTROL":{if(L)Bt(o,C,S);L=new nt(k),o.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),o.holdBack=L.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{if(o.partTarget)Bt(o,C,S);let D=new nt(k);o.partTarget=D.decimalFloatingPoint("PART-TARGET");break}case"PART":{let D=o.partList;if(!D)D=o.partList=[];let G=f>0?D[D.length-1]:void 0,F=f++,N=new nt(k,o),W=new fr(N,p,l,F,G);D.push(W),p.duration+=W.duration;break}case"PRELOAD-HINT":{let D=new nt(k,o);o.preloadHint=D;break}case"RENDITION-REPORT":{let D=new nt(k,o);o.renditionReports=o.renditionReports||[],o.renditionReports.push(D);break}default:st.warn(`line parsed but not handled: ${S}`);break}}}if(y&&!y.relurl){if(u.pop(),g-=y.duration,o.partList)o.fragmentHint=y}else if(o.partList){if(Di(p,y,d),p.cc=m,o.fragmentHint=p,x)Fs(p,x,o)}if(!o.targetduration)o.playlistParsingError=Error("Missing Target Duration");let P=u.length,O=u[0],H=u[P-1];if(g+=o.skippedSegments*o.targetduration,g>0&&P&&H){o.averagetargetduration=g/P;let M=H.sn;if(o.endSN=M!=="initSegment"?M:0,!o.live)H.endList=!0;if(A>0){if(go(u,A,A>P-1?p:null),O)d.unshift(O)}}if(o.fragmentHint)g+=o.fragmentHint.duration;if(o.totalduration=g,d.length&&o.dateRangeTagCount&&O)Vr(d,o);return o.endCC=m,o}}function Ds(t,e,i,s,r,n){var a;if(e===void 0)return null;let l=e,o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Ot.resolve(l,i)},u=t.decimalResolution("RESOLUTION");if(u)o.width=u.width,o.height=u.height;ks(t.CODECS,o);let d=t["SUPPLEMENTAL-CODECS"];if(d)o.supplemental={},ks(d,o.supplemental);if(!((a=o.unknownCodecs)!=null&&a.length))r.push(o);if(n)o.iframes=!0;return o}function Vr(t,e){let i=t.length;if(!i)if(e.hasProgramDateTime){let l=e.fragments[e.fragments.length-1];t.push(l),i++}else return;let s=t[i-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let l=n.length;l--;){let o=e.dateRanges[n[l]],u=o.startDate.getTime();o.tagAnchor=s.ref;for(let d=i;d--;){var a;if(((a=t[d])==null?void 0:a.sn)<e.startSN)break;let c=fo(e,u,t,d,r);if(c){o.tagAnchor=c.ref;break}}}}function fo(t,e,i,s,r){let n=i[s];if(n){let l=n.programDateTime;if(e>=l||s===0){var a;let o=(((a=i[s+1])==null?void 0:a.start)||r)-n.start;if(e<=l+o*1000){let u=n.sn-t.startSN,d=t.fragments;if(u>=0&&u<d.length){if(d.length>i.length){let c=i[s+1]||d[d.length-1],h=Math.min(c.sn-t.startSN,d.length-1);for(let f=h;f>u;f--){let g=d[f].programDateTime;if(e>=g&&e<g+d[f].duration*1000)return d[f]}}return d[u]}}}}return null}function Cs(t,e,i){var s,r;let n=new nt(t,i),a=(s=n.METHOD)!=null?s:"",l=n.URI,o=n.hexadecimalInteger("IV"),u=n.KEYFORMATVERSIONS,d=(r=n.KEYFORMAT)!=null?r:"identity";if(l&&n.IV&&!o)st.error(`Invalid IV: ${n.IV}`);let c=l?Ot.resolve(l,e):"",h=(u?u:"1").split("/").map(Number).filter(Number.isFinite);return new ve(a,c,d,h,o,n.KEYID)}function Ps(t){let i=new nt(t).decimalFloatingPoint("TIME-OFFSET");if(V(i))return i;return null}function ks(t,e){let i=(t||"").split(/[ ,]+/).filter((s)=>s);["video","audio","text","image"].forEach((s)=>{let r=i.filter((n)=>Wi(n,s));if(r.length)e[`${s}Codec`]=r.map((n)=>n.split("/")[0]).join(","),i=i.filter((n)=>r.indexOf(n)===-1)}),e.unknownCodecs=i}function Os(t,e,i){let s=e[i];if(s)t[i]=s}function go(t,e,i){if(i||(i=t[e]),!i)return;for(let s=e;s--;){let r=t[s];if(!r)return;r.programDateTime=i.programDateTime-r.duration*1000,i=r}}function Di(t,e,i){if(t.rawProgramDateTime)i.push(t);else if(e!=null&&e.programDateTime)t.programDateTime=e.endProgramDateTime}function ws(t,e,i,s){if(t.relurl=e.URI,e.BYTERANGE)t.setByteRange(e.BYTERANGE);if(t.level=i,t.sn="initSegment",s)t.levelkeys=s;t.initSegment=null}function Fs(t,e,i){t.levelkeys=e;let{encryptedFragments:s}=i;if((!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some((r)=>e[r].isCommonEncryption))s.push(t)}function Bt(t,e,i){t.playlistParsingError=Error(`#EXT-X-${e} must not appear more than once (${i[0]})`)}function mo(t,e,i){t.playlistParsingError=Error(`#EXT-X-${e} must appear before the first Media Segment (${i[0]})`)}function fi(t,e){let i=e.startPTS;if(V(i)){let s=0,r;if(e.sn>t.sn)s=i-t.start,r=t;else s=t.start-i,r=e;if(r.duration!==s)r.setDuration(s)}else if(e.sn>t.sn)if(t.cc===e.cc&&t.minEndPTS)e.setStart(t.start+(t.minEndPTS-t.start));else e.setStart(t.start+t.duration);else e.setStart(Math.max(t.start-e.duration,0))}function Kr(t,e,i,s,r,n,a,l){if(s-i<=0)l.warn("Fragment should have a positive duration",e),s=i+e.duration,n=r+e.duration;let u=i,d=s,{startPTS:c,endPTS:h}=e;if(V(c)){let p=Math.abs(c-i);if(t&&p>t.totalduration)l.warn(`media timestamps and playlist times differ by ${p}s for level ${e.level} ${t.url}`);else if(!V(e.deltaPTS))e.deltaPTS=p;else e.deltaPTS=Math.max(p,e.deltaPTS);u=Math.max(i,c),i=Math.min(i,c),r=e.startDTS!==void 0?Math.min(r,e.startDTS):r,d=Math.min(s,h),s=Math.max(s,h),n=e.endDTS!==void 0?Math.max(n,e.endDTS):n}let f=i-e.start;if(e.start!==0)e.setStart(i);e.setDuration(s-e.start),e.startPTS=i,e.maxStartPTS=u,e.startDTS=r,e.endPTS=s,e.minEndPTS=d,e.endDTS=n;let g=e.sn;if(!t||g<t.startSN||g>t.endSN)return 0;let m,E=g-t.startSN,y=t.fragments;y[E]=e;for(m=E;m>0;m--)fi(y[m],y[m-1]);for(m=E;m<y.length-1;m++)fi(y[m],y[m+1]);if(t.fragmentHint)fi(y[y.length-1],t.fragmentHint);return t.PTSKnown=t.alignedSliding=!0,f}function po(t,e,i){if(t===e)return;let s=null,r=t.fragments;for(let d=r.length-1;d>=0;d--){let c=r[d].initSegment;if(c){s=c;break}}if(t.fragmentHint)delete t.fragmentHint.endPTS;let n;yo(t,e,(d,c,h,f)=>{if((!e.startCC||e.skippedSegments)&&c.cc!==d.cc){let g=d.cc-c.cc;for(let m=h;m<f.length;m++)f[m].cc+=g;e.endCC=f[f.length-1].cc}if(V(d.startPTS)&&V(d.endPTS)){if(c.setStart(c.startPTS=d.startPTS),c.startDTS=d.startDTS,c.maxStartPTS=d.maxStartPTS,c.endPTS=d.endPTS,c.endDTS=d.endDTS,c.minEndPTS=d.minEndPTS,c.setDuration(d.endPTS-d.startPTS),c.duration)n=c;e.PTSKnown=e.alignedSliding=!0}if(d.hasStreams)c.elementaryStreams=d.elementaryStreams;if(c.loader=d.loader,d.hasStats)c.stats=d.stats;if(d.initSegment)c.initSegment=d.initSegment,s=d.initSegment});let a=e.fragments,l=e.fragmentHint?a.concat(e.fragmentHint):a;if(s)l.forEach((d)=>{var c;if(d&&(!d.initSegment||d.initSegment.relurl===((c=s)==null?void 0:c.relurl)))d.initSegment=s});if(e.skippedSegments){if(e.deltaUpdateFailed=a.some((d)=>!d),e.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let d=e.skippedSegments;d--;)a.shift();e.startSN=a[0].sn}else{if(e.canSkipDateRanges)e.dateRanges=Eo(t.dateRanges,e,i);let d=t.fragments.filter((c)=>c.rawProgramDateTime);if(t.hasProgramDateTime&&!e.hasProgramDateTime){for(let c=1;c<l.length;c++)if(l[c].programDateTime===null)Di(l[c],l[c-1],d)}Vr(d,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var o;let d=Yr(t,e.startSN-1);e.startCC=(o=d==null?void 0:d.cc)!=null?o:a[0].cc}if(vo(t.partList,e.partList,(d,c)=>{c.elementaryStreams=d.elementaryStreams,c.stats=d.stats,c.gap=d.gap||c.gap}),n){let d=e.iframesOnly&&n.type===Q.MAIN;Kr(e,n,n.startPTS,n.endPTS,n.startDTS,n.endDTS,d,i)}else Hr(t,e);if(a.length)e.totalduration=e.edge-a[0].start;e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;let u=e.advancedDateTime;if(e.advanced&&u){let d=e.edge;if(!e.driftStart)e.driftStartTime=u,e.driftStart=d;e.driftEndTime=u,e.driftEnd=d}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime;if(e.requestScheduled===-1)e.requestScheduled=t.requestScheduled}function Eo(t,e,i){let{dateRanges:s,recentlyRemovedDateranges:r}=e,n=dt({},t);if(r)r.forEach((o)=>{delete n[o]});let l=Object.keys(n).length;if(!l)return s;return Object.keys(s).forEach((o)=>{let u=n[o],d=new zi(s[o].attr,u);if(d.isValid){if(n[o]=d,!u)d.tagOrder+=l}else i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${yt(s[o].attr)}"`)}),n}function vo(t,e,i){if(t&&e){let s=0;for(let r=0,n=t.length;r<n;r++){let a=t[r],l=e[r+s];if(a&&l&&a.index===l.index&&a.fragment.sn===l.fragment.sn)i(a,l);else s--}}}function yo(t,e,i){var s;let r=e.skippedSegments,n=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,l=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,u=(s=t.fragmentHint)!=null&&s.duration?t.fragments.concat(t.fragmentHint):t.fragments;for(let d=n;d<=a;d++){let c=u[l+d],h=o[d];if(r&&!h&&c)h=e.fragments[d]=c;if(c&&h){i(c,h,d,o);let f=c.relurl,g=h.relurl;if(f&&To(f,g)){e.playlistParsingError=Ms(`media sequence mismatch ${h.sn}:`,t,e,c,h);return}else if(c.cc!==h.cc){e.playlistParsingError=Ms(`discontinuity sequence mismatch (${c.cc}!=${h.cc})`,t,e,c,h);return}}}}function Ms(t,e,i,s,r){return Error(`${t} ${r.url}
|
|
12
|
+
Playlist starting @${e.startSN}
|
|
13
|
+
${e.m3u8}
|
|
14
|
+
|
|
15
|
+
Playlist starting @${i.startSN}
|
|
16
|
+
${i.m3u8}`)}function Hr(t,e,i=!0,s){let r=e.startSN+e.skippedSegments-t.startSN,n=t.fragments,a=r>=0,l=0;if(a&&r<n.length)l=n[r].start,s==null||s.log(`Aligning playlists based on SN ${e.startSN} (diff: ${l})`);else if(a&&e.startSN===t.endSN+1)l=t.fragmentEnd,s==null||s.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${l})`);else if(a&&i)l=t.fragmentStart+r*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)l=t.fragmentStart,s==null||s.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${l})`);else return l;return So(e,l),l}function So(t,e){if(e){let i=t.fragments;for(let s=t.skippedSegments;s<i.length;s++)i[s].addStart(e);if(t.fragmentHint)t.fragmentHint.addStart(e)}}function Wr(t,e=1/0){let i=1000*t.targetduration;if(t.updated){let s=t.fragments,r=4;if(s.length&&i*4>e){let n=s[s.length-1].duration*1000;if(n>0&&n<i)i=n}}else i/=2;return Math.round(i)}function Yr(t,e,i){var s;if(!t)return null;let r=t.fragments[e-t.startSN];if(r)return r;if(r=t.fragmentHint,((s=r)==null?void 0:s.sn)===e)return r;if(i&&e<t.startSN&&i.sn===e)return i;return null}function Ns(t,e,i){if(!t)return null;return jr(t.partList,e,i)}function jr(t,e,i){if(t)for(let s=t.length;s--;){let r=t[s];if(r.index===i&&r.fragment.sn===e)return r}return null}function qr(t){t.forEach((e,i)=>{var s;(s=e.details)==null||s.fragments.forEach((r)=>{if(r.level=i,r.initSegment)r.initSegment.level=i})})}function To(t,e){if(t!==e&&e)return $s(t)!==$s(e);return!1}function $s(t){return t.replace(/\?[^?]*$/,"")}class zr extends wt{constructor(t,e){super(e,t.logger);this.hls=void 0,this.canLoad=!1,this.timer=-1,this.loadingSync=!1,this.hls=t}destroy(){this.clearTimer(),this.hls=null}clearTimer(){if(this.timer!==-1)self.clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e,i){let s=e==null?void 0:e.renditionReports;if(s){let r=-1;for(let n=0;n<s.length;n++){let a=s[n],l;try{l=new self.URL(a.URI,e.url).href}catch(o){this.warn(`Could not construct new URL for Rendition Report: ${o}`),l=a.URI||""}if(l===t){r=n;break}else if(l===t.substring(0,l.length))r=n}if(r!==-1){let n=s[r],a=parseInt(n["LAST-MSN"])||e.lastPartSn,l=parseInt(n["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){let u=Math.min(e.age-e.partTarget,e.targetduration);if(l>=0&&u>e.partTarget)l+=1}let o=i&&Ss(i);return new _i(a,l>=0?l:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(i){this.warn(`Could not construct new URL with HLS Delivery Directives: ${i}`)}return t}playlistLoaded(t,e,i){let{details:s,stats:r}=e,n=s.fragments,a=self.performance.now(),l=r.loading.first?Math.max(0,Math.floor(a-r.loading.first)):0;s.advancedDateTime=Date.now()-l;let o=this.hls.config.timelineOffset;if(o!==s.appliedTimelineOffset){let d=Math.max(o||0,0);s.appliedTimelineOffset=d,n.forEach((c)=>{c==null||c.setStart(c.playlistOffset+d)})}if(s.live||i!=null&&i.live){var u;let d="levelInfo"in e?e.levelInfo:e.track;s.reloaded(i);let c=(u=n[n.length-1])==null?void 0:u.type;if(s.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){let T=Error(`${c} playlist ${d.id} hit max allowed unchanged reloads.`);this.warn(T);let{networkDetails:x,context:A}=e;this.hls.trigger(v.ERROR,{type:q.NETWORK_ERROR,details:R.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:s.url,error:T,reason:T.message,level:e.level,parent:c,context:A,networkDetails:x,stats:r});return}if(i){po(i,s,this);let T=s.playlistParsingError;if(T){this.warn(T);let x=this.hls;if(!x.config.ignorePlaylistParsingErrors){let{networkDetails:A}=e;x.trigger(v.ERROR,{type:q.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:T,reason:T.message,level:e.level,parent:c,networkDetails:A,stats:r});return}s.playlistParsingError=null}}if(s.requestScheduled===-1)s.requestScheduled=r.loading.start;let h=this.hls.mainForwardBufferInfo,f=h?h.end-h.len:0,g=(s.edge-f)*1000,m=Wr(s,g);if(s.requestScheduled+m<a)s.requestScheduled=a;else if(s.requestScheduled<=a)s.requestScheduled+=m;let E=e.deliveryDirectives;if(this.log(`live playlist ${t} ${s.advanced?`REFRESHED ${s.lastPartSn} - ${s.lastPartIndex}`:s.updated?"UPDATED":`MISSED (received ${s.lastPartSn} - ${s.lastPartIndex}${E?` | requested ${E.msn} - ${E.part}`:""})`}`),!this.canLoad||!s.live)return;let y,p=void 0,S=void 0;if(s.canBlockReload&&s.advanced){let T=this.hls.config.lowLatencyMode,{lastPartSn:x,endSN:A,lastPartIndex:b}=s,I=b!==-1,L=x===A;if(I)if(L)p=A+1,S=T?0:b;else p=x,S=T?b+1:s.maxPartIndex;else p=A+1;let _=s.age,P=_+s.ageHeader,O=Math.min(P-s.partTarget,s.targetduration*1.5);if(O>0){if(P>s.targetduration*3)this.log(`Playlist last advanced ${_.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,S=void 0;else if(i!=null&&i.tuneInGoal&&P-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${O} with playlist age: ${s.age}`),O=0;else{let H=Math.floor(O/s.targetduration);if(p+=H,S!==void 0){let M=Math.round(O%s.targetduration/s.partTarget);S+=M}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${_.toFixed(2)}s goal: ${O} skip sn ${H} to part ${S}`)}s.tuneInGoal=O}if(y=this.getDeliveryDirectives(s,e.deliveryDirectives,p,S),T||!L){s.requestScheduled=a,this.loadingPlaylist(d,y);return}}else if(s.canBlockReload||s.canSkipUntil)y=this.getDeliveryDirectives(s,e.deliveryDirectives,p,S);if(y&&p!==void 0&&s.canBlockReload)s.requestScheduled=r.loading.first+Math.max(m-l*2,m/2);this.scheduleLoading(d,y,s)}else this.clearTimer()}scheduleLoading(t,e,i){let s=i||t.details;if(!s){this.loadingPlaylist(t,e);return}let r=self.performance.now(),n=s.requestScheduled;if(r>=n&&!this.loadingSync){this.loadingSync=!0,this.loadingPlaylist(t,e),this.loadingSync=!1;return}let a=Math.max(n-r,0);this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,i,s){let r=Ss(t);if(e!=null&&e.skip&&t.deltaUpdateFailed)i=e.msn,s=e.part,r=Ne.No;return new _i(i,s,r)}checkRetry(t){let e=t.details,i=Ge(t),s=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},l=!!s&&!!a&&(r===ht.RetryRequest||!s.resolved&&r===ht.SendAlternateToPenaltyBox);if(l){var o;if(n>=a.maxNumRetry)return!1;if(i&&(o=t.context)!=null&&o.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{var u;let d=pe((u=t.response)==null?void 0:u.code);if(this.clearTimer(),d)this.log("Waiting for connection (offline)"),t.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1000);else{let c=Vi(a,n);this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${c}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),c)}}t.levelRetry=!0,s.resolved=!0}return l}checkOfflineStatus(){if(this.clearTimer(),pe(0))this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1000);else this.log("Connection restored (online)"),this.loadPlaylist()}}var mt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Xr{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=0.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){let{hls:t}=this;if(t)t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.BUFFER_APPENDED,this.onBufferAppended,this),t.on(v.FRAG_BUFFERED,this.onFragBuffered,this),t.on(v.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){let{hls:t}=this;if(t)t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.BUFFER_APPENDED,this.onBufferAppended,this),t.off(v.FRAG_BUFFERED,this.onFragBuffered,this),t.off(v.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){let i=this.activePartLists[e];if(i)for(let s=i.length;s--;){let r=i[s];if(!r)break;if(r.start<=t&&t<=r.end&&r.loaded)return r}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,i){let{fragments:s}=this,r=Object.keys(s);for(let n=r.length;n--;){let a=s[r[n]];if((a==null?void 0:a.body.type)===e&&(!i||a.buffered)){let l=a.body;if(l.start<=t&&t<=l.end)return l}}return null}detectEvictedFragments(t,e,i,s,r,n){if(this.timeRanges)this.timeRanges[t]=e;let a=(r==null?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach((l)=>{let o=this.fragments[l];if(!o||!this.hls)return;let u=o.body;if(a>=u.sn)return;if(!o.buffered&&(!o.loaded||n)){if(u.type===i)this.removeFragment(u);return}let d=o.range[t];if(!d)return;if(d.time.length===0){this.removeFragment(u);return}if(d.time.some((c)=>{let h=!this.isTimeBuffered(c.startPTS,c.endPTS,e);if(h)this.removeFragment(u);return h}),s&&s!==u&&he()){let c=s.endPTS,h=u.startPTS;if(c&&h&&o.range.video){let f=h-c;if(f<0&&f>-0.1)this.removeFragment(u),this.hls.trigger(v.BUFFER_FLUSHING,{startOffset:c+0.004,endOffset:1/0,type:"video"})}}})}detectPartialFragments(t){let e=this.timeRanges,{frag:i,part:s,id:r}=t;if(!e||!St(i))return;let n=te(i),a=this.fragments[n];if(!a||a.buffered&&i.gap)return;let l=!i.relurl;Object.keys(e).forEach((u)=>{let d=i.elementaryStreams[u];if(!d)return;let c=e[u],h=l||d.partial===!0;a.range[u]=this.getBufferedTimes(i,s,h,c),this.detectEvictedFragments(u,c,r,i,s)}),a.loaded=null;let o=Object.keys(a.range);if(o.length){if(this.bufferedEnd(a,i),!Ce(a))this.removeParts(i.sn-1,i.type);if(!s){let u=Math.min(0.004,i.duration);o.some((d)=>{var c;let h=(c=a.range[d])==null?void 0:c.time,f=h.length===0||h.length===1&&h[0].endPTS-h[0].startPTS<u;if(f)this.addAsGap(i);return f})}}else this.removeFragment(i)}addAsGap(t){t.gap=!0,this.removeFragment(t),this.fragBuffered(t,!0)}bufferedEnd(t,e){if(t.buffered=!0,(t.body.endList=e.endList||t.body.endList)&&!e.gap)this.endListFragments[t.body.type]=t}removeParts(t,e){let i=this.activePartLists[e];if(!i)return;this.activePartLists[e]=Bs(i,(s)=>s.fragment.sn>=t)}fragBuffered(t,e){let i=te(t),s=this.fragments[i];if(!s&&e){if(s=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap)this.hasGaps=!0}if(s)s.loaded=null,this.bufferedEnd(s,t);return s}getBufferedTimes(t,e,i,s){let r={time:[],partial:i},{start:n,end:a}=t,l=t.minEndPTS||a,o=t.maxStartPTS||n;for(let u=0;u<s.length;u++){let d=s.start(u)-this.bufferPadding,c=s.end(u)+this.bufferPadding;if(o>=d&&l<=c){r.time.push({startPTS:Math.max(n,s.start(u)),endPTS:Math.min(a,s.end(u))});break}else if(n<c&&a>d){let h=Math.max(n,s.start(u)),f=Math.min(a,s.end(u));if(f>h)r.partial=!0,r.time.push({startPTS:h,endPTS:f})}else if(a<=d)break}return r}getPartialFragment(t){let e=null,i,s,r,n=0,{bufferPadding:a,fragments:l}=this;return Object.keys(l).forEach((o)=>{let u=l[o];if(!u)return;if(Ce(u)){if(s=u.body.start-a,r=u.body.end+a,t>=s&&t<=r){if(i=Math.min(t-s,r-t),n<=i)e=u.body,n=i}}}),e}isEndListAppended(t){let e=this.endListFragments[t];return e!==void 0&&(e.buffered||Ce(e))}getState(t){let e=te(t),i=this.fragments[e];if(i)if(!i.buffered)return mt.APPENDING;else if(Ce(i))return mt.PARTIAL;else return mt.OK;return mt.NOT_LOADED}isTimeBuffered(t,e,i){let s,r;for(let n=0;n<i.length;n++){if(s=i.start(n)-this.bufferPadding,r=i.end(n)+this.bufferPadding,t>=s&&e<=r)return!0;if(e<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if(!St(e.frag)||e.frag.bitrateTest)return;let i=e.frag,s=e.part?null:e,r=te(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){let{frag:i,part:s,timeRanges:r}=e;if(!St(i))return;let n=i.type;if(s){let a=this.activePartLists[n];if(!a)this.activePartLists[n]=a=[];a.push(s)}this.timeRanges=r}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){let e=te(t);return!!this.fragments[e]}hasFragments(t){let{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let s=i.length;s--;){let r=e[i[s]];if((r==null?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!!((e=this.activePartLists[t])!=null&&e.length)}getBackBufferEvictionEnd(t,e,i){let{fragments:s}=this,r=0,n=0,a=Object.keys(s);for(let l=0;l<a.length;l++){let o=s[a[l]];if(!o||!o.buffered||o.body.type!==e)continue;let u=o.body;if(u.gap)return 0;let d=u.hasStats&&u.stats.loaded||u.byteLength||u.bitrate&&u.bitrate*8*u.duration;if(u.end<=t&&d){if(r+=d,n=Math.max(n,u.end),r>=i)return n}}return n>0?n:0}removeFragmentsInRange(t,e,i,s,r){if(s&&!this.hasGaps)return;Object.keys(this.fragments).forEach((n)=>{let a=this.fragments[n];if(!a)return;let l=a.body;if(l.type!==i||s&&!l.gap)return;if(l.start<e&&l.end>t&&(a.buffered||r))this.removeFragment(l)})}removeFragment(t){let e=te(t);t.clearElementaryStreamInfo();let i=this.activePartLists[t.type];if(i){let s=t.sn;this.activePartLists[t.type]=Bs(i,(r)=>r.fragment.sn!==s)}if(delete this.fragments[e],t.endList)delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let e=(t=this.hls)==null||(t=t.latestLevelDetails)==null?void 0:t.partList;if(e)e.forEach((i)=>i.clearElementaryStreamInfo())}}function Ce(t){var e,i,s,r;return t.buffered&&!!(t.body.gap||(e=t.range.video)!=null&&e.partial||(i=t.range.audio)!=null&&i.partial||(s=t.range.audiovideo)!=null&&s.partial||(r=t.range.subs)!=null&&r.partial)}function te(t){return`${t.type}_${t.level}_${t.sn}`}function Bs(t,e){return t.filter((i)=>{let s=e(i);if(!s)i.clearElementaryStreamInfo();return s})}class Qr{constructor(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}decrypt(t,e){switch(this.aesMode){case qt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case qt.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function xo(t){let e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);if(i)return t.slice(0,e-i);return t}class Zr{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){let e=new DataView(t),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=e.getUint32(s*4);return i}initTable(){let t=this.sBox,e=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],a=i[3],l=this.invSubMix,o=l[0],u=l[1],d=l[2],c=l[3],h=new Uint32Array(256),f=0,g=0,m=0;for(m=0;m<256;m++)if(m<128)h[m]=m<<1;else h[m]=m<<1^283;for(m=0;m<256;m++){let E=g^g<<1^g<<2^g<<3^g<<4;E=E>>>8^E&255^99,t[f]=E,e[E]=f;let y=h[f],p=h[y],S=h[p],T=h[E]*257^E*16843008;if(s[f]=T<<24|T>>>8,r[f]=T<<16|T>>>16,n[f]=T<<8|T>>>24,a[f]=T,T=S*16843009^p*65537^y*257^f*16843008,o[E]=T<<24|T>>>8,u[E]=T<<16|T>>>16,d[E]=T<<8|T>>>24,c[E]=T,!f)f=g=1;else f=y^h[h[h[S^y]]],g^=h[h[g]]}}expandKey(t){let e=this.uint8ArrayToUint32Array_(t),i=!0,s=0;while(s<e.length&&i)i=e[s]===this.key[s],s++;if(i)return;this.key=e;let r=this.keySize=e.length;if(r!==4&&r!==6&&r!==8)throw Error("Invalid aes key size="+r);let n=this.ksRows=(r+6+1)*4,a,l,o=this.keySchedule=new Uint32Array(n),u=this.invKeySchedule=new Uint32Array(n),d=this.sBox,c=this.rcon,h=this.invSubMix,f=h[0],g=h[1],m=h[2],E=h[3],y,p;for(a=0;a<n;a++){if(a<r){y=o[a]=e[a];continue}if(p=y,a%r===0)p=p<<8|p>>>24,p=d[p>>>24]<<24|d[p>>>16&255]<<16|d[p>>>8&255]<<8|d[p&255],p^=c[a/r|0]<<24;else if(r>6&&a%r===4)p=d[p>>>24]<<24|d[p>>>16&255]<<16|d[p>>>8&255]<<8|d[p&255];o[a]=y=(o[a-r]^p)>>>0}for(l=0;l<n;l++){if(a=n-l,l&3)p=o[a];else p=o[a-4];if(l<4||a<=4)u[l]=p;else u[l]=f[d[p>>>24]]^g[d[p>>>16&255]]^m[d[p>>>8&255]]^E[d[p&255]];u[l]=u[l]>>>0}}networkToHostOrderSwap(t){return t<<24|(t&65280)<<8|(t&16711680)>>8|t>>>24}decrypt(t,e,i){let s=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,l=a[0],o=a[1],u=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(i),h=c[0],f=c[1],g=c[2],m=c[3],E=new Int32Array(t),y=new Int32Array(E.length),p,S,T,x,A,b,I,L,_,P,O,H,M,C,k=this.networkToHostOrderSwap;while(e<E.length){_=k(E[e]),P=k(E[e+1]),O=k(E[e+2]),H=k(E[e+3]),A=_^r[0],b=H^r[1],I=O^r[2],L=P^r[3],M=4;for(C=1;C<s;C++)p=l[A>>>24]^o[b>>16&255]^u[I>>8&255]^d[L&255]^r[M],S=l[b>>>24]^o[I>>16&255]^u[L>>8&255]^d[A&255]^r[M+1],T=l[I>>>24]^o[L>>16&255]^u[A>>8&255]^d[b&255]^r[M+2],x=l[L>>>24]^o[A>>16&255]^u[b>>8&255]^d[I&255]^r[M+3],A=p,b=S,I=T,L=x,M=M+4;p=n[A>>>24]<<24^n[b>>16&255]<<16^n[I>>8&255]<<8^n[L&255]^r[M],S=n[b>>>24]<<24^n[I>>16&255]<<16^n[L>>8&255]<<8^n[A&255]^r[M+1],T=n[I>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[b&255]^r[M+2],x=n[L>>>24]<<24^n[A>>16&255]<<16^n[b>>8&255]<<8^n[I&255]^r[M+3],y[e]=k(p^h),y[e+1]=k(x^f),y[e+2]=k(T^g),y[e+3]=k(S^m),h=_,f=P,g=O,m=H,e=e+4}return y.buffer}}class Jr{constructor(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}expandKey(){let t=Ao(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}function Ao(t){switch(t){case qt.cbc:return"AES-CBC";case qt.ctr:return"AES-CTR";default:throw Error(`[FastAESKey] invalid aes mode ${t}`)}}var Lo=16;class ti{constructor(t,e){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,e!==!0)try{let i=self.crypto;if(i)this.subtle=i.subtle||i.webkitSubtle}catch(i){}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(){let{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;let i=new Uint8Array(t);this.reset();let s=this.decryptRange;if(s){if(s.start===0&&s.end>=i.length)return i;return i.slice(s.start,s.end)}return xo(i)}reset(){if(this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter)this.softwareDecrypter=null}decrypt(t,e,i,s,r){if(this.decryptRange=r,this.useSoftware||r)return new Promise((n,a)=>{let l=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(l,e,i,s);let o=this.flush();if(o)n(o.buffer);else a(Error("[softwareDecrypt] Failed to decrypt data"))});return this.webCryptoDecrypt(new Uint8Array(t),e,i,s)}softwareDecrypt(t,e,i,s){let{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==qt.cbc||e.byteLength!==16)return st.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;if(this.logOnce("JS AES decrypt"),a)t=It(a,t),this.remainderData=null;let l=this.getValidChunk(t);if(!l.length)return null;if(r)i=r;let o=this.softwareDecrypter;if(!o)o=this.softwareDecrypter=new Zr;o.expandKey(e);let u=n;if(this.currentResult=o.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,!u)return null;return u}webCryptoDecrypt(t,e,i,s){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,s));this.key=e,this.fastAesKey=new Jr(this.subtle,e,s)}return this.fastAesKey.expandKey().then((r)=>{if(!this.subtle)return Promise.reject(Error("web crypto not initialized"));return this.logOnce("WebCrypto AES decrypt"),new Qr(this.subtle,new Uint8Array(i),s).decrypt(t.buffer,r)}).catch((r)=>(st.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,i,s)))}onWebCryptoError(t,e,i,s){let r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,s);let n=this.flush();if(n)return n.buffer}throw Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t,i=t.length-t.length%Lo;if(i!==t.length)e=t.slice(0,i),this.remainderData=t.slice(i);return e}logOnce(t){if(!this.logEnabled)return;st.log(`[decrypter]: ${t}`),this.logEnabled=!1}}var Us=Math.pow(2,17);class Ci{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){if(this.loader)this.loader.destroy(),this.loader=null}abort(){if(this.loader)this.loader.abort()}load(t,e,i,s){let r=t.url;if(!r)return Promise.reject(new Rt({type:q.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();let n=this.config,{fLoader:a,loader:l}=n;return new Promise((o,u)=>{if(this.loader)this.loader.destroy();if(t.gap)if(t.tagList.some((m)=>m[0]==="GAP")){u(Vs(t));return}else t.gap=!1;let d=this.loader=a?new a(n):new l(n),c=Gs(t,null,e);t.loader=d;let h=cs(n.fragLoadPolicy.default),f={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:Us};d.stats.retry=t.stats.retry,t.stats=d.stats;let g={onSuccess:(m,E,y,p)=>{this.resetLoader(t,d);let S=m.data;if(y.resetIV&&t.decryptdata)t.decryptdata.iv=new Uint8Array(S.slice(0,16)),S=S.slice(16);o({frag:t,part:null,payload:S,networkDetails:p})},onError:(m,E,y,p)=>{this.resetLoader(t,d),u(new Rt({type:q.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:Tt({url:r,data:void 0},m),error:Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:y,stats:p}))},onAbort:(m,E,y)=>{this.resetLoader(t,d),u(new Rt({type:q.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:t,error:Error("Aborted"),networkDetails:y,stats:m}))},onTimeout:(m,E,y)=>{this.resetLoader(t,d),u(new Rt({type:q.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:Error(`Timeout after ${f.timeout}ms`),networkDetails:y,stats:m}))}};if(i){let m=this.gateProgress(i,s);g.onProgress=(E,y,p,S)=>m({frag:t,part:null,payload:p,networkDetails:S})}d.load(c,f,g)})}gateProgress(t,e){let i=t;if(e){let s=[],r=!1;e.then(()=>{r=!0,s.forEach((n)=>t(n)),s.length=0}).catch(()=>{}),i=(n)=>{if(r)t(n);else s.push(n)}}return i}loadPart(t,e,i){this.abort();let s=this.config,{fLoader:r,loader:n}=s;return new Promise((a,l)=>{if(this.loader)this.loader.destroy();if(t.gap||e.gap){l(Vs(t,e));return}let o=this.loader=r?new r(s):new n(s),u=Gs(t,e);t.loader=o;let d=cs(s.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Us};e.stats=o.stats,o.load(u,c,{onSuccess:(h,f,g,m)=>{this.resetLoader(t,o),this.updateStatsFromPart(t,e);let E={frag:t,part:e,payload:h.data,networkDetails:m};i(E),a(E)},onError:(h,f,g,m)=>{this.resetLoader(t,o),l(new Rt({type:q.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:Tt({url:u.url,data:void 0},h),error:Error(`HTTP Error ${h.code} ${h.text}`),networkDetails:g,stats:m}))},onAbort:(h,f,g)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,o),l(new Rt({type:q.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:Error("Aborted"),networkDetails:g,stats:h}))},onTimeout:(h,f,g)=>{this.resetLoader(t,o),l(new Rt({type:q.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:Error(`Timeout after ${c.timeout}ms`),networkDetails:g,stats:h}))}})})}updateStatsFromPart(t,e){let i=t.stats,s=e.stats,r=s.total;if(i.loaded+=s.loaded,r){let l=Math.round(t.duration/e.duration),o=Math.min(Math.round(i.loaded/r),l),d=(l-o)*Math.round(i.loaded/o);i.total=i.loaded+d}else i.total=Math.max(i.loaded,i.total);let n=i.loading,a=s.loading;if(n.start)n.first+=a.first-a.start;else n.start=a.start,n.first=a.first;n.end=a.end}resetLoader(t,e){if(t.loader=null,t.url=null,this.loader===e)self.clearTimeout(this.partLoadTimeout),this.loader=null;e.destroy()}}function Gs(t,e=null,i){let s=e||t,r={type:J.MEDIA_FRAGMENT,frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},n=je(t,e,i);if(n.resetIV)r.resetIV=!0;if(n.byteRange)r.rangeStart=n.byteRange.start,r.rangeEnd=n.byteRange.end;return r}function je(t,e=null,i){let s={},r=e||t,{byteRangeStartOffset:n,byteRangeEndOffset:a}=r;if(V(n)&&V(a)){var l;if((t.sn==="initSegment"||i)&&Ro((l=t.decryptdata)==null?void 0:l.method)){let o=Math.floor(n/16)*16,u=Math.ceil(a/16)*16;if(s.decryptRange={start:n-o,end:a-o},o>=16)s.resetIV=!0,o=o-16;s.byteRange={start:o,end:u}}else s.byteRange={start:n,end:a}}return s}function Vs(t,e){let i=Error(`GAP ${t.gap?"tag":"attribute"} found`),s={type:q.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};if(e)s.part=e;return(e?e:t).stats.aborted=!0,new Rt(s)}function Ro(t){return t==="AES-128"||t==="AES-256"}class Rt extends Error{constructor(t){super(t.error.message);this.data=void 0,this.data=t}}class Xi extends wt{constructor(t,e){super(t,e);this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){if(!this._tickInterval)return this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0;return!1}clearInterval(){if(this._tickInterval)return self.clearInterval(this._tickInterval),this._tickInterval=null,!0;return!1}clearNextTick(){if(this._tickTimer)return self.clearTimeout(this._tickTimer),this._tickTimer=null,!0;return!1}tick(){if(this._tickCallCount++,this._tickCallCount===1){if(this.doTick(),this._tickCallCount>1)this.tickImmediate();this._tickCallCount=0}else this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Qi{constructor(t,e,i,s=0,r=-1,n=!1,a,l,o){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=Pe(),this.buffering={audio:Pe(),video:Pe(),audiovideo:Pe()},this.level=t,this.sn=e,this.id=i,this.size=s,this.part=r,this.partial=n,this.duration=a||0,this.decryptRange=o,this.iframe=l||!1}}function Pe(){return{start:0,executeStart:0,executeEnd:0,end:0}}var Ks={length:0,start:()=>0,end:()=>0};class j{static isBuffered(t,e){if(t){let i=j.getBuffered(t);for(let s=i.length;s--;)if(e>=i.start(s)&&e<=i.end(s))return!0}return!1}static bufferedRanges(t){if(t){let e=j.getBuffered(t);return j.timeRangesToArray(e)}return[]}static timeRangesToArray(t){let e=[];for(let i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e}static bufferInfo(t,e,i){if(t){let s=j.bufferedRanges(t);if(s.length)return j.bufferedInfo(s,e,i)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,i){if(e=Math.max(0,e),t.length>1)t.sort((u,d)=>u.start-d.start||d.end-u.end);let s=-1,r=[];if(i)for(let u=0;u<t.length;u++){if(e>=t[u].start&&e<=t[u].end)s=u;let d=r.length;if(d){let c=r[d-1].end;if(t[u].start-c<i){if(t[u].end>c)r[d-1].end=t[u].end}else r.push(t[u])}else r.push(t[u])}else r=t;let n=0,a,l=e,o=e;for(let u=0;u<r.length;u++){let d=r[u].start,c=r[u].end;if(s===-1&&e>=d&&e<=c)s=u;if(e+i>=d&&e<c)l=d,o=c,n=o-e;else if(e+i<d){a=d;break}}return{len:n,start:l||0,end:o||0,nextStart:a,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||Ks}catch(e){return st.log("failed to get media.buffered",e),Ks}}}function ge(t,e){for(let s=0,r=t.length;s<r;s++){var i;if(((i=t[s])==null?void 0:i.cc)===e)return t[s]}return null}function bo(t,e){if(t){if(e.startCC<t.endCC&&e.endCC>t.startCC)return!0}return!1}function Hs(t,e){let i=t.start+e;t.setStart(i)}function tn(t,e){let i=e.fragments;for(let s=0,r=i.length;s<r;s++)Hs(i[s],t);if(e.fragmentHint)Hs(e.fragmentHint,t);e.alignedSliding=!0}function Io(t,e,i){if(!t)return;if(_o(e,t,i),!e.alignedSliding)Do(e,t,i);if(!e.alignedSliding&&!e.skippedSegments)Hr(t,e,!1,i)}function _o(t,e,i){if(!bo(e,t))return;let s=Math.min(e.endCC,t.endCC),r=ge(e.fragments,s),n=ge(t.fragments,s);if(!r||!n)return;let a=r.start-n.start;i.log(`Aligning playlists using dicontinuity sequence ${s} (diff: ${a})`),tn(a,t)}function Do(t,e,i){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;let s=t.fragments,r=e.fragments;if(!s.length||!r.length)return;let n,a,l=Math.min(e.endCC,t.endCC);if(e.startCC<l&&t.startCC<l)n=ge(r,l),a=ge(s,l);if(!n||!a)n=r[Math.floor(r.length/2)]||r.filter((h)=>!!h)[0],a=ge(s,n.cc)||s[Math.floor(s.length/2)];let o=n.programDateTime,u=a.programDateTime;if(!o||!u)return;let d=(u-o)/1000;if(Math.abs(d)>Math.max(60,t.totalduration)){i.log(`Cannot align playlists using PDT without overlap (${Math.abs(d)} > ${t.totalduration})`);return}let c=d-(a.start-n.start);i.log(`Aligning playlists using PDT (diff: ${c})`),tn(c,t)}function pt(t,e,i){ut(t,e,i),t.addEventListener(e,i)}function ut(t,e,i){t.removeEventListener(e,i)}function Pi(t){let e="",i=t.length;for(let s=0;s<i;s++)e+=`[${t.start(s).toFixed(3)}-${t.end(s).toFixed(3)}]`;return e}var w={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_LEVEL:"WAITING_LEVEL"};class en extends Xi{constructor(t,e,i,s,r){super(s,t.logger);this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=w.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:n,fragCurrent:a,media:l,mediaBuffer:o,state:u}=this,d=l?l.currentTime:0,c=j.bufferInfo(o?o:l,d,n.maxBufferHole),h=c.len;if(this.log(`Media seeking to ${d}, state: ${u}, ${!h?"out of":"in"} buffer`),this.state===w.ENDED)this.resetLoadingState();else if(a){let g=n.maxFragLookUpTolerance,m=a.start-g,E=a.start+a.duration+g;if(!h||E<c.start||m>c.end){let y=d<m,p=d>E;if(y||p)if(a.loader&&(p||!this.isFragmentNearlyDownloaded(a)))this.log(`Cancelling fragment load for seek (sn: ${a.sn}) - ${y?"backward":"forward"} seek`),a.abortRequests(),this.resetLoadingState();else this.fragPrevious=null}}if(l){this.fragmentTracker.removeFragmentsInRange(d,1/0,this.playlistType,!0);let g=this.lastCurrentTime;if(d>g)this.lastCurrentTime=d;if(!this.loadingParts){let m=Math.max(c.end,d),E=this.shouldLoadParts(this.getLevelDetails(),m);if(E)this.log(`LL-Part loading ON after seeking to ${d} with buffer @${m}`),this.loadingParts=E}}let f=!j.isBuffered(l,d);if(!this.hls.hasEnoughToStart||f){if(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${d} for seek without enough to start`),this.nextLoadPosition=d,f)this.startPosition=d}if(h<1&&this.state===w.IDLE)this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new Ci(t.config),this.initFragmentLoader=new Ci(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new ti(t.config)}registerListeners(){let{hls:t}=this;t.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(v.ERROR,this.onError,this)}unregisterListeners(){let{hls:t}=this;t.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(v.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===w.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let t=this.fragCurrent;if(t!=null&&t.loader)t.abortRequests(),this.fragmentTracker.removeFragment(t);this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=w.STOPPED}get startPositionValue(){let{nextLoadPosition:t,startPosition:e}=this;if(e===-1&&t){let i=this.getLevelDetails();if(i!=null&&i.live)return(this.hls.liveSyncPosition||i.fragmentStart)+this.timelineOffset;return t}return e}get bufferingEnabled(){return this.buffering}get backtrackFragment(){return}set backtrackFragment(t){}get couldBacktrack(){return!1}set couldBacktrack(t){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;let i=t.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;let r=t.buffered;if(this.config.maxBufferHole&&r&&r.length>1)t=j.bufferedInfo(r,t.start,0);let n=t.nextStart;if(n&&n>s&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;let l=e.partList;if(l!=null&&l.length){let u=l[l.length-1];return j.isBuffered(this.media,u.start+u.duration/2)}let o=e.fragments[e.fragments.length-1];return this.fragmentTracker.isEndListAppended(o.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let t=this.config.timelineOffset;if(t){var e;return((e=this.getLevelDetails())==null?void 0:e.appliedTimelineOffset)||t}return 0}onMediaAttached(t,e){let i=this.media=this.mediaBuffer=e.media;pt(i,"seeking",this.onMediaSeeking),pt(i,"ended",this.onMediaEnded);let s=this.config;if(this.levels&&s.autoStartLoad&&this.state===w.STOPPED)this.startLoad(s.startPosition)}onMediaDetaching(t,e){this.fragPlaying=null;let i=!!e.transferMedia,s=this.media;if(s===null)return;if(s.ended)this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0;if(ut(s,"seeking",this.onMediaSeeking),ut(s,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){if(this.stopLoad(),this.transmuxer)this.transmuxer.destroy(),this.transmuxer=null;super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){if(this.state=w.STOPPED,this.fragmentLoader)this.fragmentLoader.destroy();if(this.initFragmentLoader)this.initFragmentLoader.destroy();if(this.keyLoader)this.keyLoader.destroy();if(this.decrypter)this.decrypter.destroy();this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,i){this.startFragRequested=!0,this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){let s=(r)=>{let 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}let a=++n.stats.chunkCount;this.log(`load progress ${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)} chunk: ${a}`),this._handleFragmentLoadProgress(r)};this._doFragLoad(t,e,i,s).then((r)=>{if(!r)return;let n=this.state,a=r.frag;if(this.fragContextChanged(a)){if(n===w.FRAG_LOADING||!this.fragCurrent&&n===w.PARSING)this.fragmentTracker.removeFragment(a),this.state=w.IDLE;return}if("payload"in r)this.log(`Loaded ${a.type} sn: ${a.sn} of ${this.playlistLabel()} ${a.level} (bytes ${a.stats.loaded})`),this.hls.trigger(v.FRAG_LOADED,r);this._handleFragmentLoadComplete(r)}).catch((r)=>{if(this.state===w.STOPPED||this.state===w.ERROR)return;this.log(`Frag error ${t.type} sn:${t.sn} cc:${t.cc}: ${(r==null?void 0:r.message)||r}`),this.resetFragmentLoading(t)})}clearTrackerIfNeeded(t){var e;let{fragmentTracker:i}=this;if(i.getState(t)===mt.APPENDING){let r=t.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),a=Math.max(t.duration,n?n.len:this.config.maxBufferLength),l=this.backtrackFragment;if((l?t.sn-l.sn:0)===1||this.reduceMaxBufferLength(a,t.duration))i.removeFragment(t)}else if(((e=this.mediaBuffer)==null?void 0:e.buffered.length)===0)i.removeAllFragments();else if(i.hasParts(t.type)){if(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===mt.PARTIAL)i.removeFragment(t)}}checkLiveUpdate(t){if(t.updated&&!t.live){let e=this.fragmentTracker,i=t.fragments[t.fragments.length-1];if(i.endList&&!e.isEndListAppended(this.playlistType)){let s=e.getPartialFragment(i.end);if(s)e.removeFragment(s),e.fragBuffered(i,!0)}e.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}if(!t.fragments[0])t.deltaUpdateFailed=!0}waitForLive(t){let e=t.details;return(e==null?void 0:e.live)&&e.type!=="EVENT"&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,i=null){if(!(t-e))return;let s={startOffset:t,endOffset:e,type:i};this.hls.trigger(v.BUFFER_FLUSHING,s)}_loadInitSegment(t){let{hls:e}=this;return this.initFragmentLoader.abort(),e.trigger(v.FRAG_LOADING,{frag:t,targetBufferTime:0}),this.initFragmentLoader.load(t).then((i)=>{var s;let r=i.frag;if(!this.levels||!xi(r,(s=this.fragCurrent)==null?void 0:s.initSegment))throw new Rt({type:q.NETWORK_ERROR,details:R.INTERNAL_ABORTED,error:Error("init load aborted"),fatal:!1,frag:r,networkDetails:null});return i}).then((i)=>{let{frag:s,payload:r}=i,n=s.decryptdata;if(r&&r.byteLength>0&&n!=null&&n.key&&n.iv&&fe(n.method)){let a=self.performance.now(),{decryptRange:l}=je(s,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,Gr(n.method),l).catch((o)=>{throw e.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:s}),this.fragmentLoader.abort(),o}).then((o)=>{let u=self.performance.now();return e.trigger(v.FRAG_DECRYPTED,{frag:s,part:null,payload:o,stats:{tstart:a,tdecrypt:u}}),i.payload=o,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)})}completeInitSegmentLoad(t){let e=t.frag.stats;t.frag.data=new Uint8Array(t.payload),e.parsing.start=e.buffering.start=self.performance.now(),e.parsing.end=e.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(t){let{initSegment:e}=t;if(!this.bitrateTest&&St(t)&&e&&!e.data){var i;return(e.encrypted&&!((i=e.decryptdata)!=null&&i.key)?this.keyLoader.load(e).then(()=>this._loadInitSegment(e)):this._loadInitSegment(e)).catch((r)=>{if(this.state===w.STOPPED||this.state===w.ERROR)throw r;if("data"in r)r.data.frag=t,this.fragmentLoader.abort(),this.handleFragLoadError(r);throw this.resetFragmentLoading(t),r})}}unhandledEncryptionError(t,e){var i,s;let r=t.tracks;if(r&&!e.encrypted&&((i=r.audio)!=null&&i.encrypted||(s=r.video)!=null&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let n=this.media,a=Error("EME not supported (light build)");if(this.warn(a.message),!n||n.mediaKeys)return!1;return this.hls.trigger(v.ERROR,{type:q.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,fatal:!0,error:a,frag:e}),this.resetTransmuxer(),!0}return!1}fragContextChanged(t){let{fragCurrent:e}=this;return!t||!xi(t,e)}fragBufferedComplete(t,e){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${i?Pi(j.getBuffered(i)):"(detached)"})`),St(t)){var s;if(t.type!==Q.SUBTITLE){let n=t.elementaryStreams;if(!Object.keys(n).some((a)=>!!n[a])){this.state=w.IDLE;return}}let r=(s=this.levels)==null?void 0:s[t.level];if(r!=null&&r.fragmentError&&(e||this.fragmentTracker.getState(t)!==mt.PARTIAL))this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0,t.stats.retry=0}this.state=w.IDLE}_handleFragmentLoadComplete(t){let{transmuxer:e}=this;if(!e)return;let i=t.frag,{part:s,partsLoaded:r}=t,n=!r||r.length===0||r.some((o)=>!o),{decryptRange:a}=je(i,s),l=new Qi(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n,i.duration,this.iframesOnly,a);this.log(`load complete ${i.type} sn: ${i.sn}${s?" part: "+s.index:""} of ${this.fragInfo(i,!1,s)}`),e.flush(l)}_handleFragmentLoadProgress(t){}loadKeyFor(t,e,i){var s;let r=null;if(t.encrypted&&!((s=t.decryptdata)!=null&&s.key))this.log(`Loading key for ${t.sn} of [${e.startSN}-${e.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=w.KEY_LOADING,r=this.keyLoader.load(t,i).then((n)=>{if(!this.fragContextChanged(n.frag)){if(this.hls.trigger(v.KEY_LOADED,n),this.state===w.KEY_LOADING)this.state=w.IDLE;return n}}),this.hls.trigger(v.KEY_LOADING,{frag:t});else if(!t.encrypted){if(r=this.keyLoader.loadClear(t,e.encryptedFragments,this.startFragRequested),r)this.log(`[eme] blocking frag sn: ${t.sn} load until media-keys acquired`)}return r}_doFragLoad(t,e,i=null,s){this.fragCurrent=t;let r=e.details;if(!this.levels||!r)throw Error(`frag load aborted, missing level${r?"":" detail"}s`);let n=this.fragPrevious;if(!Le(t,n)){let h=this.shouldLoadParts(e.details,t.end);if(h!==this.loadingParts)this.log(`LL-Part loading ${h?"ON":"OFF"} loading sn ${n==null?void 0:n.sn}->${t.sn}`),this.loadingParts=h}if(i=Math.max(t.start,i||0),this.loadingParts){let h=r.partList;if(h&&s){if(i>r.fragmentEnd&&r.fragmentHint)t=r.fragmentHint;let f=this.getNextPart(h,t,i);if(f>-1){let g=h[f];if(t=this.fragCurrent=g.fragment,!Le(t,n)&&!this.shouldLoadParts(e.details,t.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(t,!1,g)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(g,e.details))return Promise.resolve(null);let m=this.loadKeyFor(t,r);if(this.fragContextChanged(t))return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} part: ${g.index} (${f}/${h.length-1}) of ${this.fragInfo(t,!1,g)} cc: ${t.cc} [${r.startSN}-${r.endSN}], target: ${i}${g.byteRange.length?` range:${g.byteRange.join("-")}`:""}`),this.nextLoadPosition=g.start+g.duration,this.state=w.FRAG_LOADING;let E,y=this.loadInitSegmentIfNeeded(t);if(m||y){let p=!!m;E=Promise.all([m,y]).then(([S])=>{if(p&&(!S||this.fragContextChanged(S.frag)))return null;return this.doFragPartsLoad(t,g,e,s)}).catch((S)=>this.handleFragLoadError(S))}else E=this.doFragPartsLoad(t,g,e,s).catch((p)=>this.handleFragLoadError(p));if(this.hls.trigger(v.FRAG_LOADING,{frag:t,part:g,targetBufferTime:i}),this.fragCurrent===null)return Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING parts"));return E}else if(!t.url||this.loadedEndOfParts(h,i))return Promise.resolve(null)}}if(this.loadingParts){var a;this.log(`LL-Part loading OFF after next part miss @${i} Check buffer at sn: ${t.sn} loaded parts: ${(a=r.partList)==null?void 0:a.filter((h)=>h.loaded).map((h)=>`[${h.start}-${h.end}]`)}`),this.loadingParts=!1}else if(!t.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(t,e.details))return Promise.resolve(null);let l=this.loadInitSegmentIfNeeded(t),o=this.loadKeyFor(t,r,l);if(this.fragContextChanged(t)){var u;return this.log(`Context changed in KEY_LOADING sn: ${t.sn} ${t.relurl} > ${(u=this.fragCurrent)==null?void 0:u.relurl}`),l==null||l.catch(()=>null),o==null||o.catch(()=>null),Promise.resolve(null)}if(this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)} cc: ${t.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${i}${t.byteRange.length?` range:${t.byteRange.join("-")}`:""}`),V(t.sn)&&!this.bitrateTest)this.nextLoadPosition=t.start+t.duration;this.state=w.FRAG_LOADING;let d=this.config.progressive&&t.type!==Q.SUBTITLE,c;if(d&&o)c=o.then((h)=>{if(!h||this.fragContextChanged(h.frag))return null;return this.fragmentLoader.load(t,this.iframesOnly,s,l)}).catch((h)=>this.handleFragLoadError(h));else c=Promise.all([this.fragmentLoader.load(t,this.iframesOnly,d?s:void 0,d?l:void 0),o,l]).then(([h])=>{if(!d&&s)s(h);return h}).catch((h)=>this.handleFragLoadError(h));if(this.hls.trigger(v.FRAG_LOADING,{frag:t,targetBufferTime:i}),this.fragCurrent===null)return Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING"));return Promise.all([c,l]).then(([h])=>h)}doFragPartsLoad(t,e,i,s){return new Promise((r,n)=>{var a;let l=[],o=(a=i.details)==null?void 0:a.partList,u=(d)=>{this.fragmentLoader.loadPart(t,d,s).then((c)=>{l[d.index]=c;let h=c.part;this.hls.trigger(v.FRAG_LOADED,c);let f=Ns(i.details,t.sn,d.index+1)||jr(o,t.sn,d.index+1);if(f)u(f);else return r({frag:t,part:h,partsLoaded:l})}).catch(n)};u(e)})}handleFragLoadError(t){if("data"in t){let e=t.data;if(e.frag&&e.details===R.INTERNAL_ABORTED)this.handleFragLoadAborted(e.frag,e.part);else if(e.frag&&e.type===q.KEY_SYSTEM_ERROR&&!e.fatal)e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag);this.hls.trigger(v.ERROR,e)}else this.hls.trigger(v.ERROR,{type:q.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){let e=this.getCurrentContext(t);if(!e||this.state!==w.PARSING){if(!this.fragCurrent&&this.state!==w.STOPPED&&this.state!==w.ERROR)this.state=w.IDLE;return}let{frag:i,part:s,level:r}=e,n=self.performance.now();if(i.stats.parsing.end=n,s)s.stats.parsing.end=n;let a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);if(o!==this.loadingParts)this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end}`),this.loadingParts=o;this.updateLevelTiming(i,s,r,t)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList&&!this.iframesOnly){var i;let s=t.partList[0],r=s.end+(((i=t.fragmentHint)==null?void 0:i.duration)||0);if(e>=r){if(this.playhead>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(t){let{levels:e,fragCurrent:i}=this,{level:s,sn:r,part:n}=t;if(!(e!=null&&e[s]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;let a=e[s],l=a.details,o=n>-1?Ns(l,r,n):null,u=o?o.fragment:Yr(l,r,i);if(!u)return null;if(i&&i!==u)u.stats=i.stats;return{frag:u,part:o,level:a}}bufferFragmentData(t,e,i,s,r){if(this.state!==w.PARSING)return;if(St(e)&&!this.fragContextChanged(e))this.fragPrevious=e;let{data1:n,data2:a}=t,l=n;if(a)l=It(n,a);if(!l.length)return;let o=this.initPTS[e.cc],u=o?-o.baseTime/o.timescale:void 0,d={type:t.type,frag:e,part:i,chunkMeta:s,offset:u,parent:e.type,data:l};if(this.hls.trigger(v.BUFFER_APPENDING,d),t.dropped&&t.independent&&!i){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){let e=this.media;if(!e)return;if(!j.isBuffered(e,e.currentTime)){this.flushMainBuffer(0,t.start);return}let i=e.currentTime,s=j.bufferInfo(e,i,0),r=t.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*0.25),a=Math.max(Math.min(t.start-n,s.end-n),i+n);if(t.start-a>n)this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var i;let s=this.playhead,n=this.lastCurrentTime>s||(i=this.media)!=null&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,s,e,n)}getFwdBufferInfoAtPos(t,e,i,s){let r=j.bufferInfo(t,e,s);if(r.len===0&&r.nextStart!==void 0){let n=this.fragmentTracker.getBufferedFrag(e,i);if(n&&(r.nextStart<=n.end||n.gap)){let a=Math.max(Math.min(r.nextStart,n.end)-e,s);return j.bufferInfo(t,e,a)}}return r}getMaxBufferLength(t){let{config:e}=this,i;if(t)i=Math.max(8*e.maxBufferSize/t,e.maxBufferLength);else i=e.maxBufferLength;return Math.min(i,e.maxMaxBufferLength)}exceedsMaxBuffer(t,e,i){let s=t.nextStart;if(s&&i.start>s){let r=t.buffered;if(r){let{len:n,bufferedIndex:a}=t;for(let l=r.length-1;l>a;l--)if(r[l].start<i.start)n+=r[l].end-r[l].start;return n>=e}}return!1}reduceMaxBufferLength(t,e){let i=this.config,s=Math.max(Math.min(t-e,i.maxBufferLength),e/2),r=Math.max(t-e*3,i.maxMaxBufferLength/2,s);if(r>=s)return i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0;return!1}getAppendedFrag(t){let e=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,this.playlistType):null;if(e&&"fragment"in e)return e.fragment;return e}getNextFragment(t,e){let i=e.fragments,s=i.length;if(!s)return null;let{config:r}=this,n=e.fragmentStart,a=r.lowLatencyMode&&!!e.partList,l=null;if(e.live){let d=r.initialLiveManifestSize;if(s<d)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${d})`),null;if(!this.startFragRequested&&a&&!this.loadingParts)this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0;if(!e.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||t<n){var o;l=this.getInitialLiveFragment(e);let c=this.config.startPosition,h=this.hls.startPosition,f=this.hls.liveSyncPosition,g=((o=l)==null?void 0:o.start)||0,m,E;if(h!==-1&&h>=n)m=h,E=h===c?"config":"next load start";else if(f)m=f,E="live edge";else m=t,E="buffer pos";if(m<g)m=g,E="live frag start";if(m<n)m=n,E="playlist start";if(this.startPosition!=m||this.nextLoadPosition!=m){let p=e.live&&!this.filterReplacedPrimary(l,e)?-1:m;this.log(`Setting startPosition to ${p} next load ${m} ${h===-1?"":`(from ${c}) `}based on ${E}. live edge: ${f} live frag start: ${g} playlist start: ${n} buffer pos: ${t}`),this.startPosition=p,this.nextLoadPosition=m}}}else if(t<=n)l=i[0];if(!l){let d=this.loadingParts?e.partEnd:e.fragmentEnd;l=this.getFragmentAtPosition(t,d,e)}let u=this.filterReplacedPrimary(l,e);if(!u&&l){if(u=ro(e,l.sn),u)this.nextLoadPosition=u.start}return u}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;let i=this.fragmentTracker.getState(t);if(i===mt.OK)return!0;if(i===mt.PARTIAL){if(t.gap)return!0;if(t.stats.retry>1)return!0}return!1}getNextFragmentLoopLoading(t,e,i,s,r){let n=null;if(t.gap){if(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&i.nextStart){let a=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(a!==null&&i.len+a.len>=r){let l=n.sn;if(this.loopSn!==l)this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${l}`),this.loopSn=l;return null}}}return this.loopSn=void 0,n}get primaryPrefetch(){if(ki(this.config));return!1}filterReplacedPrimary(t,e){if(!t)return t;if(ki(this.config));return t}getNextPart(t,e,i){let s=-1,r=!1,n=!0;for(let l=0,o=t.length;l<o;l++){let u=t[l];if(n=n&&!u.independent,s>-1&&i<u.start)break;let d=u.loaded||u.gap;if(d)s=-1;else if(r||(u.independent||n)&&u.fragment===e)s=l;r=d&&!u.gap}let a=t[s];if(a&&a.fragment!==e)this.log(`Need buffer at ${i} but next unloaded part starts at ${a.start} (sn: ${e.sn} -> ${a.fragment.sn})`);return s}loadedEndOfParts(t,e){let i;for(let s=t.length;s--;){if(i=t[s],!i.loaded)return!1;if(e>i.start)return!0}return!1}getInitialLiveFragment(t){let e=t.fragments,i=this.fragPrevious,s=null;if(i){if(t.hasProgramDateTime){if(s=to(e,i.endProgramDateTime,this.config.maxFragLookUpTolerance),s)this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`)}if(!s){let r=i.sn+1;if(r>=t.startSN&&r<=t.endSN){let n=e[r-t.startSN];if(i.cc===n.cc)s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`)}if(!s){if(s=so(t,i.cc,i.end),s)this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`)}}}else{let r=this.hls.liveSyncPosition;if(r!==null)s=this.getFragmentAtPosition(r,this.bitrateTest?t.fragmentEnd:t.edge,t)}return s}getFragmentAtPosition(t,e,i){let{config:s}=this,{fragPrevious:r}=this,{fragments:n,endSN:a}=i,{fragmentHint:l}=i,{maxFragLookUpTolerance:o}=s,u=i.partList,d=!!(this.loadingParts&&u!=null&&u.length&&l);if(d&&!this.bitrateTest&&u[u.length-1].fragment.sn===l.sn)n=n.concat(l),a=l.sn;if(r&&this.fragmentTracker.getState(r)===mt.NOT_LOADED)r=null;let c;if(t<e){var h;let g=t<this.lastCurrentTime||t>e-o||(h=this.media)!=null&&h.paused||!this.startFragRequested?0:o;c=qi(r,n,t,g)}else c=n[n.length-1];if(c){let f=c.sn-i.startSN,g=this.fragmentTracker.getState(c);if(g===mt.OK||g===mt.PARTIAL&&c.gap)r=c;if(Le(c,r)&&(!d||u[0].fragment.sn>c.sn||!i.live)){let m=n[f+1];if(c.sn<a&&this.fragmentTracker.getState(m)!==mt.OK)c=m;else c=null}}return c}alignPlaylists(t,e,i){let s=t.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;let r=t.fragmentStart,n=!e,a=t.alignedSliding&&V(r);if(n||!a&&!r){Io(i,t,this);let l=t.fragmentStart;return this.log(`Live playlist sliding: ${l} start-sn: ${e?e.startSN:"na"}->${t.startSN} fragments: ${s}`),l}return r}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,e){let i=this.startPosition;if(i<e)i=-1;let s=this.timelineOffset;if(i===-1){let r=this.startTimeOffset!==null,n=r?this.startTimeOffset:t.startTimeOffset;if(n!==null&&V(n)){if(i=e+n,n<0)i+=t.edge;i=Math.min(Math.max(e,i),e+t.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=i}else if(t.live){let a=this.hls.liveSyncPosition;i=a||e,this.log(`Setting startPosition to -1 to start at ${a?"live edge":"playlist start"} ${i}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=i=0;this.lastCurrentTime=i+s}this.nextLoadPosition=i+s}getLoadPosition(){var t;let{media:e}=this,i=0;if((t=this.hls)!=null&&t.hasEnoughToStart&&e&&!this.iframesOnly)i=e.currentTime;else if(this.nextLoadPosition>=0)i=this.nextLoadPosition;return i}get playhead(){var t;if((t=this.hls)!=null&&t.hasEnoughToStart){var e;let i=(e=this.media)==null?void 0:e.currentTime;if(V(i))return i;return this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var t;if(this.playlistType!==Q.MAIN)return!1;let e=this.getLevelDetails();if(e)return e.iframesOnly;return(t=this.levelLastLoaded)==null?void 0:t.iframes}handleFragLoadAborted(t,e){if(this.transmuxer&&t.type===this.playlistType&&St(t)&&t.stats.aborted)this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t)}resetFragmentLoading(t){if(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==w.FRAG_LOADING_WAITING_RETRY)this.state=w.IDLE}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){let y=this.getCurrentContext(e.chunkMeta);if(y)e.frag=y.frag}let{frag:i,part:s}=e;if(!i||!this.levels||i.type!==t)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.relurl} > ${(r=this.fragCurrent)==null?void 0:r.relurl}`);return}let n=e.details===R.FRAG_GAP;if(n)this.fragmentTracker.addAsGap(i);let a=e.errorAction;if(!a){this.state=w.ERROR;return}let{action:l,flags:o,retryCount:u=0,retryConfig:d}=a,c=!!d,h=c&&l===ht.RetryRequest,f=c&&!a.resolved&&o&ct.MoveAllAlternatesMatchingHost,g=this.hls.latestLevelDetails,m=g==null?void 0:g.live;if(!h&&f&&St(i)&&m&&i.sn<g.endSN&&!pr(e)){if(this.resetFragmentErrors(t),s)s.gap=!0;else this.treatAsGap(i);a.resolved=!0}else if((h||f)&&u<d.maxNumRetry){var E;let y=pe((E=e.response)==null?void 0:E.code),p=Vi(d,u);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+p,this.state=w.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,y){this.log("Waiting for connection (offline)"),this.retryDate=1/0,e.reason="offline";return}this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${u+1}/${d.maxNumRetry} in ${p}ms`)}else if(d)if(this.resetFragmentErrors(t),u<d.maxNumRetry){if(!n&&l!==ht.RemoveAlternatePermanently)a.resolved=!0}else{this.warn(`${e.details} reached or exceeded max retry (${u})`);return}else if(l===ht.SendAlternateToPenaltyBox)this.state=w.WAITING_LEVEL;else this.state=w.ERROR;this.tickImmediate()}checkRetryDate(){let t=self.performance.now(),e=this.retryDate,i=e===1/0;if(!e||t>=e||i&&!pe(0)){if(i)this.log("Connection restored (online)");this.resetStartWhenNotLoaded(),this.state=w.IDLE}}reduceLengthAndFlushBuffer(t){if(this.state===w.PARSING||this.state===w.PARSED){let{frag:e,parent:i}=t,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>0.5;if(r)this.reduceMaxBufferLength(s.len,(e==null?void 0:e.duration)||10);let n=!r;if(n)this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${i} buffer`);else if(s.nextStart&&e&&s.nextStart>e.start)this.flushMainBuffer(s.nextStart,Number.POSITIVE_INFINITY,i===Q.AUDIO?i:void 0);if(e)this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start;return this.resetLoadingState(),n}return!1}resetFragmentErrors(t){if(t===Q.AUDIO)this.fragCurrent=null;if(!this.hls.hasEnoughToStart)this.startFragRequested=!1;if(this.state!==w.STOPPED)this.state=w.IDLE}afterBufferFlushed(t,e){if(!t)return;let i=j.getBuffered(t);if(this.fragmentTracker.detectEvictedFragments(e,i,this.playlistType),this.state===w.ENDED)this.resetLoadingState()}resetLoadingState(){if(this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==w.STOPPED)this.state=w.IDLE}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let t=this.getLevelDetails();if(t!=null&&t.live)this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState();else this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${t.level===-1?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,s){let r=i.details;if(!r){this.warn("level.details undefined");return}if(this.log(`update level timing ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`),!Object.keys(t.elementaryStreams).reduce((d,c)=>{let h=t.elementaryStreams[c];if(h){let f=h.endPTS-h.startPTS;if(f<=0)return this.warn(`Could not parse fragment ${t.sn} ${c} duration reliably (${f})`),d||!1;let g=s.partial?0:Kr(r,t,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this.iframesOnly,this);return this.hls.trigger(v.LEVEL_PTS_UPDATED,{details:r,level:i,drift:g,type:c,frag:t,start:h.startPTS,end:h.endPTS}),!0}return d},!1)){var a,l,o,u;let d=((a=this.transmuxer)==null?void 0:a.error)===null,c=((l=this.transmuxer)==null?void 0:l.error)!=null,h=((o=(u=this.levels)==null?void 0:u.length)!=null?o:0)>1;if(i.fragmentError===0||d&&(i.fragmentError<2||t.endList)||c&&h)this.treatAsGap(t,i);if(d){let f=Error(`Found no media in ${this.playlistLabel()} ${t.level} ${e?`part: ${e.index} of `:""}sn: ${t.sn} at playlist time: ${t.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(f.message),this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:f,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=w.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`),this.hls.trigger(v.FRAG_PARSED,{frag:t,part:e,chunkMeta:s})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(t,e=!0,i){var s,r;return`${this.playlistLabel()} ${t.level} (${i?"part":"frag"}:[${(s=e&&!i?t.startPTS:(i||t).start)!=null?s:NaN}-${(r=e&&!i?t.endPTS:(i||t).end)!=null?r:NaN}]${i&&t.type==="main"?"INDEPENDENT="+(i.independent?"YES":"NO"):""})`}treatAsGap(t,e){if(e)e.fragmentError++;this.fragmentTracker.addAsGap(t)}resetTransmuxer(){var t;(t=this.transmuxer)==null||t.reset()}isFragmentNearlyDownloaded(t){var e;let i=(e=t.loader)==null?void 0:e.stats;if(!i)return!1;let s=i.loading.first>0,n=(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return s&&n<=0.15}recoverWorkerError(t){if(t.event==="demuxerWorker"){if(this.fragmentTracker.removeAllFragments(),this.transmuxer)this.transmuxer.destroy(),this.transmuxer=null;this.resetStartWhenNotLoaded(),this.resetLoadingState()}}set state(t){let e=this._state;if(e!==t)this._state=t,this.log(`${e}->${t}`)}get state(){return this._state}calculateOptimalSwitchPoint(t,e){let i=0,{hls:s,media:r,config:n,levels:a,playlistType:l}=this,o=this.getLevelDetails();if(r&&!r.paused&&a){var u;let h=l===Q.AUDIO?Gt.estimatedAudioBitrate(t.audioCodec,128000):t.maxBitrate,f=1+s.ttfbEstimate/1000,g=s.bandwidthEstimate*n.abrBandWidthUpFactor,m=o&&(this.loadingParts?o.partTarget:o.averagetargetduration)||((u=this.fragCurrent)==null?void 0:u.duration)||6;if(i=f+h*m/g,!t.details)i+=f}let d=this.playhead,c=!(o!=null&&o.live)||e.end-d>i*1.5;return{fetchdelay:i,okToFlushForwardBuffer:c}}scheduleTrackSwitch(t,e,i){let{media:s,playlistType:r}=this;if(!s||!t)return;let n=i?this.getBufferedFrag(this.playhead+e):null;if(n){let l=this.followingBufferedFrag(n);if(l){var a;this.abortCurrentFrag();let o=l.maxStartPTS?l.maxStartPTS:l.start,u=l.duration,d=Math.max(n.end,o+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?0.5:0.125)),u*(this.couldBacktrack?0.75:0.25)));if((((a=this.getLevelDetails())==null?void 0:a.fragmentStart)||0)>d)return;let h=r===Q.MAIN?null:"audio";this.flushMainBuffer(d,Number.POSITIVE_INFINITY,h),this.cleanupBackBuffer()}}}cleanupBackBuffer(){let{media:t,playlistType:e}=this;if(!t)return;let i=this.getAppendedFrag(this.playhead);if(i&&i.start>1){let s=e===Q.AUDIO;this.flushMainBuffer(0,i.start-(s?0:1),s?"audio":null)}}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,this.playlistType)}followingBufferedFrag(t){if(t)return this.getBufferedFrag(t.end+0.5);return null}abortCurrentFrag(){let t=this.fragCurrent;if(this.fragCurrent=null,t)t.abortRequests(),this.fragmentTracker.removeFragment(t);switch(this.state){case w.KEY_LOADING:case w.FRAG_LOADING:case w.FRAG_LOADING_WAITING_RETRY:case w.PARSING:case w.PARSED:this.state=w.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){let t=this.media,e=null;if(t&&t.readyState>1&&t.seeking===!1){let i=t.currentTime;if(j.isBuffered(t,i))e=this.getAppendedFrag(i);else if(j.isBuffered(t,i+0.1))e=this.getAppendedFrag(i+0.1);if(e){if(this.backtrackFragment=void 0,!Le(e,this.fragPlaying))return this.fragPlaying=e,!0}}return!1}getBufferOutput(){return null}nextLevelSwitch(){let{levels:t,media:e,hls:i,config:s,playlistType:r}=this;if(e!=null&&e.readyState&&t&&i&&s){let n=this.getBufferOutput(),a=this.getFwdBufferInfo(n,r);if(!a)return;let l=r===Q.AUDIO?i.nextAudioTrack:i.nextLoadLevel,o=t[l],{fetchdelay:u,okToFlushForwardBuffer:d}=this.calculateOptimalSwitchPoint(o,a);this.scheduleTrackSwitch(a,u,d)}this.tickImmediate()}}function ki(t){return!1}class sn{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,i){if(this.queues===null||this.tracks===null)return;let s=this.queues[e];if(s.push(t),s.length===1&&!i)this.executeNext(e)}appendBlocker(t){return new Promise((e)=>{let i={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,t)})}prependBlocker(t){return new Promise((e)=>{if(this.queues){let i={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(i)}})}removeBlockers(){if(this.queues===null)return;[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach((t)=>{var e;let i=(e=t[0])==null?void 0:e.label;if(i==="async-blocker"||i==="async-blocker-prepend")t[0].execute(),t.splice(0,1);else if(i==="block-audio")t.splice(0,1)})}insertNext(t,e){if(this.queues===null)return;this.queues[e].splice(1,0,...t)}unblockAudio(){var t;if(this.queues===null)return;if(((t=this.current("audio"))==null?void 0:t.label)==="block-audio")this.shiftAndExecuteNext("audio")}audioBlocking(){if(this.queues===null)return!1;return this.queues.audio.some((t)=>t.label==="block-audio")}executeNext(t){if(this.queues===null||this.tracks===null)return;let e=this.queues[t];if(e.length){let s=e[0];try{s.execute()}catch(r){var i;if(s.onError(r),this.queues===null||this.tracks===null)return;let n=(i=this.tracks[t])==null?void 0:i.buffer;if(!(n!=null&&n.updating))this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){if(this.queues===null)return;this.queues[t].shift(),this.executeNext(t)}current(t){var e;return((e=this.queues)==null?void 0:e[t][0])||null}toString(){let{queues:t,tracks:e}=this;if(t===null||e===null)return"<destroyed>";return`
|
|
17
|
+
${this.list("video")}
|
|
18
|
+
${this.list("audio")}
|
|
19
|
+
${this.list("audiovideo")}}`}list(t){var e,i;return(e=this.queues)!=null&&e[t]||(i=this.tracks)!=null&&i[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;let i=(e=this.tracks)==null?void 0:e[t],s=i==null?void 0:i.buffer;if(!s)return"none";return`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`}listOps(t){var e;return((e=this.queues)==null?void 0:e[t].map((i)=>i.label).join(", "))||""}}var Ws=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,rn="HlsJsTrackRemovedError",Co=0.25,Po=0.001;class nn extends Error{constructor(t){super(t);this.name=rn}}class an extends wt{constructor(t,e){super("buffer-controller",t.logger);this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=(i)=>{var s;if(!this.hls)return;if(((s=this.mediaSource)==null?void 0:s.readyState)!=="open")return;if(!this.media||this.media.seeking)return;this.hls.pauseBuffering()},this._onStartStreaming=(i)=>{if(!this.hls)return;this.hls.resumeBuffering()},this._onMediaSourceOpen=(i)=>{let{media:s,mediaSource:r}=this;if(i)this.log("Media source opened");if(!s||!r)return;if(ut(r,"sourceopen",this._onMediaSourceOpen),ut(s,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(v.MEDIA_ATTACHED,{media:s,mediaSource:r}),this.mediaSource!==null)this.checkPendingTracks()},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){let i=this.media.error,{appendError:s,appendErrors:r}=this,n=!1;if(!s&&i)n=Math.max(++r.audio,++r.video,++r.audiovideo)>=this.hls.config.appendErrorMaxRetry;let a=Error(`MediaSource closed while media attached${js(n,i)}`);this.warn(a),this.hls.trigger(v.ERROR,dt({fatal:n},s,{type:q.MEDIA_ERROR,details:R.MEDIA_SOURCE_REQUIRES_RESET,error:a}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:i,_objectUrl:s}=this;if(i!==s)this.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this._onMediaError=()=>{let{media:i}=this;if(i){var s,r;this.log(`Media error (code: ${(s=i.error)==null?void 0:s.code}): ${(r=i.error)==null?void 0:r.message}`)}},this.hls=t,this.fragmentTracker=e,this.appendSource=aa(jt(t.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){if(this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue)this.operationQueue.destroy(),this.operationQueue=null;this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){let{hls:t}=this;t.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.MANIFEST_PARSED,this.onManifestParsed,this),t.on(v.BUFFER_RESET,this.onBufferReset,this),t.on(v.BUFFER_APPENDING,this.onBufferAppending,this),t.on(v.BUFFER_CODECS,this.onBufferCodecs,this),t.on(v.BUFFER_EOS,this.onBufferEos,this),t.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(v.FRAG_PARSED,this.onFragParsed,this),t.on(v.FRAG_CHANGED,this.onFragChanged,this),t.on(v.ERROR,this.onError,this)}unregisterListeners(){let{hls:t}=this;t.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.MANIFEST_PARSED,this.onManifestParsed,this),t.off(v.BUFFER_RESET,this.onBufferReset,this),t.off(v.BUFFER_APPENDING,this.onBufferAppending,this),t.off(v.BUFFER_CODECS,this.onBufferCodecs,this),t.off(v.BUFFER_EOS,this.onBufferEos,this),t.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(v.FRAG_PARSED,this.onFragParsed,this),t.off(v.FRAG_CHANGED,this.onFragChanged,this),t.off(v.ERROR,this.onError,this)}transferMedia(){let{media:t,mediaSource:e}=this;if(!t)return null;let i={};if(this.operationQueue){let r=this.isUpdating();if(!r)this.operationQueue.removeBlockers();let n=this.isQueued();if(r||n)this.warn(`Transfering MediaSource with${n?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`);this.operationQueue.destroy()}let s=this.transferData;if(s&&!this.sourceBufferCount&&s.mediaSource===e)dt(i,s.tracks);else this.sourceBuffers.forEach((r)=>{let[n]=r;if(n)i[n]=dt({},this.tracks[n]),this.removeBuffer(n);r[0]=r[1]=null});return{media:t,mediaSource:e,tracks:i}}initTracks(){let t={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=t,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(t,e){var i;let s=2;if(e.audio&&!e.video||!e.altAudio)s=1;if(this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),(i=this.transferData)!=null&&i.mediaSource&&this.sourceBufferCount&&s)this.bufferCreated()}onMediaAttaching(t,e){let i=this.media=e.media;this.transferData=this.overrides=void 0;let s=jt(this.appendSource);if(s){let r=!!e.mediaSource;if(r||e.overrides)this.transferData=e,this.overrides=e.overrides;let n=this.mediaSource=e.mediaSource||new s;if(this.assignMediaSource(n),r)this._objectUrl=i.src,this.attachTransferred();else{let a=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{i.removeAttribute("src");let l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&n instanceof l,Ys(i),ko(i,a),i.load()}catch(l){i.src=a}else i.src=a}if(pt(i,"emptied",this._onMediaEmptied),pt(i,"error",this._onMediaError),this.appendSource)pt(i,"seeking",this._onStartStreaming)}}assignMediaSource(t){var e,i;if(this.log(`${((e=this.transferData)==null?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${(i=t.constructor)==null?void 0:i.name}`),pt(t,"sourceopen",this._onMediaSourceOpen),pt(t,"sourceended",this._onMediaSourceEnded),pt(t,"sourceclose",this._onMediaSourceClose),this.appendSource)pt(t,"startstreaming",this._onStartStreaming),pt(t,"endstreaming",this._onEndStreaming)}attachTransferred(){let t=this.media,e=this.transferData;if(!e||!t)return;let i=this.tracks,s=e.tracks,r=s?Object.keys(s):null,n=r?r.length:0,a=()=>{Promise.resolve().then(()=>{if(this.media&&this.mediaSourceOpenOrEnded)this._onMediaSourceOpen()})};if(s&&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})
|
|
20
|
+
required tracks: ${yt(i,(l,o)=>l==="initSegment"?void 0:o)};
|
|
21
|
+
transfer tracks: ${yt(s,(l,o)=>l==="initSegment"?void 0:o)}}`),!oa(s,i)){e.mediaSource=null,e.tracks=void 0;let l=t.currentTime,o=this.details,u=Math.max(l,(o==null?void 0:o.fragments[0].start)||0);if(u-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${u} currentTime: ${l}`),this.onMediaDetaching(v.MEDIA_DETACHING,{}),this.onMediaAttaching(v.MEDIA_ATTACHING,e),t.currentTime=u;return}this.transferData=void 0,r.forEach((l)=>{let o=l,u=s[o];if(u){let d=u.buffer;if(d){let c=this.fragmentTracker,h=u.id;if(c.hasFragments(h)||c.hasParts(h)){let m=j.getBuffered(d);c.detectEvictedFragments(o,m,h,null,null,!0)}let f=gi(o),g=[o,d];if(this.sourceBuffers[f]=g,d.updating&&this.operationQueue)this.operationQueue.prependBlocker(o);this.trackSourceBuffer(o,u)}}}),a(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),a()}get mediaSourceOpenOrEnded(){var t;let e=(t=this.mediaSource)==null?void 0:t.readyState;return e==="open"||e==="ended"}onMediaDetaching(t,e){let i=!!e.transferMedia;this.transferData=this.overrides=void 0;let{media:s,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([a])=>{if(a)this.removeBuffer(a)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let a=r.readyState==="open";try{let l=r.sourceBuffers;for(let o=l.length;o--;){if(a)l[o].abort();r.removeSourceBuffer(l[o])}if(a)r.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}if(this.sourceBufferCount)this.onBufferReset()}if(ut(r,"sourceopen",this._onMediaSourceOpen),ut(r,"sourceended",this._onMediaSourceEnded),ut(r,"sourceclose",this._onMediaSourceClose),this.appendSource)ut(r,"startstreaming",this._onStartStreaming),ut(r,"endstreaming",this._onEndStreaming);this.mediaSource=null,this._objectUrl=null}if(s){if(ut(s,"emptied",this._onMediaEmptied),ut(s,"error",this._onMediaError),ut(s,"seeking",this._onStartStreaming),!i){if(n)self.URL.revokeObjectURL(n);if(this.mediaSrc===n){if(s.removeAttribute("src"),this.appendSource)Ys(s);s.load()}else this.warn("media|source.src was changed by a third party - skip cleanup")}this.media=null}}onBufferReset(){this.sourceBuffers.forEach(([t])=>{if(t)this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;let i=(e=this.tracks[t])==null?void 0:e.buffer;if(this.removeBuffer(t),i)try{var s;if((s=this.mediaSource)!=null&&s.sourceBuffers.length)this.mediaSource.removeSourceBuffer(i)}catch(r){this.warn(`onBufferReset ${t}`,r)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[gi(t)]=[null,null];let e=this.tracks[t];if(e)this.clearBufferAppendTimeoutId(e),e.buffer=void 0}resetQueue(){if(this.operationQueue)this.operationQueue.destroy();this.operationQueue=new sn(this.tracks)}onBufferCodecs(t,e){var i;let s=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);let n="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&(("audio"in e)||("video"in e)),a=!n&&this.sourceBufferCount&&this.media&&r.some((l)=>!s[l]);if(n||a){this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`);return}if(r.forEach((l)=>{var o,u;let d=e[l],{id:c,codec:h,levelCodec:f,container:g,metadata:m,supplemental:E}=d,y=s[l],p=(o=this.transferData)==null||(o=o.tracks)==null?void 0:o[l],S=p!=null&&p.buffer?p:y,T=(S==null?void 0:S.pendingCodec)||(S==null?void 0:S.codec),x=S==null?void 0:S.levelCodec;if(!y)y=s[l]={buffer:void 0,listeners:[],codec:h,supplemental:E,container:g,levelCodec:f,metadata:m,id:c};let A=Me(T,x),b=A==null?void 0:A.replace(Ws,"$1"),I=Me(h,f),L=(u=I)==null?void 0:u.replace(Ws,"$1");if(I&&A&&b!==L){if(l.slice(0,5)==="audio")I=We(I,this.appendSource);if(this.log(`switching codec ${T} to ${I}`),I!==(y.pendingCodec||y.codec))y.pendingCodec=I;y.container=g,this.appendChangeType(l,g,I)}}),this.tracksReady||this.sourceBufferCount)e.tracks=this.sourceBufferTracks;if(this.sourceBufferCount)return;if(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&((i=e.audio)==null?void 0:i.id)==="main")this.log("Main audio-only"),this.bufferCodecEventsTotal=1;if(this.mediaSourceOpenOrEnded)this.checkPendingTracks()}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{let i=this.tracks[e];return t[e]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}appendChangeType(t,e,i){let s=`${e};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{let n=this.tracks[t];if(n){let a=n.buffer;if(a!=null&&a.changeType)this.log(`changing ${t} sourceBuffer type to ${s}`),a.changeType(s),n.codec=i,n.container=e}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:(n)=>{this.warn(`Failed to change ${t} SourceBuffer type`,n)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;let i=t.start,s=i+t.duration*0.05;if(((e=this.fragmentTracker.getAppendedFrag(i,Q.MAIN))==null?void 0:e.gap)===!0)return;let n={label:"block-audio",execute:()=>{var a,l;if(this.lastVideoAppendEnd>s||j.isBuffered((a=this.tracks.video)==null?void 0:a.buffer,s)||((l=this.fragmentTracker.getAppendedFrag(s,Q.MAIN))==null?void 0:l.gap)===!0)this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:(a)=>{this.warn("Error executing block-audio operation",a)}};this.append(n,"audio",!0)}unblockAudio(){if(this.operationQueue)this.operationQueue.unblockAudio()}onBufferAppending(t,e){let{tracks:i}=this,{data:s,type:r,parent:n,frag:a,part:l,chunkMeta:o,offset:u}=e,d=o.buffering[r],c=St(a)&&!l&&!a.gap&&!o.partial&&!o.iframe,h=null,f=!1,{sn:g,cc:m}=a,E=self.performance.now();d.start=E;let y=a.stats.buffering,p=l?l.stats.buffering:null;if(y.start===0)y.start=E;if((p==null?void 0:p.start)===0)p.start=E;let S=i.audio,T=!1;if(r==="audio"&&(S==null?void 0:S.container)==="audio/mpeg")T=!this.lastMpegAudioChunk||o.id===1||this.lastMpegAudioChunk.sn!==o.sn,this.lastMpegAudioChunk=o;let x=i.video,A=x==null?void 0:x.buffer;if(A&&g!=="initSegment"&&u!==void 0){let L=S==null?void 0:S.buffer,_=l||a;if(r==="audio"&&n!=="main"&&!(x.ending||x.ended)&&L&&j.getBuffered(L).length){let O=_.start+_.duration*0.05,H=j.getBuffered(A),M=this.currentOp("video");if(!H.length&&!M)this.blockAudio(_);else if(!j.isBuffered(A,O)&&this.lastVideoAppendEnd<O)this.blockAudio(_)}else if(r==="video"){let P=_.end,O=this.lastVideoAppendEnd-P;if(this.lastVideoAppendEnd=P,O<0||O>_.duration)this.unblockAudio();else if(this.isAudioBlocked())this.executeNext("audio")}}let b=(l||a).start,I={label:`append-${r}`,execute:()=>{var L;d.executeStart=self.performance.now();let _=(L=this.tracks[r])==null?void 0:L.buffer;if(_){if(c)h=j.timeRangesToArray(j.getBuffered(_)),f=zs(mi(h,a),a);if(T)this.updateTimestampOffset(_,b,0.1,r,g,m);else if(u!==void 0&&V(u))this.updateTimestampOffset(_,u,0.000001,r,g,m)}this.appendExecutor(s,r)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[r]);let L=self.performance.now();if(d.executeEnd=d.end=L,y.first===0)y.first=L;if((p==null?void 0:p.first)===0)p.first=L;let _={};if(this.sourceBuffers.forEach(([P,O])=>{if(P)_[P]=j.getBuffered(O)}),c){let P=this.getFragmentAppendProgress(a),O=_[r];if(O&&h){let H=j.timeRangesToArray(O),M=mi(H,a);P.progressed||(P.progressed=M-mi(h,a)>Po);let C=f&&zs(M,a);P.fullyBuffered[r]=P.fullyBuffered[r]===void 0?C:P.fullyBuffered[r]&&C}}this.hls.trigger(v.BUFFER_APPENDED,{type:r,frag:a,part:l,chunkMeta:o,parent:n,timeRanges:_})},onError:(L)=>{var _;this.clearBufferAppendTimeoutId(this.tracks[r]);let P=L.code===DOMException.QUOTA_EXCEEDED_ERR||L.name=="QuotaExceededError"||"quota"in L;if(P){if(!this._quotaEvictionPending[r]){let C=this.getBackBufferEvictionTarget(r,s.byteLength,a.type);if(C>0){this._quotaEvictionPending[r]=!0,this.log(`QuotaExceededError on "${r}" append sn: ${g} - evicting back buffer to ${C.toFixed(3)}s and retrying`);let k=this.getFlushOp(r,0,C),U=this.getClearEvictionPendingOp(r);this.insertNext([k,I,U],r);return}this.warn(`QuotaExceededError on "${r}" sn: ${g} - no back buffer available to evict`)}}if(c)this.getFragmentAppendProgress(a).errored=!0;let O={type:q.MEDIA_ERROR,parent:n,details:R.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:a,part:l,chunkMeta:o,error:L,err:L,fatal:!1},H=(_=this.media)==null?void 0:_.error;if(L.name===rn&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))O.errorAction=$e(!0);else{var M;if(P)O.details=R.BUFFER_FULL_ERROR;let C=++this.appendErrors[r],k=this.hls.config.appendErrorMaxRetry;if(this.warn(`Failed ${C}/${k+1} times to append segment in "${r}" sourceBuffer with error: ${L.message}`),C>=k)O.fatal=!P;let U=(M=this.mediaSource)==null?void 0:M.readyState;if(U==="ended"||U==="closed"||!!H)this.warn(`MediaSource readyState "${U}" during SourceBuffer${js(O.fatal,H)}`),O.details=R.MEDIA_SOURCE_REQUIRES_RESET}if(this.appendError=O,this.hls.trigger(v.ERROR,O),P&&this.hls)this.trimBuffers(a.start,1)}};this.log(`queuing "${r}" append sn: ${g}${l?" p: "+l.index:""} of ${n} playlist ${a.level} cc: ${m} offset: ${u} bytes: ${s.byteLength}`),this.append(I,r,this.isPending(this.tracks[r]))}getClearEvictionPendingOp(t){return{label:"clear",execute:()=>{this._quotaEvictionPending[t]=!1,this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(t,e,i){return this.log(`queuing "${t}" remove ${e}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,i)},onStart:()=>{},onComplete:()=>{var s;let r=(s=this.tracks[t])==null?void 0:s.buffer;this.log(`Remove request ${e}-${i} from ${t} Source Buffer complete > buffer: ${r?Pi(j.getBuffered(r)):"(detached)"}`),this.hls.trigger(v.BUFFER_FLUSHED,{type:t,start:e,end:i})},onError:(s)=>{this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`,s),this.hls.trigger(v.BUFFER_FLUSHED,{type:t,start:0,end:0,error:s})}}}onBufferFlushing(t,e){let{type:i,startOffset:s,endOffset:r}=e;if(!i||i==="audio")this.unblockAudio();if(i)this.append(this.getFlushOp(i,s,r),i);else this.sourceBuffers.forEach(([n])=>{if(n)this.append(this.getFlushOp(n,s,r),n)})}onFragParsed(t,e){let{frag:i,part:s,chunkMeta:r}=e,n=[],a=s?s.elementaryStreams:i.elementaryStreams;if(a[rt.AUDIOVIDEO])n.push("audiovideo");else{if(a[rt.AUDIO])n.push("audio");if(a[rt.VIDEO])n.push("video")}let l=()=>{let o=self.performance.now();if(i.stats.buffering.end=o,s)s.stats.buffering.end=o;let u=s?s.stats:i.stats;if(this.checkAppendProgress(i,s,r,n),!this.hls)return;if(this.hls.trigger(v.FRAG_BUFFERED,{frag:i,part:s,stats:u,id:i.type,chunkMeta:r}),!s&&i.gap&&u.retry)this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${u.retry}`)};if(n.length===0)this.log(`Fragments must have at least one ElementaryStreamType set. ${i.type} ${i.level} ${s?`part: ${s.index} of `:""}sn: ${i.sn}`);this.blockBuffers(l,n).catch((o)=>{this.warn(`Fragment buffered callback ${o.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){var i,s;let r=(i=this.hls)==null?void 0:i.config;if(!r)return;let{backBufferLength:n,frontBufferFlushThreshold:a}=r;this.trimBuffers(a,n,e.frag,e.previousFrag);let l=e.frag.elementaryStreams,{appendErrors:o}=this,u=(s=this.appendError)==null?void 0:s.sourceBufferName;Object.keys(l).forEach((d)=>{if(!l[d])return;if(o[d]=0,d===u)this.appendError=void 0;if(d==="audio"||d==="video"){if(o.audiovideo=0,u==="audiovideo")this.appendError=void 0}else if(o.audio=0,o.video=0,u!=="audiovideo")this.appendError=void 0})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){let e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var i;this.sourceBuffers.forEach(([n])=>{if(n){let a=this.tracks[n];if(!e.type||e.type===n){if(a.ending=!0,!a.ended)a.ended=!0,this.log(`${n} buffer reached EOS`)}}});let s=((i=this.overrides)==null?void 0:i.endOfStream)!==!1;if(this.sourceBufferCount>0&&!this.sourceBuffers.some(([n])=>{var a;return n&&!((a=this.tracks[n])!=null&&a.ended)}))if(this.unblockAudio(),s)this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:n}=this;if((n==null?void 0:n.readyState)!=="open"){if(n)this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${n.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),n.endOfStream(),this.hls.trigger(v.BUFFERED_TO_END,void 0)});else this.tracksEnded(),this.hls.trigger(v.BUFFERED_TO_END,void 0);else if(e.type==="video")this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(t!==null){let e=this.tracks[t];if(e)e.ending=!1}})}onLevelUpdated(t,{details:e}){if(!e.fragments.length)return;this.details=e,this.updateDuration()}updateDuration(){this.blockUntilOpen(()=>{let t=this.getDurationAndRange();if(!t)return;this.updateMediaSource(t)})}onError(t,e){if(e.details===R.BUFFER_APPEND_ERROR&&e.frag){var i;let s=(i=e.errorAction)==null?void 0:i.nextAutoLevel;if(V(s)&&s!==e.frag.level)this.resetAppendErrors()}}getBackBufferEvictionTarget(t,e,i){let{media:s}=this;if(!s)return 0;return this.fragmentTracker.getBackBufferEvictionEnd(s.currentTime,i,e)}getFragmentAppendProgress(t){var e;let i=qs(t),s=this.fragmentAppendProgress[i];if(((e=s)==null?void 0:e.stats)!==t.stats)s={stats:t.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[i]=s;return s}checkAppendProgress(t,e,i,s){if(e||!St(t)||t.gap||i.iframe||i.partial)return;let r=qs(t),n=this.fragmentAppendProgress[r];delete this.fragmentAppendProgress[r];let a=t.stats.buffering;if(a.start&&!a.first)return;let l=(n==null?void 0:n.stats)===t.stats?n:void 0;if(l!=null&&l.errored)return;let o=s.length>0&&s.every((h)=>(l==null?void 0:l.fullyBuffered[h])===!0);if(l!=null&&l.progressed||o){delete this.appendsWithoutProgress[r];return}if(!l&&s.length===0)return;let u=(this.appendsWithoutProgress[r]||0)+1,d=this.hls;if(u>=d.config.appendErrorMaxRetry)delete this.appendsWithoutProgress[r];else this.appendsWithoutProgress[r]=u;this.warn(`Fragment ${t.sn} of ${t.type} playlist ${t.level} appended ${u} time${u>1?"s":""} without buffered range growth`),d.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:t,chunkMeta:i,parent:t.type,appendsWithoutProgress:u,error:Error(`Fragment append did not increase buffered coverage (${u})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(t,e,i,s){let{hls:r,details:n,media:a}=this;if(!a||n===null)return;if(!this.sourceBufferCount)return;let l=r.config,o=a.currentTime,u=n.levelTargetDuration;e=n.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:e;let d=-1/0;if(V(e)&&e>=0){let c=Math.max(e,u);d=Math.floor(o/u)*u-c}if(i){let c=this.getLoopBackBufferFlushEnd(i,s!=null?s:null);if(c>0)d=Math.max(d,c)}if(d>0)this.flushBackBuffer(o,u,d);if(V(t)&&t>0){let c=Math.max(l.maxBufferLength,t),h=Math.max(c,u),f=Math.floor(o/u)*u+h;this.flushFrontBuffer(o,u,f)}}getLoopBackBufferFlushEnd(t,e){var i;let{media:s}=this;if(((i=this.hls)==null?void 0:i.config.loopBackBufferFlush)===!1||!(s!=null&&s.loop)||!e||t.level<=e.level)return 0;let{video:r,audiovideo:n}=t.elementaryStreams;if(r!=null&&r.partial||n!=null&&n.partial)return 0;let a=this.getEarliestElementaryStreamStart(t)-Co;if(a<=0)return 0;return this.log(`Flushing lower quality back buffer for loop: level ${t.level}, range [0-${a.toFixed(3)}]`),a}getEarliestElementaryStreamStart(t){let{audio:e,video:i,audiovideo:s}=t.elementaryStreams,r=t.start;if(s)r=Math.min(r,s.startDTS);else{if(e)r=Math.min(r,e.startDTS);if(i)r=Math.min(r,i.startDTS)}return r}flushBackBuffer(t,e,i){this.sourceBuffers.forEach(([s,r])=>{if(r){let o=j.getBuffered(r);if(o.length>0&&i>o.start(0)){var n,a,l;this.hls.trigger(v.BACK_BUFFER_REACHED,{bufferEnd:i});let u=this.tracks[s];if((n=this.details)!=null&&n.live)this.hls.trigger(v.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(u!=null&&u.ended&&!((a=this.media)!=null&&a.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${s} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:s})}}})}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach(([s,r])=>{if(r){let n=j.getBuffered(r),a=n.length;if(a<2)return;let l=n.start(a-1),o=n.end(a-1);if(i>l||t>=l&&t<=o)return;this.hls.trigger(v.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:s})}})}getDurationAndRange(){var t;let{details:e,mediaSource:i}=this;if(!e||!this.media||(i==null?void 0:i.readyState)!=="open")return null;let s=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&!!i.setLiveSeekableRange){let o=Math.max(0,e.fragmentStart),u=Math.max(o,s);return{duration:1/0,start:o,end:u}}return{duration:1/0}}let r=(t=this.overrides)==null?void 0:t.duration;if(r){if(!V(r))return null;return{duration:r}}let n=this.media.duration,a=V(i.duration)?i.duration:0;if(s>a&&s>n||!V(n))return{duration:s};return null}updateMediaSource({duration:t,start:e,end:i}){let s=this.mediaSource;if(!s||!this.media||s.readyState!=="open")return;if(s.duration!==t){if(V(t))this.log(`Updating MediaSource duration to ${t.toFixed(3)}`);s.duration=t}if(e!==void 0&&i!==void 0)this.log(`MediaSource duration is set to ${s.duration}. Setting seekable range to ${e}-${i}.`),s.setLiveSeekableRange(e,i)}get tracksReady(){let t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${yt(i)}`),this.tracksReady){var s;let r=(s=this.transferData)==null?void 0:s.tracks;if(r&&Object.keys(r).length)this.attachTransferred();else this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let t={};this.sourceBuffers.forEach(([e,i])=>{if(e){let s=this.tracks[e];t[e]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(v.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{let t=Error("could not create source buffer for media codec(s)");this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){let{tracks:t,sourceBuffers:e,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(let r in t){let n=r,a=t[n];if(this.isPending(a)){let l=this.getTrackCodec(a,n),o=`${a.container};codecs=${l}`;a.codec=l,this.log(`creating sourceBuffer(${o})${this.currentOp(n)?" Queued":""} ${yt(a)}`);try{let u=i.addSourceBuffer(o),d=gi(n),c=[n,u];e[d]=c,a.buffer=u}catch(u){var s;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(n),(s=this.operationQueue)==null||s.removeBlockers(),delete this.tracks[n],this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:n,mimeType:o,parent:a.id});return}this.trackSourceBuffer(n,a)}}this.bufferCreated()}clearBufferAppendTimeoutId(t){if(!t)return;self.clearTimeout(t.bufferAppendTimeoutId),t.bufferAppendTimeoutId=void 0}getTrackCodec(t,e){let{supplemental:i,codec:s}=t;if(i&&(e==="video"||e==="audiovideo")&&Ee(i,"video"))s=Ha(s,i);let r=Me(s,t.levelCodec);if(r){if(e.slice(0,5)==="audio")return We(r,this.appendSource);return r}return""}trackSourceBuffer(t,e){let i=e.buffer;if(!i)return;let s=this.getTrackCodec(e,t);if(this.tracks[t]={buffer:i,codec:s,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource)this.addBufferListener(t,"bufferedchange",(r,n)=>{let a=n.removedRanges;if(a!=null&&a.length)this.log(`${r} buffer removed ${Pi(a)}`),this.hls.trigger(v.BUFFER_FLUSHED,{type:r,start:a.start(0),end:a.end(a.length-1)})})}get mediaSrc(){var t,e;let i=((t=this.media)==null||(e=t.querySelector)==null?void 0:e.call(t,"source"))||this.media;return i==null?void 0:i.src}onSBUpdateStart(t){let e=this.currentOp(t);if(!e)return;e.onStart()}onSBUpdateEnd(t){var e,i;if(((e=this.mediaSource)==null?void 0:e.readyState)==="closed"){this.resetBuffer(t);return}let s=this.currentOp(t);if(!s)return;if(s.onComplete(),(i=this.tracks[t])==null||(i=i.buffer)==null?void 0:i.updating){this.log(`${t} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(t)});return}this.shiftAndExecuteNext(t)}onSBUpdateError(t,e){var i;let s=(i=this.mediaSource)==null?void 0:i.readyState,r=Error(`${t} SourceBuffer error. MediaSource readyState: ${s}`);this.error(`${r.message}`,e),this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});let n=this.currentOp(t);if(n)n.onError(r)}updateTimestampOffset(t,e,i,s,r,n){let a=e-t.timestampOffset;if(Math.abs(a)>=i)this.log(`Updating ${s} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${n})`),t.timestampOffset=e}removeExecutor(t,e,i){let{media:s,mediaSource:r}=this,n=this.tracks[t],a=n==null?void 0:n.buffer;if(!s||!r||!a)throw Error(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`);let l=V(s.duration)?s.duration:1/0,o=V(r.duration)?r.duration:1/0,u=Math.max(0,e);if(u>=o){var d;(d=this.currentOp(t))==null||d.onComplete(),this.shiftAndExecuteNext(t);return}let c=Math.min(i,l,o);if(c>u&&(!n.ending||n.ended))n.ended=!1,this.log(`Removing [${u},${c}] from the ${t} SourceBuffer`),a.remove(u,c);else throw Error(`Cannot remove ${c<=u?`invalid range (${u} >= ${c}) `:""}from the ${t} SourceBuffer${n.ending?" while track ending":""}`)}appendExecutor(t,e){let i=this.tracks[e],s=i==null?void 0:i.buffer;if(!s)throw new nn(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){let r=this.calculateAppendTimeoutTime(s);i.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(e,s,r),r)}s.appendBuffer(t)}appendTimeoutHandler(t,e,i){this.log(`Received timeout after ${i}ms for append on ${t} source buffer. Aborting and triggering error.`);try{e.abort()}catch(r){this.log(`Failed to abort append on ${t} source buffer after timeout.`)}let s=this.currentOp(t);if(s)s.onError(Error(`${t}-append-timeout`))}calculateAppendTimeoutTime(t){let e=$r;if(this.details)e=this.details.levelTargetDuration;let i=2*e*1000;if(this.media===null)return i;let s=j.bufferInfo(t,this.media.currentTime,0);if(!s.len)return i;return i=Math.max(s.len*1000,i),Math.max(this.hls.config.appendTimeout,i)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch((e)=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}isAudioBlocked(){var t;return((t=this.currentOp("audio"))==null?void 0:t.label)==="block-audio"}isAudioBlocking(){if(this.operationQueue)return this.operationQueue.audioBlocking();return!1}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);let{operationQueue:i}=this,r=e.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:e.map((n)=>this.appendBlocker(n));return Promise.all(r).then((n)=>{if(i!==this.operationQueue)return;t(),this.stepOperationQueue(this.sourceBufferTypes)})}stepOperationQueue(t){t.forEach((e)=>{var i;let s=(i=this.tracks[e])==null?void 0:i.buffer;if(!s||s.updating||e==="audio"&&this.isAudioBlocked())return;this.shiftAndExecuteNext(e)})}append(t,e,i){if(this.operationQueue)this.operationQueue.append(t,e,i)}insertNext(t,e){if(this.operationQueue)this.operationQueue.insertNext(t,e)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){if(this.operationQueue)return this.operationQueue.current(t);return null}executeNext(t){if(t&&this.operationQueue)this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){if(this.operationQueue)this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter((t)=>!!t)}addBufferListener(t,e,i){let s=this.tracks[t];if(!s)return;let r=s.buffer;if(!r)return;let n=i.bind(this,t);s.listeners.push({event:e,listener:n}),pt(r,e,n)}removeBufferListeners(t){let e=this.tracks[t];if(!e)return;let i=e.buffer;if(!i)return;e.listeners.forEach((s)=>{ut(i,s.event,s.listener)}),e.listeners.length=0}}function Ys(t){let e=t.querySelectorAll("source");[].slice.call(e).forEach((i)=>{t.removeChild(i)})}function ko(t,e){let i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}function gi(t){return t==="audio"?1:0}function js(t,e){return`${t?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function qs(t){return`${t.type}_${t.sn}_${t.level}`}function mi(t,e){let{start:i,end:s}=e,r=0;for(let n=0;n<t.length;n++){let a=t[n];if(a.start>=s)break;let l=Math.max(i,a.start),o=Math.min(s,a.end);if(o>l)r+=o-l}return r}function zs(t,e){return e.duration-t<=0.05}class Zi{constructor(t){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){if(this.hls)this.unregisterListener();if(this.timer||this.observer)this.stopCapping();this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){let{hls:t}=this;if(t)t.on(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(v.MANIFEST_PARSED,this.onManifestParsed,this),t.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(v.BUFFER_CODECS,this.onBufferCodecs,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:t}=this;if(t)t.off(v.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(v.MANIFEST_PARSED,this.onManifestParsed,this),t.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(v.BUFFER_CODECS,this.onBufferCodecs,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){if(!this.hls)return;let i=this.hls.levels[e.droppedLevel];if(this.isLevelAllowed(i))this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){let i=e.media;if(this.clientRect=null,!this.hls)return;if(i instanceof HTMLVideoElement){if(this.media=i,this.hls.config.capLevelToPlayerSize)this.observe()}else this.media=null;if((this.timer||this.observer)&&this.hls.levels.length>1)this.detectPlayerSize()}onManifestParsed(t,e){if(this.restrictedLevels=[],e.video)this.startCapping();this.onLevelsUpdated()}onLevelsUpdated(){if(!this.hls)return;if((this.timer||this.observer)&&(V(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(this.observer===void 0&&this.timer===void 0){let t=this.hls.levels;if(t.length>1&&t.some((e)=>!!e.videoCodec))this.startCapping()}}onBufferCodecs(t,e){if(e.video)this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}let t=this.hls.levels;if(t.length>1){let e=this.hls,i=this.getMaxLevel(t.length-1);if(i!==this.autoLevelCapping)e.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`);if(e.autoLevelCapping=i,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController)this.streamController.nextLevelSwitch();this.autoLevelCapping=e.autoLevelCapping}else if(t.length===1)this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;let e=this.hls.levels;if(!e.length)return-1;let i=e.filter((s,r)=>this.isLevelAllowed(s)&&r<=t);if(!this.observer)this.clientRect=null;return Zi.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){let t=self.ResizeObserver;if(t)this.observer=new t((e)=>{var i;let s=(i=e[0])==null?void 0:i.contentRect;if(s)this.clientRect=s,this.detectPlayerSize()});if(this.observer&&this.media)this.observer.observe(this.media)}startCapping(){var t;if(this.timer||this.observer||!((t=this.hls)!=null&&t.config.capLevelToPlayerSize))return;if(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),!this.observer)this.timer=self.setInterval(this.detectPlayerSize.bind(this),1000);this.detectPlayerSize()}stopCapping(){if(this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer)self.clearInterval(this.timer),this.timer=void 0;if(this.observer)this.observer.disconnect(),this.observer=void 0}getDimensions(){if(this.clientRect)return this.clientRect;let t=this.media,e={width:0,height:0};if(t){let i=t.getBoundingClientRect();if(e.width=i.width,e.height=i.height,!e.width&&!e.height)e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls)return t;let{ignoreDevicePixelRatio:e,maxDevicePixelRatio:i}=this.hls.config;if(!e)try{t=self.devicePixelRatio}catch(s){}return Math.min(t,i)}isLevelAllowed(t){return!this.restrictedLevels.some((i)=>t.bitrate===i.bitrate&&t.width===i.width&&t.height===i.height)}static getMaxLevelByMediaSize(t,e,i){if(!(t!=null&&t.length))return-1;let s=(a,l)=>{if(!l)return!0;return a.width!==l.width||a.height!==l.height},r=t.length-1,n=Math.max(e,i);for(let a=0;a<t.length;a+=1){let l=t[a];if((l.width>=n||l.height>=n)&&s(l,t[a+1])){r=a;break}}return r}}var Oo=300000;class on extends wt{constructor(t){super("content-steering",t.logger);this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.registerListeners()}registerListeners(){let t=this.hls;t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(v.MANIFEST_PARSED,this.onManifestParsed,this),t.on(v.ERROR,this.onError,this)}unregisterListeners(){let t=this.hls;if(!t)return;t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(v.MANIFEST_PARSED,this.onManifestParsed,this),t.off(v.ERROR,this.onError,this)}pathways(){return(this.levels||[]).reduce((t,e)=>{if(t.indexOf(e.pathwayId)===-1)t.push(e.pathwayId);return t},[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let t=this.timeToLoad*1000-(performance.now()-this.updated);if(t>0){this.scheduleRefresh(this.uri,t);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){if(this.started=!1,this.loader)this.loader.destroy(),this.loader=null;this.clearTimeout()}clearTimeout(){if(this.reloadTimer!==-1)self.clearTimeout(this.reloadTimer),this.reloadTimer=-1}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){let e=this.levels;if(e)this.levels=e.filter((i)=>i!==t)}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){let{contentSteering:i}=e;if(i===null)return;if(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started)this.startLoad()}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){let{errorAction:i}=e;if((i==null?void 0:i.action)===ht.SendAlternateToPenaltyBox&&i.flags&ct.MoveAllAlternatesMatchingHost){let s=this.levels,r=this._pathwayPriority,n=this.pathwayId;if(e.context){let{groupId:a,pathwayId:l,type:o}=e.context;if(a&&s)n=this.getPathwayForGroupId(a,o,n);else if(l)n=l}if(!(n in this.penalizedPathways))this.penalizedPathways[n]=performance.now();if(!r&&s)r=this.pathways();if(r&&r.length>1){if(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==n,!i.resolved&&(e.details!==R.BUFFER_APPEND_ERROR||e.fatal))this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${n} levels: ${s?s.length:s} priorities: ${yt(r)} penalized: ${yt(this.penalizedPathways)}`)}}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(e.length===0){let i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}if(e.length!==t.length)this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`);return e}getLevelsForPathway(t){if(this.levels===null)return[];return this.levels.filter((e)=>t===e.pathwayId)}updatePathwayPriority(t){this._pathwayPriority=t;let e,i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach((r)=>{if(s-i[r]>Oo)delete i[r]});for(let r=0;r<t.length;r++){let n=t[r];if(n in i)continue;if(n===this.pathwayId)return;let a=this.hls.nextLoadLevel,l=this.hls.levels[a];if(e=this.getLevelsForPathway(n),e.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,qr(e),this.hls.trigger(v.LEVELS_UPDATED,{levels:e});let o=this.hls.levels[a];if(l&&o&&this.levels){if(o.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&o.bitrate!==l.bitrate)this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${o.bitrate}`);this.hls.nextLoadLevel=a}break}}}getPathwayForGroupId(t,e,i){let s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r<s.length;r++)if(e===J.AUDIO_TRACK&&s[r].hasAudioGroup(t)||e===J.SUBTITLE_TRACK&&s[r].hasSubtitleGroup(t))return s[r].pathwayId;return i}clonePathways(t){let e=this.levels;if(!e)return;let i={},s={};t.forEach((r)=>{let{ID:n,"BASE-ID":a,"URI-REPLACEMENT":l}=r;if(e.some((u)=>u.pathwayId===n))return;let o=this.getLevelsForPathway(a).map((u)=>{let d=new nt(u.attrs);d["PATHWAY-ID"]=n;let c=d.AUDIO&&`${d.AUDIO}_clone_${n}`,h=d.SUBTITLES&&`${d.SUBTITLES}_clone_${n}`;if(c)i[d.AUDIO]=c,d.AUDIO=c;if(h)s[d.SUBTITLES]=h,d.SUBTITLES=h;let f=ln(u.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new ji({attrs:d,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:f,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let m=1;m<u.audioGroups.length;m++)g.addGroupId("audio",`${u.audioGroups[m]}_clone_${n}`);if(u.subtitleGroups)for(let m=1;m<u.subtitleGroups.length;m++)g.addGroupId("text",`${u.subtitleGroups[m]}_clone_${n}`);return g});e.push(...o),Xs(this.audioTracks,i,l,n),Xs(this.subtitleTracks,s,l,n)})}loadSteeringManifest(t){let e=this.hls.config,i=e.loader;if(this.loader)this.loader.destroy();this.loader=new i(e);let s;try{s=new self.URL(t)}catch(u){this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${t}`);return}if(s.protocol!=="data:"){let u=(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate)|0;ie(s,"_HLS_pathway",this.pathwayId),ie(s,"_HLS_throughput",""+u)}let r={type:J.STEERING_MANIFEST,responseType:"json",url:s.href},n=e.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},l={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},o={onSuccess:(u,d,c,h)=>{this.log(`Loaded steering manifest: "${s}"`);let f=u.data;if((f==null?void 0:f.VERSION)!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;let{"RELOAD-URI":g,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":E}=f;if(g)try{this.uri=new self.URL(g,s).href}catch(p){this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}if(this.scheduleRefresh(this.uri||c.url),m)this.clonePathways(m);let y={steeringManifest:f,url:s.toString()};if(this.hls.trigger(v.STEERING_MANIFEST_LOADED,y),E)this.updatePathwayPriority(E)},onError:(u,d,c,h)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${d.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let f=this.timeToLoad*1000;if(u.code===429){let g=this.loader;if(typeof(g==null?void 0:g.getResponseHeader)==="function"){let m=g.getResponseHeader("Retry-After");if(m)f=parseFloat(m)*1000}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,f)},onTimeout:(u,d,c)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,l,o)}scheduleRefresh(t,e=this.timeToLoad*1000){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;let s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1000)},e)}}function Xs(t,e,i,s){if(!t)return;Object.keys(e).forEach((r)=>{let n=t.filter((a)=>a.groupId===r).map((a)=>{let l=dt({},a);return l.details=void 0,l.attrs=new nt(l.attrs),l.url=l.attrs.URI=ln(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),l.groupId=l.attrs["GROUP-ID"]=e[r],l.attrs["PATHWAY-ID"]=s,l});t.push(...n)})}function ln(t,e,i,s){if(e){let{[i]:l}=s;if(l){let o=l[e];if(o)return o}}let{HOST:r,PARAMS:n}=s,a=new self.URL(t);if(r)a.hostname=r;if(n)Object.keys(n).sort().forEach((l)=>{if(l)ie(a,l,n[l])});return a.href}class un{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(v.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(v.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){if(this.timer)clearInterval(this.timer);this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){let i=this.hls.config;if(i.capLevelOnFPSDrop){let s=e.media instanceof self.HTMLVideoElement?e.media:null;if(this.media=s,s&&typeof s.getVideoPlaybackQuality==="function")this.isVideoPlaybackQualityAvailable=!0;self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,i){let s=performance.now();if(e){if(this.lastTime){let r=s-this.lastTime,n=i-this.lastDroppedFrames,a=e-this.lastDecodedFrames,l=1000*n/r,o=this.hls;if(o.trigger(v.FPS_DROP,{currentDropped:n,currentDecoded:a,totalDroppedFrames:i}),l>0){if(n>o.config.fpsDroppedMonitoringThreshold*a){let u=o.currentLevel;if(o.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(o.autoLevelCapping===-1||o.autoLevelCapping>=u))u=u-1,o.trigger(v.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:o.currentLevel}),o.autoLevelCapping=u,this.streamController.nextLevelSwitch()}}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){let t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){let e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}var pi={exports:{}},Qs;function wo(){if(Qs)return pi.exports;return Qs=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}if(Object.create){if(s.prototype=Object.create(null),!new s().__proto__)i=!1}function r(o,u,d){this.fn=o,this.context=u,this.once=d||!1}function n(o,u,d,c,h){if(typeof d!=="function")throw TypeError("The listener must be a function");var f=new r(d,c||o,h),g=i?i+u:u;if(!o._events[g])o._events[g]=f,o._eventsCount++;else if(!o._events[g].fn)o._events[g].push(f);else o._events[g]=[o._events[g],f];return o}function a(o,u){if(--o._eventsCount===0)o._events=new s;else delete o._events[u]}function l(){this._events=new s,this._eventsCount=0}l.prototype.eventNames=function(){var u=[],d,c;if(this._eventsCount===0)return u;for(c in d=this._events)if(e.call(d,c))u.push(i?c.slice(1):c);if(Object.getOwnPropertySymbols)return u.concat(Object.getOwnPropertySymbols(d));return u},l.prototype.listeners=function(u){var d=i?i+u:u,c=this._events[d];if(!c)return[];if(c.fn)return[c.fn];for(var h=0,f=c.length,g=Array(f);h<f;h++)g[h]=c[h].fn;return g},l.prototype.listenerCount=function(u){var d=i?i+u:u,c=this._events[d];if(!c)return 0;if(c.fn)return 1;return c.length},l.prototype.emit=function(u,d,c,h,f,g){var m=i?i+u:u;if(!this._events[m])return!1;var E=this._events[m],y=arguments.length,p,S;if(E.fn){if(E.once)this.removeListener(u,E.fn,void 0,!0);switch(y){case 1:return E.fn.call(E.context),!0;case 2:return E.fn.call(E.context,d),!0;case 3:return E.fn.call(E.context,d,c),!0;case 4:return E.fn.call(E.context,d,c,h),!0;case 5:return E.fn.call(E.context,d,c,h,f),!0;case 6:return E.fn.call(E.context,d,c,h,f,g),!0}for(S=1,p=Array(y-1);S<y;S++)p[S-1]=arguments[S];E.fn.apply(E.context,p)}else{var T=E.length,x;for(S=0;S<T;S++){if(E[S].once)this.removeListener(u,E[S].fn,void 0,!0);switch(y){case 1:E[S].fn.call(E[S].context);break;case 2:E[S].fn.call(E[S].context,d);break;case 3:E[S].fn.call(E[S].context,d,c);break;case 4:E[S].fn.call(E[S].context,d,c,h);break;default:if(!p)for(x=1,p=Array(y-1);x<y;x++)p[x-1]=arguments[x];E[S].fn.apply(E[S].context,p)}}}return!0},l.prototype.on=function(u,d,c){return n(this,u,d,c,!1)},l.prototype.once=function(u,d,c){return n(this,u,d,c,!0)},l.prototype.removeListener=function(u,d,c,h){var f=i?i+u:u;if(!this._events[f])return this;if(!d)return a(this,f),this;var g=this._events[f];if(g.fn){if(g.fn===d&&(!h||g.once)&&(!c||g.context===c))a(this,f)}else{for(var m=0,E=[],y=g.length;m<y;m++)if(g[m].fn!==d||h&&!g[m].once||c&&g[m].context!==c)E.push(g[m]);if(E.length)this._events[f]=E.length===1?E[0]:E;else a(this,f)}return this},l.prototype.removeAllListeners=function(u){var d;if(u){if(d=i?i+u:u,this._events[d])a(this,d)}else this._events=new s,this._eventsCount=0;return this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=i,l.EventEmitter=l,t.exports=l}(pi),pi.exports}var Fo=wo(),dn=hr(Fo),Be=2,Mo=100;class cn extends Xi{constructor(t,e){super("gap-controller",t.logger);this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;if((i=this.media)!=null&&i.seeking)return;this.waiting=self.performance.now(),this.tick()},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=e,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){let{hls:t}=this;if(t)t.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.BUFFER_APPENDED,this.onBufferAppended,this)}unregisterListeners(){let{hls:t}=this;if(t)t.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.BUFFER_APPENDED,this.onBufferAppended,this)}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(Mo),this.mediaSource=e.mediaSource;let i=this.media=e.media;pt(i,"playing",this.onMediaPlaying),pt(i,"waiting",this.onMediaWaiting),pt(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();let{media:i}=this;if(i)ut(i,"playing",this.onMediaPlaying),ut(i,"waiting",this.onMediaWaiting),ut(i,"ended",this.onMediaEnded),this.media=null;this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var t;let e=((t=this.hls)==null?void 0:t.config.timelineOffset)||0;if(this.media)return Math.max(this.media.currentTime,e);return e}tick(){var t;if(!((t=this.media)!=null&&t.readyState)||!this.hasBuffered)return;let e=this.getCurrentTime();if(this.media.currentTime<e)return;this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e}poll(t,e){var i,s;let r=(i=this.hls)==null?void 0:i.config;if(!r)return;let n=this.media;if(!n)return;let{seeking:a}=n,l=this.seeking&&!a,o=!this.seeking&&a,u=n.paused&&!a||n.ended||n.playbackRate===0;if(this.seeking=a,t!==e){if(e)this.ended=0;if(this.moved=!0,!a){if(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!u&&t>e)this.nudgeOnVideoHole(t,e)}if(this.waiting===0)this.stallResolved(t);return}if(o||l){if(l)this.stallResolved(t);return}if(u){if(this.skipRetry=this.nudgeRetry=0,this.stallResolved(t),!this.ended&&n.ended&&this.hls)this.ended=t||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:!1});return}if(!j.getBuffered(n).length){this.skipRetry=this.nudgeRetry=0;return}let d=j.bufferInfo(n,t,0),c=this.fragmentTracker;if(c&&this.hls)tr(d,t,c,this.hls);let h=d.nextStart||0;if(a&&c&&this.hls){let x=Zs(this.hls.inFlightFragments,t),A=d.len>Be,b=!h||x||h-t>Be&&!c.getPartialFragment(t);if(A||b)return;this.moved=!1}let f=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&c){if(!(d.len>0)&&!h)return;let A=Math.max(h,d.start||0)-t,I=f!=null&&f.live?f.targetduration*2:Be,L=de(t,c);if(A>0&&(A<=I||L)){if(!n.paused)this._trySkipBufferHole(L);return}}let g=r.detectStallWithCurrentTimeMs,m=self.performance.now(),E=this.waiting,y=this.stalled;if(y===null)if(E>0&&m-E<g)y=this.stalled=E;else{this.stalled=m;return}let p=m-y;if(!a&&(p>=g||E&&this.moved)&&this.hls){var S;if(((S=this.mediaSource)==null?void 0:S.readyState)==="ended"&&!(f!=null&&f.live)&&Math.abs(t-((f==null?void 0:f.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(v.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return;if(n.currentTime!==t){let x=t;t=n.currentTime,this.moved=!0,this.log(`currentTime changed ${x} > ${t}`);return}}let T=j.bufferInfo(n,t,r.maxBufferHole);this._tryFixBufferStall(T,p,t)}stallResolved(t){let e=this.stalled;if(e&&this.hls){if(this.stalled=null,this.stallReported){let i=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(v.STALL_RESOLVED,{})}}}nudgeOnVideoHole(t,e){var i;let s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&t>s.end(0)){let r=j.bufferedInfo(j.timeRangesToArray(this.buffered.audio),t,0);if(r.len>1&&e>=r.start){let n=j.timeRangesToArray(s),a=j.bufferedInfo(n,e,0).bufferedIndex;if(a>-1&&a<n.length-1){let l=j.bufferedInfo(n,t,0).bufferedIndex,o=n[a].end,u=n[a+1].start;if((l===-1||l>a)&&u-o<1&&t-o<2){let d=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${o} -> ${u} buffered index: ${l}`);this.warn(d.message),this.media.currentTime+=0.000001;let c=de(t,this.fragmentTracker);if(c&&"fragment"in c)c=c.fragment;else if(!c)c=void 0;let h=j.bufferInfo(this.media,t,0);this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:c,buffer:h.len,bufferInfo:h})}}}}}_tryFixBufferStall(t,e,i){var s,r;let{fragmentTracker:n,media:a}=this,l=(s=this.hls)==null?void 0:s.config;if(!a||!n||!l)return;let o=(r=this.hls)==null?void 0:r.latestLevelDetails,u=de(i,n);if(u||o!=null&&o.live&&i<o.fragmentStart){if(this._trySkipBufferHole(u)||!this.media)return}let d=t.buffered,c=this.adjacentTraversal(t,i);if((d&&d.length>1&&t.len>l.maxBufferHole||t.nextStart&&(t.nextStart-i<l.maxBufferHole||c))&&(e>l.highBufferWatchdogPeriod*1000||this.waiting))this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t)}adjacentTraversal(t,e){let i=this.fragmentTracker,s=t.nextStart;if(i&&s){let r=i.getFragAtPos(e,Q.MAIN),n=i.getFragAtPos(s,Q.MAIN);if(r&&n)return n.sn-r.sn<2}return!1}_reportStall(t){let{hls:e,media:i,stallReported:s,stalled:r}=this;if(!s&&r!==null&&i&&e){this.stallReported=!0;let n=Error(`Playback stalling at @${i.currentTime} due to low buffer (${yt(t)})`);this.warn(n.message),e.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:t.len,bufferInfo:t,stalled:{start:r}})}}_trySkipBufferHole(t){let{fragmentTracker:e,media:i,hls:s}=this,r=s==null?void 0:s.config;if(!i||!e||!r)return 0;let n=i.currentTime,a=j.bufferInfo(i,n,0);tr(a,n,e,s);let l=n<a.start?a.start:a.nextStart;if(l){let u=a.len<=r.maxBufferHole,d=a.len>0&&a.len<1&&i.readyState<3,c=l-n;if(c>0&&(u||d)){if(c>r.maxBufferHole){let E=!1;if(n===0){let y=e.getAppendedFrag(0,Q.MAIN);if(y&&l<y.end)E=!0}if(!E&&t){var o;if(!((o=s.loadLevelObj)!=null&&o.details))return 0;if(Zs(s.inFlightFragments,l))return 0;let p=!1,S=t.end;while(S<l){let T=de(S,e),x=T?T.duration:0;if(x>0)S+=x;else{p=!0;break}}if(p)return 0}}let{nudgeMaxRetry:h,skipBufferHolePadding:f}=r,g=++this.skipRetry>h,m=Math.max(l,n)+f;if(!g)this.warn(`skipping hole, adjusting currentTime from ${n} to ${m}`),this.moved=!0,i.currentTime=m;if(!(t!=null&&t.gap)||g){let E=Error(g?`Playhead still not moving after seeking over buffer hole from ${n} to ${m} after ${r.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${n} to ${m}`),y={type:q.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:g,error:E,reason:E.message,buffer:a.len,bufferInfo:a};if(t)if("fragment"in t)y.part=t;else y.frag=t;s.trigger(v.ERROR,y)}return m}}return 0}_tryNudgeBuffer(t){let{hls:e,media:i,nudgeRetry:s}=this,r=e==null?void 0:e.config;if(!i||!r)return 0;let n=i.currentTime;if(this.nudgeRetry++,s<r.nudgeMaxRetry){let a=n+(s+1)*r.nudgeOffset,l=Error(`Nudging 'currentTime' from ${n} to ${a}`);this.warn(l.message),i.currentTime=a,e.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:t.len,bufferInfo:t})}else{let a=Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(a.message),e.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:a,fatal:!0,buffer:t.len,bufferInfo:t})}}}function Zs(t,e){let i=Js(t.main);if(i&&i.start<=e)return i;let s=Js(t.audio);if(s&&s.start<=e)return s;return null}function Js(t){if(!t)return null;switch(t.state){case w.IDLE:case w.STOPPED:case w.ENDED:case w.ERROR:return null}return t.frag}function de(t,e){return e.getAppendedFrag(t,Q.MAIN)||e.getPartialFragment(t)}function tr(t,e,i,s){if(s.latestLevelDetails,de(e,i),ki(s.config));}var vt=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function No(t,e,i,s="",r="disabled"){let n=t.ownerDocument.createElement("track");if(n.kind=e,n.label=i,s)n.srclang=s;return n.src="data:,WEBVTT",n.track.mode=r,t.appendChild(n),n}function $o(t,e,i,s){let r=t.mode;if(r==="disabled")t.mode="hidden";if(t.cues&&t.cues.length>0){let n=Uo(t.cues,e,i);for(let a=0;a<n.length;a++)if(!s||s(n[a]))t.removeCue(n[a])}if(r==="disabled")t.mode=r}function Bo(t,e){if(e<=t[0].startTime)return 0;let i=t.length-1;if(e>t[i].endTime)return-1;let s=0,r=i,n;while(s<=r)if(n=Math.floor((r+s)/2),e<t[n].startTime)r=n-1;else if(e>t[n].startTime&&s<i)s=n+1;else return n;return t[s].startTime-e<e-t[r].startTime?s:r}function Uo(t,e,i){let s=[],r=Bo(t,e);if(r>-1)for(let n=r,a=t.length;n<a;n++){let l=t[n];if(l.startTime>=e&&l.endTime<=i)s.push(l);else if(l.startTime>i)return s}return s}var Go=0.25;function Oi(){if(typeof self>"u")return;return self.VTTCue||self.TextTrackCue}function er(t,e,i,s,r){let n=new t(e,i,"");try{if(n.value=s,r)n.type=r}catch(a){n=new t(e,i,yt(r?Tt({type:r},s):s))}return n}var ke=(()=>{let t=Oi();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class hn{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{if(!this.hls)return;this.hls.trigger(v.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:t}=this;if(t)t.on(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(v.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(v.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}_unregisterListeners(){let{hls:t}=this;if(t)t.off(v.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(v.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(v.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this)}onMediaAttaching(t,e){this.media=e.media}onMediaAttached(){var t;let e=(t=this.hls)==null?void 0:t.latestLevelDetails;if(e)this.updateDateRangeCues(e)}onMediaDetaching(t,e){if(this.media=null,!!e.transferMedia)return;if(this.id3Track)this.id3Track.remove(),this.id3Track=null;this.dateRangeCuesAppended={}}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){return No(t,"metadata","id3","","hidden")}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;let{samples:r}=e;if(!this.id3Track)this.id3Track=this.createTrack(this.media);let n=Oi();if(!n)return;for(let a=0;a<r.length;a++){let l=r[a].type;if(l===vt.emsg&&!i||!s)continue;let o=Sr(r[a].data),u=r[a].pts,d=u+r[a].duration;if(d>ke)d=ke;if(d-u<=0)d=u+Go;for(let h=0;h<o.length;h++){let f=o[h];if(!Tr(f)){this.updateId3CueEnds(u,l);let g=er(n,u,d,f,l);if(g)this.id3Track.track.addCue(g)}}}}updateId3CueEnds(t,e){var i;let s=(i=this.id3Track)==null?void 0:i.track.cues;if(s)for(let r=s.length;r--;){let n=s[r];if(n.type===e&&n.startTime<t&&n.endTime===ke)n.endTime=t}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:s}){let{id3Track:r,hls:n}=this;if(!n)return;let{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:l}}=n;if(r&&(a||l)){let o;if(s==="audio")o=(u)=>u.type===vt.audioId3&&l;else if(s==="video")o=(u)=>u.type===vt.emsg&&a;else o=(u)=>u.type===vt.audioId3&&l||u.type===vt.emsg&&a;$o(r.track,e,i,o)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){if(Math.abs(e.drift)>0.01)this.updateDateRangeCues(e.details)}updateDateRangeCues(t,e){if(!this.hls||!this.media)return;let{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;let a=Oi();if(!t.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:o}=t,u=Object.keys(o),d=this.dateRangeCuesAppended;if(l&&e){var c;if((c=l.track.cues)!=null&&c.length){let g=Object.keys(d).filter((m)=>u.indexOf(m)===-1);for(let m=g.length;m--;){var h;let E=g[m],y=(h=d[E])==null?void 0:h.cues;if(delete d[E],y)Object.keys(y).forEach((p)=>{let S=y[p];if(S){S.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(S)}catch(T){}}})}}else d=this.dateRangeCuesAppended={}}let f=t.fragments[t.fragments.length-1];if(u.length===0||!V(f==null?void 0:f.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));for(let g=0;g<u.length;g++){let m=u[g],E=o[m],y=E.startTime,p=d[m],S=(p==null?void 0:p.cues)||{},T=(p==null?void 0:p.durationKnown)||!1,x=ke,{duration:A,endDate:b}=E;if(b&&A!==null)x=y+A,T=!0;else if(E.endOnNext&&!T){let L=u.reduce((_,P)=>{if(P!==E.id){let O=o[P];if(O.class===E.class&&O.startDate>E.startDate&&(!_||E.startDate<_.startDate))return O}return _},null);if(L)x=L.startTime,T=!0}let I=Object.keys(E.attr);for(let L=0;L<I.length;L++){let _=I[L];if(!oo(_))continue;let P=S[_];if(P){if(T&&!(p!=null&&p.durationKnown))P.endTime=x;else if(Math.abs(P.startTime-y)>0.01)P.startTime=y,P.endTime=x}else if(a){let O=E.attr[_];if(lo(_))O=Ar(O);let M=er(a,y,x,{key:_,data:O},vt.dateRange);if(M)M.id=m,this.id3Track.track.addCue(M),S[_]=M}}d[m]={cues:S,dateRange:E,durationKnown:T}}}}class fn{constructor(t){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{let{media:e}=this,i=this.levelDetails;if(!e||!i||!this.hls)return;this.currentTime=e.currentTime;let s=this.hls.config,r=this.computeLatency();if(r===null)return;this._latency=r;let{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=s;if(!n||a===1||!i.live)return;let l=this.targetLatency;if(l===null)return;let o=r-l,u=Math.min(this.maxLatency,l+i.targetduration);if(o<u&&o>0.05&&this.forwardBufferLength>1){let c=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-0.75*o-this.edgeStalled))*20)/20,f=Math.min(c,Math.max(1,h));this.changeMediaPlaybackRate(e,f)}else if(e.playbackRate!==1&&e.playbackRate!==0)this.changeMediaPlaybackRate(e,1)},this.hls=t,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var t;let e=(t=this.hls)==null?void 0:t.config;if(!e)return 0;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let i=this.levelDetails;return i?e.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){let t=this.levelDetails;if(t===null||!this.hls)return null;let e=this.hls.config,{holdBack:i,partHoldBack:s,targetduration:r}=t,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:l}=e,o=this.hls.userConfig,u=l?s||i:i;if(this._targetLatencyUpdated||o.liveSyncDuration||o.liveSyncDurationCount||u===0)u=n!==void 0?n:a*r;let d=r;return u+Math.min(this.stallCount*e.liveSyncOnStallIncrease,d)}set targetLatency(t){if(!this.hls)return;this.stallCount=0,this.hls.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){let t=this.estimateLiveEdge(),e=this.targetLatency;if(t===null||e===null||!this.hls)return null;let i=this.levelDetails;if(i===null)return null;let s=i.edge,r=t-e-this.edgeStalled,n=s-i.totalduration,a=s-(this.hls.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),a)}get drift(){let t=this.levelDetails;if(t===null)return 1;return t.drift}get edgeStalled(){let t=this.levelDetails;if(t===null||!this.hls)return 0;let e=(this.hls.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-e,0)}get forwardBufferLength(){let{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;let i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:t}=this;if(!t)return;t.on(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(v.ERROR,this.onError,this),t.on(v.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this)}unregisterListeners(){let{hls:t}=this;if(!t)return;t.off(v.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(v.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(v.ERROR,this.onError,this),t.off(v.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this)}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){if(this.media)this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){if(e.advanced)this.onTimeupdate();if(!e.live&&this.media)this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(t,e){var i;let s=this.hls,r=this.media||e.event.appendInPlace&&(s==null||(i=s.interstitialsManager)==null?void 0:i.playerQueue.reduce((n,a)=>n||a.media,null));if(s&&r&&r.playbackRate>1&&r.playbackRate<=s.config.maxLiveSyncPlaybackRate)this.changeMediaPlaybackRate(r,1)}onError(t,e){var i;if(e.details!==R.BUFFER_STALLED_ERROR)return;if(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live)this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency")}changeMediaPlaybackRate(t,e){var i,s;if(t.playbackRate===e)return;(i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e}estimateLiveEdge(){let t=this.levelDetails;if(t===null)return null;return t.edge+t.age}computeLatency(){let t=this.estimateLiveEdge();if(t===null)return null;return t-this.currentTime}}var ye="1.7.3",re={};function Vo(){return typeof __HLS_WORKER_BUNDLE__==="function"}function Ko(){let t=re[ye];if(t)return t.clientCount++,t;let e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(e),r={worker:new self.Worker(i),objectURL:i,clientCount:1};return re[ye]=r,r}function Ho(t){let e=re[t];if(e)return e.clientCount++,e;let i=new self.URL(t,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return re[t]=r,r}function Wo(t){let e=re[t||ye];if(e){if(e.clientCount--===1){let{worker:s,objectURL:r}=e;if(delete re[t||ye],r)self.URL.revokeObjectURL(r);s.terminate()}}}function Yo(t,e,i,s){let r=[96000,88200,64000,48000,44100,32000,24000,22050,16000,12000,11025,8000,7350],n=e[i+2],a=n>>2&15;if(a>12){let E=Error(`invalid ADTS sampling index:${a}`);t.emit(v.ERROR,v.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:E,reason:E.message});return}let l=(n>>6&3)+1,o=e[i+3]>>6&3|(n&1)<<2,u=r[a],d=a;if(l===5||l===29)d-=3;let c,h=(d&14)>>1,f=(d&1)<<7|o<<3,g=0;if(l===1&&a>=6){g=5;let E=a-3;c=[g<<3|h,f|(E&14)>>1,(E&1)<<7|8,0]}else c=[l<<3|h,f];let m="mp4a.40."+(g||l);return st.log(`manifest codec:${s}, parsed codec:${m}, channels:${o}, rate:${u} (ADTS object type:${l} sampling index:${a} esds config:[${c.join(",")}])`),{config:c,samplerate:u,channelCount:o,codec:m,parsedCodec:m,manifestCodec:s}}function gn(t,e){return t[e]===255&&(t[e+1]&246)===240}function mn(t,e){return t[e+1]&1?7:9}function Ji(t,e){return(t[e+3]&3)<<11|t[e+4]<<3|(t[e+5]&224)>>>5}function jo(t,e){return e+5<t.length}function qe(t,e){return e+1<t.length&&gn(t,e)}function qo(t,e){return jo(t,e)&&gn(t,e)&&Ji(t,e)<=t.length-e}function zo(t,e){if(qe(t,e)){let i=mn(t,e);if(e+i>=t.length)return!1;let s=Ji(t,e);if(s<=i)return!1;let r=e+s;return r===t.length||qe(t,r)}return!1}function pn(t,e,i,s,r){if(!t.samplerate){let n=Yo(e,i,s,r);if(!n)return;dt(t,n)}}function En(t){return 92160000/t}function Xo(t,e){let i=mn(t,e);if(e+i<=t.length){let s=Ji(t,e)-i;if(s>0)return{headerLength:i,frameLength:s}}}function vn(t,e,i,s,r){let n=En(t.samplerate),a=s+r*n,l=Xo(e,i),o;if(l){let{frameLength:c,headerLength:h}=l,f=h+c,g=Math.max(0,i+f-e.length);if(g)o=new Uint8Array(f-h),o.set(e.subarray(i+h,e.length),0);else o=e.subarray(i+h,i+f);let m={unit:o,pts:a};if(!g)t.samples.push(m);return{sample:m,length:f,missing:g}}let u=e.length-i;return o=new Uint8Array(u),o.set(e.subarray(i,e.length),0),{sample:{unit:o,pts:a},length:u,missing:-1}}function kt(t="",e=90000){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class ts{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:90000,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,e){if(this.cachedData)t=It(this.cachedData,t),this.cachedData=null;let i=Ve(t,0),s=i?i.length:0,r,n=this._audioTrack,a=this._id3Track,l=i?xr(i):void 0,o=t.length;if(this.basePTS===null||this.frameIndex===0&&V(l))this.basePTS=Qo(l,e,this.initPTS),this.lastPTS=this.basePTS;if(this.lastPTS===null)this.lastPTS=this.basePTS;if(i&&i.length>0)a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:vt.audioId3,duration:Number.POSITIVE_INFINITY});while(s<o){if(this.canParse(t,s)){let u=this.appendFrame(n,t,s);if(u)this.frameIndex++,this.lastPTS=u.sample.pts,s+=u.length,r=s;else s=o}else if(ca(t,s))i=Ve(t,s),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:vt.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,r=s;else s++;if(s===o&&r!==o){let u=t.slice(r);if(this.cachedData)this.cachedData=It(this.cachedData,u);else this.cachedData=u}}return{audioTrack:n,videoTrack:kt(),id3Track:a,textTrack:kt()}}demuxSampleAes(t,e,i){return Promise.reject(Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){let e=this.cachedData;if(e)this.cachedData=null,this.demux(e,0);return{audioTrack:this._audioTrack,videoTrack:kt(),id3Track:this._id3Track,textTrack:kt()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}var Qo=(t,e,i)=>{if(V(t))return t*90;let s=i?i.baseTime*90000/i.timescale:0;return e*90000+s},Zo=[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],Jo=[44100,48000,32000,22050,24000,16000,11025,12000,8000],tl=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],el=[0,1,1,4];function yn(t,e,i,s,r){if(i+24>e.length)return;let n=Sn(e,i);if(n&&i+n.frameLength<=e.length){let a=n.samplesPerFrame*90000/n.sampleRate,l=s+r*a,o={unit:e.subarray(i,i+n.frameLength),pts:l,dts:l};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Sn(t,e){let i=t[e+1]>>3&3,s=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(i!==1&&r!==0&&r!==15&&n!==3){let a=t[e+2]>>1&1,l=t[e+3]>>6,o=i===3?3-s:s===3?3:4,u=Zo[o*14+r-1]*1000,c=Jo[(i===3?0:i===2?1:2)*3+n],h=l===3?1:2,f=tl[i][s],g=el[s],m=f*8*g,E=Math.floor(f*u/c+a)*g,y=he();if(!!y&&y<=87&&s===2&&u>=224000&&l===0)t[e+3]=t[e+3]|128;return{sampleRate:c,channelCount:h,frameLength:E,samplesPerFrame:m}}}function es(t,e){return t[e]===255&&(t[e+1]&224)===224&&(t[e+1]&6)!==0}function Tn(t,e){return e+1<t.length&&es(t,e)}function il(t,e){return es(t,e)&&4<=t.length-e}function xn(t,e){if(e+1<t.length&&es(t,e)){let s=Sn(t,e),r=4;if(s!=null&&s.frameLength)r=s.frameLength;let n=e+r;return n===t.length||Tn(t,n)}return!1}class is{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new ti(e,!0)}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,qt.cbc,{start:0,end:t.byteLength})}decryptAacSample(t,e,i){let s=t[e].unit;if(s.length<=16)return;let r=s.subarray(16,s.length-s.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then((a)=>{let l=new Uint8Array(a);if(s.set(l,16),!this.decrypter.isSync())this.decryptAacSamples(t,e+1,i)}).catch(i)}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length){i();return}if(t[e].unit.length<32)continue;if(this.decryptAacSample(t,e,i),!this.decrypter.isSync())return}}getAvcEncryptedData(t){let e=Math.floor((t.length-48)/160)*16+16,i=new Int8Array(e),s=0;for(let r=32;r<t.length-16;r+=160,s+=16)i.set(t.subarray(r,r+16),s);return i}getAvcDecryptedUnit(t,e){let i=new Uint8Array(e),s=0;for(let r=32;r<t.length-16;r+=160,s+=16)t.set(i.subarray(s,s+16),r);return t}decryptAvcSample(t,e,i,s,r){let n=Pr(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((l)=>{if(r.data=this.getAvcDecryptedUnit(n,l),!this.decrypter.isSync())this.decryptAvcSamples(t,e,i+1,s)}).catch(s)}decryptAvcSamples(t,e,i,s){if(t instanceof Uint8Array)throw Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length){s();return}let r=t[e].units;for(;;i++){if(i>=r.length)break;let n=r[i];if(n.data.length<=48||n.type!==1&&n.type!==5)continue;if(this.decryptAvcSample(t,e,i,s,n),!this.decrypter.isSync())return}}}}class An extends ts{constructor(t,e){super();this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=t,this.config=e}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:90000,dropped:0}}static probe(t,e){if(!t)return!1;let i=Ve(t,0),s=(i==null?void 0:i.length)||0;if(xn(t,s))return!1;for(let r=t.length;s<r;s++)if(zo(t,s))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return qo(t,e)}appendFrame(t,e,i){pn(t,this.observer,e,i,t.manifestCodec);let s=vn(t,e,i,this.basePTS,this.frameIndex);if((s==null?void 0:s.missing)===0)return s}demuxSampleAes(t,e,i){let s=this.demux(t,i),r=this.sampleAes=new is(this.observer,this.config,e);return new Promise((n)=>{r.decryptAacSamples(s.audioTrack.samples,0,()=>{n(s)})})}}var sl=(t,e)=>{let i=0,s=5;e+=s;let r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);while(s>0){a[0]=t[e];let l=Math.min(s,8),o=8-l;n[0]=4278190080>>>24+o<<o,r[0]=(a[0]&n[0])>>o,i=!i?r[0]:i<<l|r[0],e+=1,s-=l}return i};class Ln extends ts{resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:90000,dropped:0}}static probe(t){if(!t)return!1;let e=Ve(t,0),i=(e==null?void 0:e.length)||0;if(e&&t[i]===11&&t[i+1]===119&&xr(e)!==void 0&&sl(t,i)<=16)return!1;for(let s=t.length;i<s;i++)if(xn(t,i))return st.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return il(t,e)}appendFrame(t,e,i){if(this.basePTS===null)return;return yn(t,e,i,this.basePTS,this.frameIndex)}}var rl=/\/emsg[-/]ID3/i;class Rn{constructor(t,e,i,s=st){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=e,this.logger=s}resetTimeStamp(){}resetInitSegment(t,e,i,s){let r=this.videoTrack=kt("video",1),n=this.audioTrack=kt("audio",1),a=this.txtTrack=kt("text",1);if(this.id3Track=kt("id3",1),this.initData=void 0,this.timeOffset=0,!(t!=null&&t.byteLength))return;let l=this.initData=Ir(t);if(l.video){let{id:o,timescale:u,codec:d,supplemental:c}=l.video;r.id=o,r.timescale=a.timescale=u,r.codec=d,r.supplemental=c}if(l.audio){let{id:o,timescale:u,codec:d}=l.audio;n.id=o,n.timescale=u,n.codec=d}a.id=Lr.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return La(t,"moof")}demux(t,e,i){this.timeOffset=e;let s=t,r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){if(this.remainderData)s=It(this.remainderData,t);let o=Fa(s);this.remainderData=o.remainder,r.samples=o.valid||new Uint8Array}else r.samples=s;let a=this.extractID3Track(r,e),l=this.parseFragment(r,n,e,i);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(t,e){let i=this.timeOffset,s=this.videoTrack,r=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;let n=this.extractID3Track(s,this.timeOffset),a=this.parseFragment(s,r,i,e);return{videoTrack:s,audioTrack:kt(),id3Track:n,textTrack:kt(),initData:this.initData,sampleData:a}}parseFragment(t,e,i,s){let r=this.initData;if(r&&s){let{samples:n,sampleData:a}=wa(i,t,r,this.logger,!1);return e.samples=n,a}e.samples=Ma(i,t)}extractID3Track(t,e){let i=this.id3Track;if(t.samples.length){let s=et(t.samples,["emsg"]);if(s)s.forEach((r)=>{let n=Na(r);if(rl.test(n.schemeIdUri)){let a=ir(n,e),l=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;if(l<=0.001)l=Number.POSITIVE_INFINITY;let o=n.payload;i.samples.push({data:o,len:o.byteLength,dts:a,pts:a,type:vt.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){let a=this.config.emsgKLVSchemaUri||vt.misbklv;if(n.schemeIdUri.startsWith(a)){let l=ir(n,e);i.samples.push({data:n.payload,len:n.payload.byteLength,dts:l,pts:l,type:vt.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return i}demuxSampleAes(t,e,i){return Promise.reject(Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}}function ir(t,e){return V(t.presentationTime)?t.presentationTime/t.timeScale:e+t.presentationTimeDelta/t.timeScale}var nl=1,al=2,oe=-1;class bn{constructor(){this.VideoSample=null}createVideoSample(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],length:0}}getLastNalUnit(t){var e;let i=this.VideoSample,s;if(!i||i.units.length===0)i=t[t.length-1];if((e=i)!=null&&e.units){let r=i.units;s=r[r.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(t.pts===void 0){let i=e.samples,s=i.length;if(s){let r=i[s-1];t.pts=r.pts,t.dts=r.dts}else{e.dropped++;return}}e.samples.push(t)}}parseNALu(t,e,i){let s=e.byteLength;if(s===0)return[];let r=t.naluState||0,n=r===oe?0:r,a=[],l=0,o=0,u=-1,d=0;if(r===oe)u=0,d=this.getNALuType(e,0),o=1;while(o<s){let c=e.indexOf(nl,o);if(c===-1)break;o=c+1;let h=c;while(h>0&&e[h-1]===0)h--;if(c-h+(h===0?n:0)<al)continue;if(u>=0)a.push({data:e.subarray(u,h),type:d});else{let g=this.getLastNalUnit(t.samples);if(g){if(h>0)g.data=It(g.data,e.subarray(0,h));else if(n>0)g.data=g.data.subarray(0,g.data.byteLength-n);g.state=0}}if(o<s)u=o,d=this.getNALuType(e,o);else{l=oe,u=-1;break}}if(l!==oe){let c=s;while(c>0&&e[c-1]===0)c--;l=s-c+(c===0?n:0)}if(u>=0)a.push({data:e.subarray(u),type:d,state:l});else if(a.length===0&&l!==oe){let c=this.getLastNalUnit(t.samples);if(c)c.data=It(c.data,e),c.state=l}return t.naluState=l,a}}class wi{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let t=this.data,e=this.bytesAvailable,i=t.byteLength-e,s=new Uint8Array(4),r=Math.min(4,e);if(r===0)throw Error("no bytes available");s.set(t.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(t){let e;if(t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t)this.word<<=t,this.bitsAvailable-=t;else t-=this.bitsAvailable,e=t>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t}readBits(t){let e=Math.min(this.bitsAvailable,t),i=this.word>>>32-e;if(t>32)st.error("Cannot read more than 32 bits at a time");if(this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else if(this.bytesAvailable>0)this.loadWord();else throw Error("no bits available");if(e=t-e,e>0&&this.bitsAvailable)return i<<e|this.readBits(e);else return i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if((this.word&2147483648>>>t)!==0)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let t=this.skipLZ();return this.readBits(t+1)-1}readEG(){let t=this.readUEG();if(1&t)return 1+t>>>1;else return-1*(t>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}}class In extends bn{parsePES(t,e,i,s,r){let n=r.iframe,a=this.parseNALu(t,i.data,s),l=this.VideoSample,o,u=!1;if(i.data=null,l&&a.length&&!t.audFound)this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts);if(a.forEach((d)=>{var c,h;switch(d.type){case 1:{if(n)break;let E=!1;o=!0;let y=d.data;if(u&&y.length>4){let p=this.readSliceType(y);if(p===2||p===4||p===7||p===9)E=!0}if(E){var f;if((f=l)!=null&&f.frame&&!l.key)this.pushAccessUnit(l,t),l=this.VideoSample=null}if(!l)l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts);l.frame=!0,l.key=E;break}case 5:if(o=!0,(c=l)!=null&&c.frame&&!l.key)this.pushAccessUnit(l,t),l=this.VideoSample=null;if(!l)l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts);l.key=!0,l.frame=!0;break;case 6:{if(n)break;o=!0,Ke(d.data,1,i.pts,e.samples);break}case 7:{var g,m;o=!0,u=!0;let E=d.data,y=this.readSPS(E);if(!t.sps||t.width!==y.width||t.height!==y.height||((g=t.pixelRatio)==null?void 0:g[0])!==y.pixelRatio[0]||((m=t.pixelRatio)==null?void 0:m[1])!==y.pixelRatio[1]){t.width=y.width,t.height=y.height,t.pixelRatio=y.pixelRatio,t.sps=[E];let p=E.subarray(1,4),S="avc1.";for(let T=0;T<3;T++){let x=p[T].toString(16);if(x.length<2)x="0"+x;S+=x}t.codec=S}break}case 8:o=!0,t.pps=[d.data];break;case 9:if(o=!0,t.audFound=!0,(h=l)!=null&&h.frame)this.pushAccessUnit(l,t),l=null;if(!l)l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts);break;case 12:o=!0;break;default:o=!1;break}if(l&&o)l.units.push(d)}),s&&l)this.pushAccessUnit(l,t),this.VideoSample=null}getNALuType(t,e){return t[e]&31}readSliceType(t){let e=new wi(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i=8,s=8,r;for(let n=0;n<t;n++){if(s!==0)r=e.readEG(),s=(i+r+256)%256;i=s===0?i:s}}readSPS(t){let e=new wi(t),i=0,s=0,r=0,n=0,a,l,o,u=e.readUByte.bind(e),d=e.readBits.bind(e),c=e.readUEG.bind(e),h=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),E=this.skipScalingList.bind(this);u();let y=u();if(d(5),f(3),u(),m(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){let b=c();if(b===3)f(1);if(m(),m(),f(1),h()){l=b!==3?8:12;for(o=0;o<l;o++)if(h())if(o<6)E(16,e);else E(64,e)}}m();let p=c();if(p===0)c();else if(p===1){f(1),g(),g(),a=c();for(o=0;o<a;o++)g()}m(),f(1);let S=c(),T=c(),x=d(1);if(x===0)f(1);if(f(1),h())i=c(),s=c(),r=c(),n=c();let A=[1,1];if(h()){if(h())switch(u()){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=[u()<<8|u(),u()<<8|u()];break}}}return{width:Math.ceil((S+1)*16-i*2-s*2),height:(2-x)*(T+1)*16-(x?2:4)*(r+n),pixelRatio:A}}}var lt=188;class Ut{constructor(t,e,i,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=e,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(t,e){let i=Ut.syncOffset(t);if(i>0)e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`);return i!==-1}static syncOffset(t){let e=t.length,i=Math.min(lt*5,e-lt)+1,s=0;while(s<i){let r=!1,n=-1,a=0;for(let l=s;l<e;l+=lt)if(t[l]===71&&(e-l===lt||t[l+lt]===71)){if(a++,n===-1){if(n=l,n!==0)i=Math.min(n+lt*99,t.length-lt)+1}if(!r)r=ze(t,l)===0;if(r&&a>1&&(n===0&&a>2||l+lt>i))return n}else if(a)return-1;else break;s++}return-1}static createTrack(t,e){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:Lr[t],pid:-1,inputTimeScale:90000,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?e:void 0}}resetInitSegment(t,e,i,s,r,n){if(this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ut.createTrack("video"),this._videoTrack.duration=s,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new _n(this.logger):null,this._audioTrack=Ut.createTrack("audio",s),this._id3Track=Ut.createTrack("id3"),this._txtTrack=Ut.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i,t)this.demux(t,0,n,(r==null?void 0:r.method)==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){let{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;if(t)t.pesData=null;if(e)e.pesData=null;if(i)i.pesData=null;this.aacOverFlow=null,this.remainderData=null}demux(t,e,i,s=!1,r=!1){if(!s)this.sampleAes=null;let n,a=this._videoTrack,l=this.videoIntegrityChecker,o=this._audioTrack,u=this._id3Track,d=this._txtTrack,c=i.iframe,{pid:h,pesData:f}=a,g=o.pid,m=u.pid,E=this._klvPid,y=o.pesData,p=u.pesData,S=null,T=null,x=this.pmtParsed,A=this._pmtId,b=t.length;if(this.remainderData)t=It(this.remainderData,t),b=t.length,this.remainderData=null;if(b<lt&&!r)return this.remainderData=t,{audioTrack:o,videoTrack:a,id3Track:u,textTrack:d};let I=Math.max(0,Ut.syncOffset(t));if(b-=(b-I)%lt,b<t.byteLength&&!r)this.remainderData=new Uint8Array(t.buffer,b,t.buffer.byteLength-b);let L=0;for(let P=I;P<b;P+=lt)if(t[P]===71){let O=!!(t[P+1]&64),H=ze(t,P),M=(t[P+3]&48)>>4,C;if(M>1){if(C=P+5+t[P+4],C===P+lt)continue}else C=P+4;switch(H){case h:if(O){if(f&&!(l!=null&&l.isCorrupted)&&(n=Xt(f,this.logger))){if(this.readyVideoParser(a.segmentCodec),this.videoParser!==null)this.videoParser.parsePES(a,d,n,!1,i)}f={data:[],size:0},l==null||l.reset(h)}if(l==null||l.handlePacket(t.subarray(P)),f)f.data.push(t.subarray(C,P+lt)),f.size+=P+lt-C;break;case g:if(c)break;if(O){if(y&&(n=Xt(y,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,n,i);break;case"mp3":this.parseMPEGPES(o,n);break}y={data:[],size:0}}if(y)y.data.push(t.subarray(C,P+lt)),y.size+=P+lt-C;break;case m:if(c)break;if(O){if(p&&(n=Xt(p,this.logger)))this.parseID3PES(u,n);p={data:[],size:0}}if(p)p.data.push(t.subarray(C,P+lt)),p.size+=P+lt-C;break;case E:if(c)break;if(O){if(S&&(n=Xt(S,this.logger)))this.parseKlvPES(u,n);S={data:[],size:0}}if(S)S.data.push(t.subarray(C,P+lt)),S.size+=P+lt-C;break;case 0:if(O)C+=t[C]+1;A=this._pmtId=ol(t,C);break;case A:{if(O)C+=t[C]+1;let k=ll(t,C,this.typeSupported,s,this.observer,this.logger,this.config,i);if(h=k.videoPid,h>0)a.pid=h,a.segmentCodec=k.segmentVideoCodec;if(g=k.audioPid,g>0)o.pid=g,o.segmentCodec=k.segmentAudioCodec;if(m=k.id3Pid,m>0)u.pid=m;if(E=k.klvPid,E>0)this._klvPid=E;if(T!==null&&!x)this.logger.warn(`MPEG-TS PMT found at ${P} after unknown PID '${T}'. Backtracking to sync byte @${I} to parse all TS packets.`),T=null,P=I-188;x=this.pmtParsed=!0;break}case 17:case 8191:break;default:T=H;break}}else L++;if(L>0)Xe(this.observer,Error(`Found ${L} TS packet/s that do not start with 0x47`),i,void 0,this.logger);a.pesData=f,o.pesData=y,u.pesData=p;let _={audioTrack:o,videoTrack:a,id3Track:u,textTrack:d};if(r)this.extractRemainingSamples(_,i);return _}flush(t,e){let{remainderData:i}=this;this.remainderData=null;let s;if(i)s=this.demux(i,0,e,!1,!0);else s={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack};if(this.extractRemainingSamples(s,e),this.sampleAes)return this.decrypt(s,this.sampleAes);return s}extractRemainingSamples(t,e){let{audioTrack:i,videoTrack:s,id3Track:r,textTrack:n}=t,a=s.pesData,l=i.pesData,o=r.pesData,u=this.videoIntegrityChecker,d;if(a&&!(u!=null&&u.isCorrupted)&&(d=Xt(a,this.logger))){if(this.readyVideoParser(s.segmentCodec),this.videoParser!==null)this.videoParser.parsePES(s,n,d,!0,e),s.pesData=null}else s.pesData=a;if(l&&(d=Xt(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,d,e);break;case"mp3":this.parseMPEGPES(i,d);break}i.pesData=null}else{if(l!=null&&l.size)this.logger.log("last AAC PES packet truncated,might overlap between fragments");i.pesData=l}if(o&&(d=Xt(o,this.logger)))this.parseID3PES(r,d),r.pesData=null;else r.pesData=o}demuxSampleAes(t,e,i,s){let r=this.demux(t,i,s,!0,!this.config.progressive),n=this.sampleAes=new is(this.observer,this.config,e);return this.decrypt(r,n)}readyVideoParser(t){if(this.videoParser===null){if(t==="avc")this.videoParser=new In}}decrypt(t,e){return new Promise((i)=>{let{audioTrack:s,videoTrack:r}=t;if(s.samples&&s.segmentCodec==="aac")e.decryptAacSamples(s.samples,0,()=>{if(r.samples)e.decryptAvcSamples(r.samples,0,0,()=>{i(t)});else i(t)});else if(r.samples)e.decryptAvcSamples(r.samples,0,0,()=>{i(t)})})}destroy(){if(this.observer)this.observer.removeAllListeners();this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(t,e,i){let s=0,r=this.aacOverFlow,n=e.data;if(r){this.aacOverFlow=null;let c=r.missing,h=r.sample.unit.byteLength;if(c===-1)n=It(r.sample.unit,n);else{let f=h-c;r.sample.unit.set(n.subarray(0,c),f),t.samples.push(r.sample),s=r.missing}}let a,l;for(a=s,l=n.length;a<l-1;a++)if(qe(n,a))break;if(a!==s){let c,h=a<l-1;if(h)c=`AAC PES did not start with ADTS header,offset:${a}`;else c="No ADTS header found in AAC PES";if(Xe(this.observer,Error(c),i,h,this.logger),!h)return}pn(t,this.observer,n,a,this.audioCodec);let o;if(e.pts!==void 0)o=e.pts;else if(r){let c=En(t.samplerate);o=r.sample.pts+c}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let u=0,d;while(a<l)if(d=vn(t,n,a,o,u),a+=d.length,!d.missing){u++;for(;a<l-1;a++)if(qe(n,a))break}else{this.aacOverFlow=d;break}}parseMPEGPES(t,e){let i=e.data,s=i.length,r=0,n=0,a=e.pts;if(a===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}while(n<s)if(Tn(i,n)){let l=yn(t,i,n,a,r);if(l)n+=l.length,r++;else break}else n++}parseAC3PES(t,e){}parseID3PES(t,e){if(e.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=dt({},e,{type:this._videoTrack?vt.emsg:vt.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}parseKlvPES(t,e){var i;let s=(i=e.pts)!=null?i:e.dts;if(s===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}let r=e.data;if(r.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let n=0;while(n<r.length){var a;if(n+16>r.length)break;let l=n;if(n+=16,n>=r.length)break;let o=r[n];n+=1;let u=0;if(o&128){let f=o&127;if(f===0||f>4||n+f>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let g=0;g<f;g++)u=u<<8|r[n+g];n+=f}else u=o;if(n+u>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}let d=n+u,c=r.subarray(l,d),h={data:c,len:c.byteLength,pts:s,dts:(a=e.dts)!=null?a:s,type:vt.misbklv,duration:Number.POSITIVE_INFINITY};t.samples.push(h),n=d}}}function ze(t,e){return((t[e+1]&31)<<8)+t[e+2]}function ol(t,e){return(t[e+10]&31)<<8|t[e+11]}function ll(t,e,i,s,r,n,a,l){let o={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=(t[e+1]&15)<<8|t[e+2],d=e+3+u-4,c=(t[e+10]&15)<<8|t[e+11];e+=12+c;while(e<d){let h=ze(t,e),f=(t[e+3]&15)<<8|t[e+4];switch(t[e]){case 207:if(!s){Ei("ADTS AAC",n);break}case 15:if(o.audioPid===-1)o.audioPid=h;break;case 21:if(o.id3Pid===-1)o.id3Pid=h;break;case 219:if(!s){Ei("H.264",n);break}case 27:if(o.videoPid===-1)o.videoPid=h;break;case 3:case 4:if(!i.mpeg&&!i.mp3)n.log("MPEG audio found, not supported in this browser");else if(o.audioPid===-1)o.audioPid=h,o.segmentAudioCodec="mp3";break;case 193:if(!s){Ei("AC-3",n);break}case 129:n.warn("AC-3 in M2TS support not included in build");break;case 6:if(f>0){let g=e+5,m=f;while(m>2){switch(t[g]){case 106:if(o.audioPid===-1)n.warn("AC-3 in M2TS support not included in build");break;case 5:if(o.klvPid===-1&&a.enableEmsgKLVMetadata)o.klvPid=h,n.log(`KLV metadata PID found: ${h}`);break}let y=t[g+1]+2;g+=y,m-=y}}break;case 194:case 135:return Xe(r,Error("Unsupported EC-3 in M2TS found"),l,void 0,n),o;case 36:return Xe(r,Error("Unsupported HEVC in M2TS found"),l,void 0,n),o}e+=f+5}return o}function Xe(t,e,i,s,r){r.warn(`parsing error: ${e.message}`),t.emit(v.ERROR,v.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:i,error:e,reason:e.message})}function Ei(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Xt(t,e){let i=0,s,r,n,a,l,o=t.data;if(!t||t.size===0)return null;while(o[0].length<19&&o.length>1)o[0]=It(o[0],o[1]),o.splice(1,1);if(s=o[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(r=(s[4]<<8)+s[5],r&&r>t.size-6)return null;let d=s[7];if(d&192)if(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,d&64){if(l=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-l>5400000)e.warn(`${Math.round((a-l)/90000)}s delta between PTS and DTS, align them`),a=l}else l=a;n=s[8];let c=n+9;if(t.size<=c)return null;t.size-=c;let h=new Uint8Array(t.size);for(let f=0,g=o.length;f<g;f++){s=o[f];let m=s.byteLength;if(c)if(c>m){c-=m;continue}else s=s.subarray(c),m-=c,c=0;h.set(s,i),i+=m}if(r)r-=n+3;return{data:h,pts:a,dts:l,len:r}}return null}class _n{constructor(t){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t}get isCorrupted(){return this.integrityState!=="ok"}reset(t){this.pid=t,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(t){if(t.byteLength<4)return;let e=ze(t,0);if(e!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${e}`);return}let i=(t[3]&48)>>4;if(i===0)return;let s=t[3]&15,r=this.lastContinuityCounter;this.lastContinuityCounter=s;let n=(i&1)!=0;if((i&2)!=0&&t[4]!=0&&(t[5]&128)!=0)return;if(r<0)return;let o=n?r+1&15:r;if(s!==o){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${e}', CC=${s}, Expected-CC=${o} Last-CC=${r}`),this.integrityState="cc-failed";return}if((t[1]&128)!==0){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${e}'`),this.integrityState="tei-bit";return}}}class Dn{static getSilentFrame(t,e){switch(t){case"mp4a.40.2":if(e===1)return new Uint8Array([0,200,0,128,35,128]);else if(e===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);else if(e===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);else if(e===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);else if(e===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);else if(e===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(e===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);else if(e===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);else if(e===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}return}}var Qe,ul={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},vi=new Uint8Array([0,0,0,0,0,0,0,0]),dl=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),cl=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),hl=new Uint8Array([0,0,0,0,0,0,0,0]),yi=new Uint8Array([0,0,0,0,0,0,0,1]),sr=new Uint8Array([105,115,111,109]),fl=new Uint8Array([97,118,99,49]),gl=new Uint8Array([0,0,0,1]);class B{static box(t,...e){let i=8,s=e.length,r=s;while(s--)i+=e[s].byteLength;let n=new Uint8Array(i);Zt(n,0,i),Zt(n,4,t);for(s=0,i=8;s<r;s++)n.set(e[s],i),i+=e[s].byteLength;return n}static hdlr(t){return B.box(X.hdlr,ul[t])}static mdat(t){return B.box(X.mdat,t)}static mdhd(t,e){e*=t;let i=Math.floor(e/(Ct+1)),s=Math.floor(e%(Ct+1));return B.box(X.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,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(t){return B.box(X.mdia,B.mdhd(t.timescale||0,t.duration||0),B.hdlr(t.type),B.minf(t))}static mfhd(t){return B.box(X.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){if(t.type==="audio")return B.box(X.minf,B.box(X.smhd,hl),B.DINF,B.stbl(t));else return B.box(X.minf,B.box(X.vmhd,cl),B.DINF,B.stbl(t))}static moof(t,e,i){return B.box(X.moof,B.mfhd(t),B.traf(i,e))}static moov(t){let e=t.length,i=[];while(e--)i[e]=B.trak(t[e]);return B.box.apply(null,[X.moov,B.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(B.mvex(t)))}static mvex(t){let e=t.length,i=[];while(e--)i[e]=B.trex(t[e]);return B.box.apply(null,[X.mvex,...i])}static mvhd(t,e){e*=t;let i=Math.floor(e/(Ct+1)),s=Math.floor(e%(Ct+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&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(X.mvhd,r)}static sdtp(t){let e=t.samples||[],i=new Uint8Array(4+e.length),s,r;for(s=0;s<e.length;s++)r=e[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return B.box(X.sdtp,i)}static stbl(t){return B.box(X.stbl,B.stsd(t),B.box(X.stts,vi),B.box(X.stsc,vi),B.box(X.stsz,dl),B.box(X.stco,vi))}static avc1(t){let e=[],i=[],s,r,n;for(s=0;s<t.sps.length;s++)r=t.sps[s],n=r.byteLength,e.push(n>>>8&255),e.push(n&255),e=e.concat(Array.prototype.slice.call(r));for(s=0;s<t.pps.length;s++)r=t.pps[s],n=r.byteLength,i.push(n>>>8&255),i.push(n&255),i=i.concat(Array.prototype.slice.call(r));let a=B.box(X.avcC,new Uint8Array([1,e[3],e[4],e[5],255,224|t.sps.length].concat(e).concat([t.pps.length]).concat(i))),{width:l,height:o}=t,u=t.pixelRatio[0],d=t.pixelRatio[1];return B.box(X.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,o>>8&255,o&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]),a,B.box(X.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),B.box(X.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(t){let e=t.config,i=e.length;return new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5,i,...e,6,1,2])}static audioStsd(t){let e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,e&255,0,0])}static mp4a(t){return B.box(X.mp4a,B.audioStsd(t),B.box(X.esds,B.esds(t)))}static mp3(t){return B.box(X[".mp3"],B.audioStsd(t))}static ac3(t){return B.box(X["ac-3"],B.audioStsd(t),B.box(X.dac3,t.config))}static stsd(t){let{segmentCodec:e}=t;if(t.type==="audio"){if(e==="aac")return B.box(X.stsd,yi,B.mp4a(t));if(e==="mp3"&&t.codec==="mp3")return B.box(X.stsd,yi,B.mp3(t))}else if(t.pps&&t.sps){if(e==="avc")return B.box(X.stsd,yi,B.avc1(t))}else throw Error("video track missing pps or sps");throw Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){let e=t.id,i=(t.duration||0)*(t.timescale||0),s=t.width||0,r=t.height||0,n=Math.floor(i/(Ct+1)),a=Math.floor(i%(Ct+1));return B.box(X.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,a>>24,a>>16&255,a>>8&255,a&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,s>>8&255,s&255,0,0,r>>8&255,r&255,0,0]))}static traf(t,e){let i=B.sdtp(t),s=t.id,r=Math.floor(e/(Ct+1)),n=Math.floor(e%(Ct+1));return B.box(X.traf,B.box(X.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),B.box(X.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),B.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,B.box(X.trak,B.tkhd(t),B.mdia(t))}static trex(t){let e=t.id;return B.box(X.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){let i=t.samples||[],s=i.length,r=12+16*s,n=new Uint8Array(r),a,l,o,u,d,c;e+=8+r,n.set([t.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255],0);for(a=0;a<s;a++)l=i[a],o=l.duration,u=l.size,d=l.flags,c=l.cts,n.set([o>>>24&255,o>>>16&255,o>>>8&255,o&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,c>>>24&255,c>>>16&255,c>>>8&255,c&255],12+16*a);return B.box(X.trun,n)}static initSegment(t){let e=B.moov(t);return It(B.FTYP,e)}static hvc1(t){return new Uint8Array}}Qe=B;B.FTYP=Qe.box(X.ftyp,sr,gl,sr,fl);B.DINF=Qe.box(X.dinf,Qe.box(X.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var ml=90000;function pl(t,e,i=1,s=!1){let r=t*e*i;return s?Math.round(r):r}function le(t,e=!1){return pl(t,1000,1/ml,e)}function rr(t){let{baseTime:e,timescale:i,trackId:s}=t;return`${e/i} (${e}/${i}) trackId: ${s}`}var El=1e4,vl=1024,yl=1152,Sl=1536,Fi=8589934592;function nr(t,e,i,s){return{duration:e,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1,paddingValue:0}}}class Ue extends wt{constructor(t,e,i,s){super("mp4-remuxer",s);this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){let e=this._initPTS;if(!e||!t||t.trackId!==e.trackId||t.baseTime!==e.baseTime||t.timescale!==e.timescale)this.log(`Reset initPTS: ${e?rr(e):e} > ${t?rr(t):t}`);this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1,i=t[0].pts,s=t.reduce((r,n)=>{let a=n.pts,l=a-r;if(l<-4294967296)e=!0,a=At(a,i),l=a-r;if(l>0)return r;return a},i);if(e)this.debug("PTS rollover detected");return s}remux(t,e,i,s,r,n,a,l,o){let u,d,c,h,f,g,m=r,E=r,p=!o.iframe&&t.pid>-1,S=e.pid>-1,T=e.samples.length,x=t.samples.length>0,A=a&&T>0||T>1;if((!p||x)&&(!S||A)||this.ISGenerated||a){if(this.ISGenerated){var I,L,_,P;let C=this.videoTrackConfig;if(C&&(e.width!==C.width||e.height!==C.height||((I=e.pixelRatio)==null?void 0:I[0])!==((L=C.pixelRatio)==null?void 0:L[0])||((_=e.pixelRatio)==null?void 0:_[1])!==((P=C.pixelRatio)==null?void 0:P[1]))||!C&&A||this.nextAudioTs===null&&x)this.resetInitSegment()}if(!this.ISGenerated)c=this.generateIS(t,e,r,n);let O=this.isVideoContiguous,H=-1,M;if(A){if(H=Tl(e.samples),!O&&this.config.forceKeyFrameOnDiscontinuity){if(g=!0,H>0){this.warn(`Dropped ${H} out of ${T} video samples due to a missing keyframe`);let C=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(H),e.dropped+=H,E+=(e.samples[0].pts-C)/e.inputTimeScale,M=E}else if(H===-1)this.warn(`No keyframe found out of ${T} video samples`),g=!1}}if(this.ISGenerated){if(x&&A&&r){let C=this.getVideoStartPts(e.samples),U=(At(t.samples[0].pts,C)-C)/e.inputTimeScale;m+=Math.max(0,U),E+=Math.max(0,-U)}if(x){if(!t.samplerate)this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(t,e,r,n);if(d=this.remuxAudio(t,m,this.isAudioContiguous,n,S||A||l===Q.AUDIO?E:void 0,o),A){let C=d?d.endPTS-d.startPTS:0;if(!e.inputTimeScale)this.warn("regenerate InitSegment as video detected"),c=this.generateIS(t,e,r,n);u=this.remuxVideo(e,E,O,C,o)}}else if(A)u=this.remuxVideo(e,E,O,0,o);if(u)u.firstKeyFrame=H,u.independent=H!==-1,u.firstKeyFramePTS=M}}if(this.ISGenerated&&this._initPTS&&this._initDTS){if(i.samples.length)f=Cn(i,r,this._initPTS,this._initDTS);if(s.samples.length)h=Pn(s,r,this._initPTS)}return{audio:d,video:u,initSegment:c,independent:g,text:h,id3:f}}computeInitPts(t,e,i,s){let r=Math.round(i*e),n=At(t,r);if(n<r){this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/e} ${s}`);while(n<r)n+=Fi}return n-r}generateIS(t,e,i,s){let r=t.samples,n=e.samples,a=this.typeSupported,l={},o=this._initPTS,u=!o||s,d="audio/mp4",c,h,f,g=-1;if(u)c=h=1/0;if(t.config&&r.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":if(a.mpeg)d="audio/mpeg",t.codec="";else if(a.mp3)t.codec="mp3";break;case"ac3":t.codec="ac-3";break}if(l.audio={id:"audio",container:d,codec:t.codec,initSegment:t.segmentCodec==="mp3"&&a.mpeg?new Uint8Array(0):B.initSegment([t]),metadata:{channelCount:t.channelCount}},u){g=t.id,f=t.inputTimeScale;let m=this.computeInitPts(r[0].pts,f,i,"audio");if(!o||f!==o.timescale||i===0&&m<o.baseTime)c=h=m}}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:B.initSegment([e]),metadata:{width:e.width,height:e.height}},u){g=e.id,f=e.inputTimeScale;let m=this.getVideoStartPts(n),E=At(n[0].dts,m),y=this.computeInitPts(E,f,i,"video"),p=this.computeInitPts(m,f,i,"video");if(!o||f!==o.timescale||V(c)||i===0&&p<o.baseTime)h=Math.min(h,y),c=Math.min(c,y)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(l).length){if(this.ISGenerated=!0,u&&V(c)){if(o)this.warn(`Timestamps at playlist time: ${s?"":"~"}${i} ${c/f} != initPTS: ${o.baseTime/o.timescale} (${o.baseTime}/${o.timescale}) trackId: ${o.trackId}`);this.log(`Found initPTS at playlist time: ${i} offset: ${c/f} (${c}/${f}) trackId: ${g}`),this._initPTS={baseTime:c,timescale:f,trackId:g},this._initDTS={baseTime:h,timescale:f,trackId:g}}else c=f=void 0;return{tracks:l,initPTS:c,timescale:f,trackId:g}}}remuxVideo(t,e,i,s,r){let{inputTimeScale:n,samples:a}=t,l=[],o=a.length,u=this._initPTS,d=u.baseTime*n/u.timescale,c=this.nextVideoTs,h=8,f=this.videoSampleDuration,g,m,{POSITIVE_INFINITY:E,NEGATIVE_INFINITY:y}=Number,p=!1;if(!i||c===null){let F=d+e*n,N=a[0].pts-At(a[0].dts,a[0].pts);if(he()&&c!==null&&Math.abs(F-N-(c+d))<15000)i=!0;else c=F-N-d}let S=c+d;for(let F=0;F<o;F++){let N=a[F];if(N.pts=At(N.pts,S),N.dts=At(N.dts,S),N.dts<a[F>0?F-1:F].dts)p=!0}if(p)a.sort(function(F,N){let W=F.dts-N.dts,z=F.pts-N.pts;return W||z});g=a[0].dts,m=a[a.length-1].dts;let T=m-g,x=T?Math.round(T/(o-1)):f||t.inputTimeScale/30;if(i){let F=g-S,N=F>x,W=F<-1;if(N||W){if(N)this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${le(F,!0)} ms (${F}dts) hole between fragments detected at ${e.toFixed(3)}`);else this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${le(-F,!0)} ms (${F}dts) overlapping between fragments detected at ${e.toFixed(3)}`);if(!W||S>=a[0].pts||he()){g=S;let z=a[0].pts-F;if(N)a[0].dts=g,a[0].pts=z;else{let Z=!0;for(let Y=0;Y<a.length;Y++){if(a[Y].dts>z&&Z)break;let at=a[Y].pts;if(a[Y].dts-=F,a[Y].pts-=F,Y<a.length-1){let gt=a[Y+1].pts,tt=a[Y].pts,it=gt<=tt,xt=gt<=at;Z=it==xt}}}this.log(`Video: Initial PTS/DTS adjusted: ${le(z,!0)}/${le(g,!0)}, delta: ${le(F,!0)} ms`)}}}g=Math.max(0,g);let A=0,b=0,I=g;for(let F=0;F<o;F++){let N=a[F],W=N.units,z=W.length,Z=0;for(let Y=0;Y<z;Y++)Z+=W[Y].data.length;if(b+=Z,A+=z,N.length=Z,N.dts<I)N.dts=I,I+=x/4|0||1;else I=N.dts;E=Math.min(N.pts,E),y=Math.max(N.pts,y)}m=a[o-1].dts;let L=b+4*A+8,_;try{_=new Uint8Array(L)}catch(F){this.observer.emit(v.ERROR,v.ERROR,{type:q.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:r,error:F,bytes:L,reason:`fail allocating video mdat ${L}`});return}Zt(_,0,L),Zt(_,4,X.mdat);let P=!1,{POSITIVE_INFINITY:O,POSITIVE_INFINITY:H,NEGATIVE_INFINITY:M,NEGATIVE_INFINITY:C}=Number;for(let F=0;F<o;F++){let N=a[F],W=N.units,z=0;for(let at=0,gt=W.length;at<gt;at++){let tt=W[at],it=tt.data,xt=tt.data.byteLength;Zt(_,h,xt),h+=4,_.set(it,h),h+=xt,z+=4+xt}let Z;if(F<o-1)f=a[F+1].dts-N.dts,Z=a[F+1].pts-N.pts;else{let at=this.config,gt=F>0?N.dts-a[F-1].dts:x;if(Z=F>0?N.pts-a[F-1].pts:x,at.stretchShortVideoTrack&&this.nextAudioTs!==null){let tt=Math.floor(at.maxBufferHole*n),it=(s?E+s*n:this.nextAudioTs+d)-N.pts;if(it>tt){if(f=it-gt,f<0)f=gt;else P=!0;this.log(`It is approximately ${it/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)}else f=gt}else f=gt}let Y=Math.round(N.pts-N.dts);if(O=Math.min(O,f),M=Math.max(M,f),H=Math.min(H,Z),C=Math.max(C,Z),!i&&F===0&&Y>f){let at=Math.round(Y/x)*x;if(at-Y===1)this.log(`pad first CTS ${Y} -> ${at} of sn: ${r.sn}`),Y=at}l.push(nr(N.key,f,z,Y))}if(l.length){let F=he();if(F){if(F<70){let N=l[0].flags;N.dependsOn=2,N.isNonSync=0}}else if($a()){if(C-H<M-O&&x/M<0.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let N=g;for(let W=0,z=l.length;W<z;W++){let Z=N+l[W].duration,Y=N+l[W].cts;if(W<z-1){let at=Z+l[W+1].cts;l[W].duration=at-Y}else l[W].duration=W?l[W-1].duration:x;l[W].cts=0,N=Z}}}}f=P||!f?x:f;let k=m+f;this.nextVideoTs=c=k-d,this.videoSampleDuration=f,this.isVideoContiguous=!0;let U=B.moof(r.sn,g,dt(t,{samples:l})),D="video",G={data1:U,data2:_,startPTS:(E-d)/n,endPTS:(y+f-d)/n,startDTS:(g-d)/n,endDTS:c/n,type:D,hasAudio:!1,hasVideo:!0,nb:l.length,dropped:t.dropped};return t.samples=[],t.dropped=0,G}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return yl;case"ac3":return Sl;default:return vl}}remuxAudio(t,e,i,s,r,n){let a=t.inputTimeScale,l=t.samplerate?t.samplerate:a,o=a/l,u=this.getSamplesPerFrame(t),d=u*o,c=this._initPTS,h=t.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=r!==void 0,m=t.samples,E=h?0:8,y=this.nextAudioTs||-1,p=c.baseTime*a/c.timescale,S=p+e*a;if(this.isAudioContiguous=i=i||m.length&&y>0&&(s&&Math.abs(S-(y+p))<9000||Math.abs(At(m[0].pts,S)-(y+p))<20*d),m.forEach(function(k){k.pts=At(k.pts,S)}),!i||y<0){let k=m.length;if(m=m.filter((U)=>U.pts>=0),k!==m.length)this.warn(`Removed ${m.length-k} of ${k} samples (initPTS ${p} / ${a})`);if(!m.length)return;if(r===0)y=0;else if(s&&!g)y=Math.max(0,S-p);else y=m[0].pts-p}if(t.segmentCodec==="aac"){let k=this.config.maxAudioFramesDrift;for(let U=0,D=y+p;U<m.length;U++){let G=m[U],F=G.pts,N=F-D,W=Math.abs(1000*N/a);if(N<=-k*d&&g){if(U===0)this.warn(`Audio frame @ ${(F/a).toFixed(3)}s overlaps marker by ${Math.round(1000*N/a)} ms.`),this.nextAudioTs=y=F-p,D=F}else if(N>=k*d&&W<El&&g){let z=Math.round(N/d);D=F-z*d;while(D<0&&z&&d)z--,D+=d;if(U===0)this.nextAudioTs=y=D-p;this.warn(`Injecting ${z} audio frames @ ${((D-p)/a).toFixed(3)}s due to ${Math.round(1000*N/a)} ms gap.`);for(let Z=0;Z<z;Z++){let Y=Dn.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);if(!Y)this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),Y=G.unit.subarray();m.splice(U,0,{unit:Y,pts:D}),D+=d,U++}}G.pts=D,D+=d}}let T=null,x=null,A,b=0,I=m.length;while(I--)b+=m[I].unit.byteLength;for(let k=0,U=m.length;k<U;k++){let D=m[k],{unit:G,pts:F}=D;if(x!==null){let W=f[k-1];W.duration=Math.round((F-x)/o)}else{if(i&&t.segmentCodec==="aac")F=y+p;if(T=F,b>0){b+=E;try{A=new Uint8Array(b)}catch(W){this.observer.emit(v.ERROR,v.ERROR,{type:q.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:n,error:W,bytes:b,reason:`fail allocating audio mdat ${b}`});return}if(!h)Zt(A,0,b),Zt(A,4,X.mdat)}else return}if(A)A.set(G,E);let N=G.byteLength;E+=N,f.push(nr(!0,u,N,0)),x=F}let L=f.length;if(!L)return;let _=f[f.length-1];y=x-p,this.nextAudioTs=y+o*_.duration;let P=h?new Uint8Array(0):B.moof(t.sequenceNumber++,T/o,dt({},t,{samples:f}));t.samples=[];let O=(T-p)/a,H=this.nextAudioTs/a,C={data1:P,data2:A,startPTS:O,endPTS:H,startDTS:O,endDTS:H,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,C}}function At(t,e){let i;if(e===null)return t;if(e<t)i=-Fi;else i=Fi;while(Math.abs(t-e)>4294967296)t+=i;return t}function Tl(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}function Cn(t,e,i,s){let r=t.samples.length;if(!r)return;let n=t.inputTimeScale;for(let l=0;l<r;l++){let o=t.samples[l];o.pts=At(o.pts-i.baseTime*n/i.timescale,e*n)/n,o.dts=At(o.dts-s.baseTime*n/s.timescale,e*n)/n}let a=t.samples;return t.samples=[],{samples:a}}function Pn(t,e,i){let s=t.samples.length;if(!s)return;let r=t.inputTimeScale;for(let a=0;a<s;a++){let l=t.samples[a];l.pts=At(l.pts-i.baseTime*r/i.timescale,e*r)/r}t.samples.sort((a,l)=>a.pts-l.pts);let n=t.samples;return t.samples=[],{samples:n}}class kn extends wt{constructor(t,e,i,s){super("passthrough-remuxer",s);this.observer=void 0,this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=t}destroy(){if(this.observer)this.observer.removeAllListeners();this.observer=null}resetTimeStamp(t){this.lastEndTime=null;let e=this.initPTS;if(e&&t){if(e.baseTime===t.baseTime&&e.timescale===t.timescale)return}this.initPTS=t}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,i,s){this.audioCodec=e,this.videoCodec=i,this.decryptdata=s,this.pendingInitSegment=t,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(t,e,i){this.videoOnlyRemux=!1;let{audioCodec:s,videoCodec:r}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:n,video:a}=this.initData=i||Ir(t);if(e)_a(t,e);else{let o=n||a;if(o!=null&&o.encrypted)this.warn(`Init segment with encrypted track with has no key ("${o.codec}")!`)}if(n)s=ar(n,rt.AUDIO,this);if(a)r=ar(a,rt.VIDEO,this);let l={};if(n&&a)l.audiovideo={container:"video/mp4",codec:s+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"};else if(n)l.audio={container:"audio/mp4",codec:s,encrypted:n.encrypted,initSegment:t,id:"audio"};else if(a)l.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"};else this.warn("initSegment does not contain moov or trak boxes.");this.initTracks=l}remux(t,e,i,s,r,n,a,l,o,u,d){var c,h;let{initPTS:f,lastEndTime:g}=this,m={audio:void 0,video:void 0,text:void 0,id3:i,initSegment:void 0};if(!V(g))g=this.lastEndTime=r||0;let E=e.samples;if(!E.length)return m;let y=this.pendingInitSegment;if(y)this.pendingInitSegment=void 0,this.generateInitSegment(y,this.decryptdata,u);let p={initPTS:void 0,timescale:void 0,trackId:void 0},S=this.initData;if(!((c=S)!=null&&c.length))this.generateInitSegment(E),S=this.initData;if(!((h=S)!=null&&h.length))return this.warn("Failed to generate initSegment."),m;if(this.emitInitSegment)p.tracks=this.initTracks,m.initSegment=p,this.emitInitSegment=!1;let T=!1,x=d&&!T?d.tracks:Oa(E,S,o,this,T),A=S.audio?x[S.audio.id]:null,b=S.video?x[S.video.id]:null,I=!!S.audio,L=!!S.video,_="";if(I)_+="audio";if(L)_+="video";let P=Oe(b,1/0),O=Oe(A,1/0),H=Oe(b,0,!0),M=Oe(A,0,!0),C=r,k=0;if(b&&A&&S.audio&&(O>H||P>M))this.warn(`audio and video track sample timestamps do not overlap. v: ${P}-${H} a: ${O}-${M}}`,b,A);let U=!!A&&(!b||!f&&O<P||!!f&&f.trackId===S.audio.id),D=U?A:b;if(!D)return this.log(`No media samples found in ${l} ${o.level} ${o.part===-1?"":`part: ${o.part} of`} sn: ${o.sn} at playlist time: ${r}`),m;let G=E,F;k=U?M-O:H-P;let N=D.timescale,W=D.start-r*N,z=U?S.audio.id:S.video.id;if(C=D.start/N,(n||!f)&&(xl(f,C,r,k)||N!==f.timescale)){let Et=!1,ot=U?"audio":"video";if(f){let Vt=r!==0?C/r:1+C/1;Et=C>=0&&Math.abs(1-Vt)<0.001,this.log(`${ot} timestamps in track ${z} at playlist time: ${n?"":"~"}${r} maps to ${C} with initPTS: ${f.baseTime/f.timescale} (${W/N-f.baseTime/f.timescale}s diff) (${_}) drift estimate: ${Vt} ${Et?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}if(!Et)this.log(`Found initPTS in ${ot} track ${z} at playlist time: ${r} offset: ${C-r} (${W}/${N})`),f=null,p.initPTS=W,p.timescale=N,p.trackId=z}if(!f){if(!p.timescale||p.trackId===void 0||p.initPTS===void 0)this.warn("Could not set initPTS"),p.initPTS=C,p.timescale=1,p.trackId=-1;this.initPTS=f={baseTime:p.initPTS,timescale:p.timescale,trackId:p.trackId}}else p.initPTS=f.baseTime,p.timescale=f.timescale,p.trackId=f.trackId;let Z=C-f.baseTime/f.timescale,Y=Z+k,at=L&&(D==null?void 0:D.ptsMin)!==void 0?D.ptsMin/D.timescale-f.baseTime/f.timescale:Z,gt=L&&D!=null&&D.ptsMax?D.ptsMax/D.timescale-f.baseTime/f.timescale:Y;if(k>0)this.lastEndTime=Y;else this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp();let tt=(S.audio?S.audio.encrypted:!1)||(S.video?S.video.encrypted:!1),it={data1:G,data2:F,startPTS:at,startDTS:Z,endPTS:gt,endDTS:Y,type:_,hasAudio:I,hasVideo:L,nb:1,dropped:0,encrypted:tt};m.audio=I&&!L?it:void 0,m.video=L?it:void 0;let xt=this.isVideoContiguous,Ft=b==null?void 0:b.sampleCount;if(Ft){let Et=b.keyFrameIndex,ot=Et!==-1;if(it.nb=Ft,it.dropped=Et===0||xt?0:ot?Et:Ft,it.independent=ot,it.firstKeyFrame=Et,ot&&b.keyFrameStart)it.firstKeyFramePTS=(b.keyFrameStart-f.baseTime)/f.timescale;if(!xt)m.independent=ot;if(this.isVideoContiguous||(this.isVideoContiguous=ot),it.dropped)this.warn(`fmp4 does not start with IDR: firstIDR ${Et}/${Ft} dropped: ${it.dropped} start: ${it.firstKeyFramePTS||"NA"}`)}if(m.initSegment=p,m.id3=Cn(i,r,f,f),s.samples.length)m.text=Pn(s,r,f);return m}}function Oe(t,e,i=!1){return(t==null?void 0:t.start)!==void 0?(t.start+(i?t.duration:0))/t.timescale:e}function xl(t,e,i,s){if(t===null)return!0;let r=Math.max(s,1),n=e-t.baseTime/t.timescale;return Math.abs(n-i)>=r}function ar(t,e,i){let s=t.codec;if(s&&s.length>4)return s;if(e===rt.AUDIO){if(s==="ec-3"||s==="ac-3"||s==="alac")return s;if(s==="fLaC"||s==="Opus")return We(s,!1);return i.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"}else if(s==="mjpg")return s;return i.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1"}var Wt;try{Wt=self.performance.now.bind(self.performance)}catch(t){Wt=Date.now}var Si=[{demux:Rn,remux:kn},{demux:Ut,remux:Ue},{demux:An,remux:Ue},{demux:Ln,remux:Ue}];class Mi{constructor(t,e,i,s,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=t,this.typeSupported=e,this.config=i,this.id=r,this.logger=n}configure(t){if(this.transmuxConfig=t,this.decrypter)this.decrypter.reset()}push(t,e,i,s){if(!this.observer)return we(i);let r=i.transmuxing;r.executeStart=Wt();let n=new Uint8Array(t),{currentTransmuxState:a,transmuxConfig:l}=this;if(s)this.currentTransmuxState=s;let{contiguous:o,discontinuity:u,trackSwitch:d,accurateTimeOffset:c,timeOffset:h,initSegmentChange:f}=s||a,{audioCodec:g,videoCodec:m,defaultInitPts:E,duration:y,initSegmentData:p}=l,S=Al(n,e);if(S&&fe(S.method)){let b=this.getDecrypter(),I=Gr(S.method);return this.asyncResult=!0,this.decryptionPromise=b.decrypt(n,S.key.buffer,S.iv.buffer,I,i.decryptRange).then((L)=>{let _=this.push(L,null,i);return this.decryptionPromise=null,_}),this.decryptionPromise}let T=this.needsProbing(u,d);if(T){let b=i.iframe&&p&&Ut.probe(p,this.logger)?p:n,I=this.configureTransmuxer(b);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(v.ERROR,v.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),r.executeEnd=Wt(),we(i)}if(u||d||f||T)this.resetInitSegment(p,g,m,y,e,i);if(u||f||T)this.resetInitialTimestamp(E);if(!o)this.resetContiguity();let x=this.transmux(n,S,h,c,i);this.asyncResult=Se(x);let A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=Wt(),x}flush(t){let e=t.transmuxing;e.executeStart=Wt();let{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));let n=[],{timeOffset:a}=s;if(i){let d=i.flush();if(d)n.push(this.push(d.buffer,null,t))}let{demuxer:l,remuxer:o}=this;if(!l||!o){e.executeEnd=Wt();let d=[we(t)];if(this.asyncResult)return Promise.resolve(d);return d}let u=l.flush(a,t);if(Se(u))return this.asyncResult=!0,u.then((d)=>(this.flushRemux(n,d,t),n));if(this.flushRemux(n,u,t),this.asyncResult)return Promise.resolve(n);return n}flushRemux(t,e,i){if(!this.remuxer)return;let{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:l,timeOffset:o}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id} playlist ${i.level}`);let u=this.remuxer.remux(s,r,n,a,o,l,!0,this.id,i,e.initData,e.sampleData);t.push({remuxResult:u,chunkMeta:i}),i.transmuxing.executeEnd=Wt()}resetInitialTimestamp(t){let{demuxer:e,remuxer:i}=this;if(!e||!i)return;e.resetTimeStamp(t),i.resetTimeStamp(t)}resetContiguity(){let{demuxer:t,remuxer:e}=this;if(!t||!e)return;t.resetContiguity(),e.resetNextTimestamp()}resetInitSegment(t,e,i,s,r,n){let{demuxer:a,remuxer:l}=this;if(!a||!l)return;a.resetInitSegment(t,e,i,s,r,n),l.resetInitSegment(t,e,i,r)}destroy(){if(this.demuxer)this.demuxer.destroy(),this.demuxer=void 0;if(this.remuxer)this.remuxer.destroy(),this.remuxer=void 0;if(this.observer)this.observer.removeAllListeners();this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(t,e,i,s,r){let n;if((e==null?void 0:e.method)==="SAMPLE-AES")n=this.transmuxSampleAes(t,e,i,s,r);else n=this.transmuxUnencrypted(t,i,s,r);return n}transmuxUnencrypted(t,e,i,s){let{demuxer:r,remuxer:n}=this;if(!r||!n)return we(s);let a=r.demux(t,e,s,!1,!this.config.progressive),{audioTrack:l,videoTrack:o,id3Track:u,textTrack:d}=a;return{remuxResult:n.remux(l,o,u,d,e,i,!1,this.id,s,a.initData,a.sampleData),chunkMeta:s}}transmuxSampleAes(t,e,i,s,r){if(!this.demuxer)return Promise.reject(Error("no demuxer"));return this.demuxer.demuxSampleAes(t,e,i,r).then((n)=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,i,s,!1,this.id,r,n.initData,n.sampleData),chunkMeta:r}))}configureTransmuxer(t){let{config:e,observer:i,typeSupported:s}=this;if(!i)return;let r;try{for(let d=0,c=Si.length;d<c;d++){var n;if((n=Si[d].demux)!=null&&n.probe(t,this.logger)){r=Si[d];break}}}catch(d){return d}if(!r)return Error("Failed to find demuxer by probing fragment data");let a=this.demuxer,l=this.remuxer,o=r.demux,u=r.remux;if(!a||!(a instanceof o))this.logger.log(`Using ${o.name}`),this.demuxer=new o(i,e,s,this.logger),this.probe=o.probe;if(!l||!(l instanceof u))this.logger.log(`Using ${u.name}`),this.remuxer=new u(i,e,s,this.logger)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;if(!t)t=this.decrypter=new ti(this.config);return t}}function Al(t,e){let i=null;if(t.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null)i=e;return i}var we=(t)=>({remuxResult:{},chunkMeta:t});function Se(t){return"then"in t&&t.then instanceof Function}class On{constructor(t,e,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class wn{constructor(t,e,i,s,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=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}var or=0;class Fn{constructor(t,e,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=or++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=(l)=>{let o=l.data,u=this.hls;if(!u||!(o!=null&&o.event)||o.instanceNo!==this.instanceNo)return;switch(o.event){case"init":{var d;let c=(d=this.workerContext)==null?void 0:d.objectURL;if(c)self.URL.revokeObjectURL(c);break}case"transmuxComplete":{this.handleTransmuxComplete(o.data);break}case"flush":{this.onFlush(o.data);break}case"workerLog":{if(u.logger[o.data.logType])u.logger[o.data.logType](o.data.message);break}default:{o.data=o.data||{},o.data.frag=this.frag,o.data.part=this.part,o.data.id=this.id,u.trigger(o.event,o.data);break}}},this.onWorkerError=(l)=>{if(!this.hls)return;let o=Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(v.ERROR,{type:q.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:o})};let r=t.config;this.hls=t,this.id=e,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;let n=(l,o)=>{if(o=o||{},o.frag=this.frag||void 0,l===v.ERROR)o=o,o.parent=this.id,o.part=this.part,this.error=o.error;this.hls.trigger(l,o)};this.observer=new dn,this.observer.on(v.FRAG_DECRYPTED,n),this.observer.on(v.ERROR,n);let a=ys(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){let l=this.hls.logger;if(r.workerPath||Vo()){try{if(r.workerPath)l.log(`loading Web Worker ${r.workerPath} for "${e}"`),this.workerContext=Ho(r.workerPath);else l.log(`injecting Web Worker for "${e}"`),this.workerContext=Ko();let{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:a,id:e,config:yt(r)})}catch(u){l.warn(`Error setting up "${e}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new Mi(this.observer,a,r,"",e,t.logger)}return}}this.transmuxer=new Mi(this.observer,a,r,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let t=this.instanceNo;this.instanceNo=or++;let e=this.hls.config,i=ys(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:yt(e)})}}terminateWorker(){if(this.workerContext){let{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),Wo(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let e=this.transmuxer;if(e)e.destroy(),this.transmuxer=null}let t=this.observer;if(t)t.removeAllListeners();this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,i,s,r,n,a,l,o,u){var d,c;o.transmuxing.start=self.performance.now();let{instanceNo:h,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,E=this.frag,y=E?r.cc!==E.cc:!0,p=E?o.level!==E.level:!0,S=E?o.sn-E.sn:-1,T=this.part?o.part-this.part.index:-1,x=S===0&&o.id>1&&o.id===(E==null?void 0:E.stats.chunkCount),A=!p&&(S===1||S===0&&(T===1||x&&T<=0)),b=self.performance.now();if(p||S||r.stats.parsing.start===0)r.stats.parsing.start=b;if(n&&(T||!A))n.stats.parsing.start=b;let I=!(E&&((d=r.initSegment)==null?void 0:d.url)===((c=E.initSegment)==null?void 0:c.url)),L=new wn(y,A,l,p,g,I);if(!A||y||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${o.sn}${o.part>-1?" part: "+o.part:""} ${this.id} playlist: ${o.level} id: ${o.id}
|
|
22
|
+
discontinuity: ${y}
|
|
23
|
+
trackSwitch: ${p}
|
|
24
|
+
contiguous: ${A}
|
|
25
|
+
accurateTimeOffset: ${l}
|
|
26
|
+
timeOffset: ${g}
|
|
27
|
+
initSegmentChange: ${I}`);let _=new On(i,s,e,a,u);this.configureTransmuxer(_)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:h,cmd:"demux",data:t,decryptdata:m,chunkMeta:o,state:L},t instanceof ArrayBuffer?[t]:[]);else if(f){let _=f.push(t,m,o,L);if(Se(_))_.then((P)=>{this.handleTransmuxComplete(P)}).catch((P)=>{this.transmuxerError(P,o,"transmuxer-interface push error")});else this.handleTransmuxComplete(_)}}flush(t){t.transmuxing.start=self.performance.now();let{instanceNo:e,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(i){let s=i.flush(t);if(Se(s))s.then((r)=>{this.handleFlushResult(r,t)}).catch((r)=>{this.transmuxerError(r,t,"transmuxer-interface flush error")});else this.handleFlushResult(s,t)}}transmuxerError(t,e,i){if(!this.hls)return;this.error=t,this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i})}handleFlushResult(t,e){t.forEach((i)=>{this.handleTransmuxComplete(i)}),this.onFlush(e)}configureTransmuxer(t){let{instanceNo:e,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t});else if(i)i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}function Mn(){return self.SourceBuffer||self.WebKitSourceBuffer}function Nn(){if(!jt())return!1;let e=Mn();return!e||e.prototype&&typeof e.prototype.appendBuffer==="function"&&typeof e.prototype.remove==="function"}function Ll(){if(!Nn())return!1;let t=jt();return typeof(t==null?void 0:t.isTypeSupported)==="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((e)=>t.isTypeSupported(bi(e,"video")))||["mp4a.40.2","fLaC"].some((e)=>t.isTypeSupported(bi(e,"audio"))))}function Rl(){var t;let e=Mn();return typeof(e==null||(t=e.prototype)==null?void 0:t.changeType)==="function"}var Dt={DISABLED:0,SWITCHING:1,SWITCHED:2},bl=100;class $n extends en{constructor(t,e,i){super(t,e,i,"stream-controller",Q.MAIN);this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=Dt.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let s=this.media,r=s?s.currentTime:null;if(r===null||!V(r))return;if(this.log(`Media seeked to ${r}`),!this.getBufferedFrag(r))return;let n=this.getFwdBufferInfoAtPos(s,r,Q.MAIN,0);if(!n||n.len===0){this.log(`Main buffer empty at ${r} on "seeked" event: ${n?n.len:n}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:t}=this;t.on(v.MANIFEST_PARSED,this.onManifestParsed,this),t.on(v.LEVEL_LOADING,this.onLevelLoading,this),t.on(v.LEVEL_LOADED,this.onLevelLoaded,this),t.on(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(v.BUFFER_CREATED,this.onBufferCreated,this),t.on(v.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(v.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:t}=this;t.off(v.MANIFEST_PARSED,this.onManifestParsed,this),t.off(v.LEVEL_LOADED,this.onLevelLoaded,this),t.off(v.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(v.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(v.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(v.BUFFER_CREATED,this.onBufferCreated,this),t.off(v.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(v.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){let{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(bl),this.level=-1,!this.startFragRequested){let r=s.startLevel;if(r===-1)if(s.config.testBandwidth&&this.levels.length>1)r=0,this.bitrateTest=!0;else r=s.firstAutoLevel;s.nextLoadLevel=r,this.level=s.loadLevel,this._hasEnoughToStart=!!e}if(i>0&&t===-1&&!e&&this.initPTS.length)this.log(`Override startPosition with lastCurrentTime @${i}`),t=i;if(this.state=w.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,!e&&!this.fragmentTracker.hasFragments(this.playlistType))this._hasEnoughToStart=this.startFragRequested=!1;this.tick()}else this._forceStartLoad=!0,this.state=w.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case w.WAITING_LEVEL:{let{levels:t,level:e}=this,i=t==null?void 0:t[e],s=i==null?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=w.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=w.IDLE;break}break}case w.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}if(this.state===w.IDLE)this.doTickIdle();this.onTickEnd()}onTickEnd(){var t;if(super.onTickEnd(),(t=this.media)!=null&&t.readyState&&this.media.seeking===!1)this.lastCurrentTime=this.media.currentTime;this.checkFragmentChanged()}doTickIdle(){let{hls:t,levelLastLoaded:e,levels:i,media:s}=this;if(e===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;let r=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(i!=null&&i[r]))return;let n=i[r],a=this.getMainFwdBufferInfo();if(a===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(a,l)){let g={type:this.targetBufferType()};this.hls.trigger(v.BUFFER_EOS,g),this.state=w.ENDED;return}if(!this.buffering)return;if(t.loadLevel!==r&&t.manualLevel===-1)this.log(`Adapting to level ${r} from level ${this.level}`);this.level=t.nextLoadLevel=r;let o=n.details;if(!o||this.state===w.WAITING_LEVEL||this.waitForLive(n)){this.level=r,this.state=w.WAITING_LEVEL,this.startFragRequested=!1;return}let u=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(u>=d)return;if(this.backtrackFragment&&this.backtrackFragment.start>a.end)this.backtrackFragment=void 0;let c=this.backtrackFragment?this.backtrackFragment.start:a.end,h=this.getNextFragment(c,o);if(this.couldBacktrack&&!this.fragPrevious&&h&&St(h)&&this.fragmentTracker.getState(h)!==mt.OK){var f;let m=((f=this.backtrackFragment)!=null?f:h).sn-o.startSN,E=o.fragments[m-1];if(E&&h.cc===E.cc)h=E,this.fragmentTracker.removeFragment(E)}else if(this.backtrackFragment&&a.len)this.backtrackFragment=void 0;if(h&&this.isLoopLoading(h,c)){if(!h.gap){let m=this.audioOnly&&!this.altAudio?rt.AUDIO:rt.VIDEO,E=(m===rt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;if(E)this.afterBufferFlushed(E,m)}h=this.getNextFragmentLoopLoading(h,o,a,Q.MAIN,d)}if(!h)return;if(this.exceedsMaxBuffer(a,d,h))return;this.loadFragment(h,n,c)}loadFragment(t,e,i){let s=this.fragmentTracker.getState(t);if(s===mt.NOT_LOADED||s===mt.PARTIAL)if(this.bitrateTest)this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e);else super.loadFragment(t,e,i);else this.clearTrackerIfNeeded(t)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==Dt.DISABLED){var t;if((((t=this.getLevelDetails())==null?void 0:t.fragmentStart)||0)>this.lastCurrentTime)super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){if(this.mediaBuffer&&this.altAudio===Dt.SWITCHED)return this.mediaBuffer;return this.media}checkFragmentChanged(){let t=this.fragPlaying;if(!this.checkFragPlaying())return!1;let i=this.fragPlaying;if(i){let s=i.level;if(this.hls.trigger(v.FRAG_CHANGED,{frag:i,previousFrag:t}),(t==null?void 0:t.level)!==s)this.hls.trigger(v.LEVEL_SWITCHED,{level:s})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(t){this._backtrackFragment=t}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(t){this._couldBacktrack=t}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.targetBufferType())}targetBufferType(){return this.altAudio===Dt.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(t,e){super.onMediaAttached(t,e);let i=e.media;pt(i,"playing",this.onMediaPlaying),pt(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){let{media:i}=this;if(i)ut(i,"playing",this.onMediaPlaying),ut(i,"seeked",this.onMediaSeeked);if(this.videoBuffer=null,super.onMediaDetaching(t,e),!!e.transferMedia)return;this._hasEnoughToStart=!1}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(v.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=Dt.DISABLED,this.audioOnly=!1}onManifestParsed(t,e){let i=!1,s=!1;for(let r=0;r<e.levels.length;r++){let n=e.levels[r].audioCodec;if(n)i=i||n.indexOf("mp4a.40.2")!==-1,s=s||n.indexOf("mp4a.40.5")!==-1}if(this.audioCodecSwitch=i&&s&&!Rl(),this.audioCodecSwitch)this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC");this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){let{levels:i}=this;if(!i||this.state!==w.IDLE)return;let s=e.levelInfo;if(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))this.state=w.WAITING_LEVEL}onLevelLoaded(t,e){var i;let{levels:s,startFragRequested:r}=this,{level:n,details:a}=e,l=a.totalduration;if(!s){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:${l}`);let o=e.levelInfo,u=this.fragCurrent;if(u&&(this.state===w.FRAG_LOADING||this.state===w.FRAG_LOADING_WAITING_RETRY)){if(u.level!==e.level&&u.loader)this.abortCurrentFrag()}let d=0;if(a.live||(i=o.details)!=null&&i.live){var c;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d=this.alignPlaylists(a,o.details,(c=this.levelLastLoaded)==null?void 0:c.details)}if(o.details=a,this.levelLastLoaded=o,!r)this.setStartPosition(a,d);if(this.hls.trigger(v.LEVEL_UPDATED,{details:a,level:n}),this.state===w.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=w.IDLE}if(r&&a.live)this.synchronizeToLiveEdge(a);this.initPTS.some((h,f)=>{if(f>=a.startCC)return!0;delete this.initPTS[f]}),this.tick()}synchronizeToLiveEdge(t){let{config:e,media:i}=this;if(!i)return;let s=this.hls.liveSyncPosition,r=this.playhead,{fragmentStart:n,edge:a}=t,l=r>=n-e.maxFragLookUpTolerance&&r<=a;if(s!==null&&i.duration>s&&(r<s||!l)){let u=e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if(!l&&i.readyState<4||r<a-u){if(!this._hasEnoughToStart)this.nextLoadPosition=s;if(i.readyState)if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s}`),this.config.liveSyncMode==="buffered"){var o;let d=j.bufferInfo(i,s,0);if(!((o=d.buffered)!=null&&o.length)){i.currentTime=s;return}if(d.start<=r){i.currentTime=s;return}let{nextStart:h}=j.bufferedInfo(d.buffered,r,0);if(h)i.currentTime=h}else i.currentTime=s}}}_handleFragmentLoadProgress(t){var e;let i=t.frag,{part:s,payload:r}=t,{levels:n}=this;if(!n){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let a=n[i.level];if(!a){this.warn(`Level ${i.level} not found on progress`);return}let l=a.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let o=a.videoCodec,u=l.PTSKnown||!l.live,d=(e=i.initSegment)==null?void 0:e.data,c=this._getAudioCodec(a),h=this.transmuxer=this.transmuxer||new Fn(this.hls,Q.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,g=f!==-1,{decryptRange:m,byteRange:E}=je(i,s,this.iframesOnly),y=new Qi(i.level,i.sn,i.stats.chunkCount,E?E.end-E.start:r.byteLength,f,g,i.duration,this.iframesOnly,m),p=this.initPTS[i.cc];h.push(r,d,c,o,i,s,l.totalduration,u,y,p)}onAudioTrackSwitching(t,e){let i=this.hls,s=this.altAudio!==Dt.DISABLED;if(!xs(e.url,i)){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let n=this.fragCurrent;if(n)this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n);this.resetTransmuxer(),this.resetLoadingState()}else if(this.audioOnly)this.resetTransmuxer();if(s){this.altAudio=Dt.DISABLED,this.fragmentTracker.removeAllFragments(),i.once(v.BUFFER_FLUSHED,()=>{if(!this.hls)return;this.hls.trigger(v.AUDIO_TRACK_SWITCHED,e)}),i.trigger(v.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(v.AUDIO_TRACK_SWITCHED,e)}else this.altAudio=Dt.SWITCHING}onAudioTrackSwitched(t,e){let i=xs(e.url,this.hls);if(i){let s=this.videoBuffer;if(s&&this.mediaBuffer!==s)this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s}this.altAudio=i?Dt.SWITCHED:Dt.DISABLED,this.tick()}onBufferCreated(t,e){let i=e.tracks,s,r,n=!1;for(let a in i){let l=i[a];if(l.id==="main"){if(r=a,s=l,a==="video"){let o=i[a];if(o)this.videoBuffer=o.buffer}}else n=!0}if(n&&s)this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer;else this.mediaBuffer=this.media}onFragBuffered(t,e){let{frag:i,part:s}=e,r=i.type===Q.MAIN;if(r){if(this.fragContextChanged(i)){if(this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===w.PARSED)this.state=w.IDLE;return}let l=!1;if(St(i))l=!!i.gap&&!i.tagList.some((o)=>o[0]==="GAP");if(this.fragBufferedComplete(i,s),l){var n;i.stats.retry++;let o=(n=this.levels)==null?void 0:n[i.level];if(o)o.fragmentError++}}let a=this.media;if(!a)return;if(!this._hasEnoughToStart&&j.getBuffered(a).length)this._hasEnoughToStart=!0,this.seekToStartPos();if(r)this.tick()}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal){this.state=w.ERROR;return}switch(e.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Q.MAIN,e);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:if(!e.levelRetry&&this.state===w.WAITING_LEVEL&&((i=e.context)==null?void 0:i.type)===J.LEVEL)this.state=w.IDLE;break;case R.BUFFER_APPEND_NO_PROGRESS:if(e.parent!=="main")return;if(e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry)this.warn(`Marking fragment ${e.frag.sn} of level ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(e.parent!=="main")return;if(this.reduceLengthAndFlushBuffer(e))this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(e.parent!=="main")return;if(this.reduceLengthAndFlushBuffer(e))if(!this.config.interstitialsController&&this.config.assetPlayerId)this._hasEnoughToStart=!0;else this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(e);break}}onFragLoadEmergencyAborted(){if(this.state=w.IDLE,!this._hasEnoughToStart)this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime;this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==rt.AUDIO||!this.altAudio){let i=(e===rt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;if(i)this.afterBufferFlushed(i,e),this.tick()}}onLevelsUpdated(t,e){if(this.level>-1&&this.fragCurrent){if(this.level=this.fragCurrent.level,this.level===-1)this.resetWhenMissingContext(this.fragCurrent)}this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:t}=this;if(!t)return;let e=t.currentTime,i=this.startPosition;if(i>=0&&e<i){if(t.seeking){this.log(`could not seek to ${i}, already seeking at ${e}`);return}let s=this.timelineOffset;if(s&&i)i+=s;let r=this.getLevelDetails(),n=j.getBuffered(t),a=n.length?n.start(0):0,l=a-i,o=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);if(this.config.startOnSegmentBoundary||l>0&&(l<o||this.loadingParts&&l<2*((r==null?void 0:r.partTarget)||0)))this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i;if(e<i)this.log(`seek to target start position ${i} from current time ${e} buffer start ${a}`),t.currentTime=i}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;if(this.audioCodecSwap&&e)if(this.log("Swapping audio codec"),e.indexOf("mp4a.40.5")!==-1)e="mp4a.40.2";else e="mp4a.40.5";return e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then((i)=>{let{hls:s}=this,r=i==null?void 0:i.frag;if(!r||this.fragContextChanged(r))return;e.fragmentError=0,this.state=w.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let n=r.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),s.trigger(v.FRAG_LOADED,i),r.bitrateTest=!1}).catch((i)=>{if(this.state===w.STOPPED||this.state===w.ERROR)return;this.warn(i),this.resetFragmentLoading(t)})}_handleTransmuxComplete(t){let e=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:r}=t,n=this.getCurrentContext(r);if(!n){this.resetWhenMissingContext(r);return}let{frag:a,part:l,level:o}=n,{video:u,text:d,id3:c,initSegment:h}=s,{details:f}=o,g=this.altAudio?void 0:s.audio;if(this.fragContextChanged(a)){this.fragmentTracker.removeFragment(a);return}if(this.state=w.PARSING,h){let m=h.tracks;if(m){let S=a.initSegment||a;if(this.unhandledEncryptionError(h,a))return;this._bufferInitSegment(o,m,S,r),i.trigger(v.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:e,tracks:m})}let{initPTS:E,timescale:y}=h,p=this.initPTS[a.cc];if(V(E)&&(!p||p.baseTime!==E||p.timescale!==y)){let S=h.trackId;this.initPTS[a.cc]={baseTime:E,timescale:y,trackId:S};let T=this.initPTS.slice(0);i.trigger(v.INIT_PTS_FOUND,{timestampOffsets:T,frag:a,id:e,initPTS:E,timescale:y,trackId:S})}}if(u&&f){if(g&&u.type==="audiovideo")this.logMuxedErr(a);let m=f.fragments[a.sn-1-f.startSN],E=a.sn===f.startSN,y=!m||a.cc>m.cc;if(s.independent!==!1){let{startPTS:p,endPTS:S,startDTS:T,endDTS:x}=u;if(l)l.elementaryStreams[u.type]={startPTS:p,endPTS:S,startDTS:T,endDTS:x};else{if(u.firstKeyFrame&&u.independent&&r.id===1&&!y)this.couldBacktrack=!0;if(u.dropped&&u.independent){let A=this.getMainFwdBufferInfo(),b=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,I=u.firstKeyFramePTS?u.firstKeyFramePTS:p;if(!E&&b<I-this.config.maxBufferHole&&!y){this.backtrack(a);return}else if(y)a.gap=!0;a.setElementaryStreamInfo(u.type,a.start,S,a.start,x,!0)}else if(E&&p-(f.appliedTimelineOffset||0)>Be)a.gap=!0}if(a.setElementaryStreamInfo(u.type,p,S,T,x),this.backtrackFragment)this.backtrackFragment=a;this.bufferFragmentData(u,a,l,r,E||y)}else if(E||y)a.gap=!0;else{this.backtrack(a);return}}if(g){let{startPTS:m,endPTS:E,startDTS:y,endDTS:p}=g;if(l)l.elementaryStreams[rt.AUDIO]={startPTS:m,endPTS:E,startDTS:y,endDTS:p};a.setElementaryStreamInfo(rt.AUDIO,m,E,y,p),this.bufferFragmentData(g,a,l,r)}if(f&&c!=null&&c.samples.length){let m={id:e,frag:a,details:f,samples:c.samples};i.trigger(v.FRAG_PARSING_METADATA,m)}if(f&&d){let m={id:e,frag:a,details:f,samples:d.samples};i.trigger(v.FRAG_PARSING_USERDATA,m)}}logMuxedErr(t){this.warn(`${St(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,s){if(this.state!==w.PARSING)return;if(this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly){if(delete e.audio,e.audiovideo)this.logMuxedErr(i)}let{audio:r,video:n,audiovideo:a}=e;if(r){let o=t.audioCodec,u=Me(r.codec,o);if(u==="mp4a")u="mp4a.40.5";if(this.audioCodecSwitch){if(u)if(u.indexOf("mp4a.40.5")!==-1)u="mp4a.40.2";else u="mp4a.40.5";let d=r.metadata;if(d&&"channelCount"in d&&(d.channelCount||1)!==1&&!Ba())u="mp4a.40.5"}if(u&&u.indexOf("mp4a.40.5")!==-1&&Ga()&&r.container!=="audio/mpeg")u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`);if(o&&o!==u)this.log(`Swapping manifest audio codec "${o}" for "${u}"`);r.levelCodec=u,r.id=Q.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${u||""}/${o||""}/${r.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=Q.MAIN;let o=n.codec;if((o==null?void 0:o.length)===4)switch(o){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";break}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${o}]${n.codec!==o?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}if(a){if(this.iframesOnly)this.logMuxedErr(i);this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),delete e.video,delete e.audio}let l=Object.keys(e);if(l.length){if(this.hls.trigger(v.BUFFER_CODECS,e),!this.hls)return;l.forEach((o)=>{let d=e[o].initSegment;if(d!=null&&d.byteLength)this.hls.trigger(v.BUFFER_APPENDING,{type:o,data:d,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let t=this.getBufferOutput();return this.getFwdBufferInfo(t,Q.MAIN)}get maxBufferLength(){let{levels:t,level:e}=this,i=t==null?void 0:t[e];if(!i)return this.config.maxBufferLength;return this.getMaxBufferLength(i.maxBitrate)}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=w.IDLE}get nextLevel(){let t=this.nextBufferedFrag;if(t)return t.level;return-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;let e=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(V(e))return this.getAppendedFrag(e);return null}get currentProgramDateTime(){var t;let e=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(V(e)){let i=this.getLevelDetails(),s=this.currentFrag||(i?qi(null,i.fragments,e):null);if(s){let r=s.programDateTime;if(r!==null){let n=r+(e-s.start)*1000;return new Date(n)}}}return null}get currentLevel(){let t=this.currentFrag;if(t)return t.level;return-1}get nextBufferedFrag(){let t=this.currentFrag;if(t)return this.followingBufferedFrag(t);return null}get forceStartLoad(){return this._forceStartLoad}}class ss{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new Ui}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(t,e,i){let s=this.stats;if(s.loading.start)throw Error("Loader can only be used once.");s.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}abort(){var t;if(this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort)this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;let t=this.config.loadPolicy.timeoutRetry,e=this.stats.retry;if(me(t,e,!0))this.retry(t);else{var i;st.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);let s=this.callbacks;if(s)this.abortInternal(),s.onTimeout(this.stats,this.context,this.getNetworkDetails())}}retry(t){let{context:e,stats:i}=this;this.retryDelay=Vi(t,i.retry),i.retry++,st.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${e==null?void 0:e.url}, retrying ${i.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}class Bn{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){let{chunks:t,dataLength:e}=this,i;if(!t.length)return new Uint8Array(0);else if(t.length===1)i=t[0];else i=Il(t,e);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function Il(t,e){let i=new Uint8Array(e),s=0;for(let r=0;r<t.length;r++){let n=t[r];i.set(n,s),s+=n.length}return i}function _l(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}var Dl=/(\d+)-(\d+)\/(\d+)/;class Ni extends ss{constructor(t){super();this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=t.fetchSetup||Ol}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){if(self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end)this.stats.aborted=!0,this.controller.abort()}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){let{config:t,context:e,stats:i}=this;if(!t||!e)return;i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;let s=Cl(e,this.controller.signal),r=e.responseType==="arraybuffer",n=r?"byteLength":"length",{maxTimeToFirstByteMs:a,maxLoadTimeMs:l}=t.loadPolicy;this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=a&&V(a)?a:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},t.timeout),(Se(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((u)=>{var d;this.response=u;let c=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(c-i.loading.start)),!u.ok){let{status:f,statusText:g}=u;throw new Un(g||"fetch, bad network response",f,u)}i.loading.first=c,i.total=kl(u.headers)||i.total;let h=(d=this.callbacks)==null?void 0:d.onProgress;if(h&&V(t.highWaterMark))return this.loadProgressively(u,i,e,t.highWaterMark,h);if(r)return u.arrayBuffer();if(e.responseType==="json")return u.json();return u.text()}).then((u)=>{var d,c;let h=this.response;if(!h)throw Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);let f=u[n];if(f)i.loaded=i.total=f;let g={url:h.url,data:u,code:h.status},m=(d=this.callbacks)==null?void 0:d.onProgress;if(m&&!V(t.highWaterMark))m(i,e,u,h);(c=this.callbacks)==null||c.onSuccess(g,i,e,h)}).catch((u)=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;let d=!u?0:u.code||0,c=!u?null:u.message,h=t.loadPolicy.errorRetry,f=i.retry,g={url:e.url,data:void 0,code:d};if(me(h,f,!1,g))this.retry(h);else{var m;st.error(`${d} while loading ${e.url}`),(m=this.callbacks)==null||m.onError({code:d,text:c},e,u?u.details:null,i)}})}getCacheAge(){let t=null;if(this.response){let e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,s=0,r){let n=new Bn,a=t.body.getReader(),l=()=>a.read().then((o)=>{if(o.done){if(n.dataLength)r(e,i,n.flush().buffer,t);return Promise.resolve(new ArrayBuffer(0))}let u=o.value,d=u.length;if(e.loaded+=d,d<s||n.dataLength){if(n.push(u),n.dataLength>=s)r(e,i,n.flush().buffer,t)}else r(e,i,u.buffer,t);return l()}).catch(()=>Promise.reject());return l()}}function Cl(t,e){let i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(dt({},t.headers))};if(t.rangeEnd)i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}function Pl(t){let e=Dl.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function kl(t){let e=t.get("Content-Range");if(e){let s=Pl(e);if(V(s))return s}let i=t.get("Content-Length");if(i)return parseInt(i)}function Ol(t,e){return new self.Request(t.url,e)}class Un extends Error{constructor(t,e,i){super(t);this.code=void 0,this.details=void 0,this.code=e,this.details=i}}var wl=(t,e,i)=>Math.max(e,Math.min(t,i)),Fl=/^age:\s*[\d.]+\s*$/im;class rs extends ss{constructor(t){super();this.xhrSetup=void 0,this.loader=null,this.xhrSetup=t.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){let t=this.loader;if(self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t){if(t.onreadystatechange=null,t.onprogress=null,t.readyState!==4)this.stats.aborted=!0,t.abort()}}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){let{config:t,context:e}=this;if(!t||!e)return;let i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;let r=this.xhrSetup;if(r)Promise.resolve().then(()=>{if(this.loader!==i||this.stats.aborted)return;return r.call(this,i,e.url,e)}).catch((n)=>{if(this.loader!==i||this.stats.aborted)return;return i.open("GET",e.url,!0),r.call(this,i,e.url,e)}).then(()=>{if(this.loader!==i||this.stats.aborted)return;this.openAndSendXhr(i,e,t)}).catch((n)=>{var a;(a=this.callbacks)==null||a.onError({code:i.status,text:n.message},e,i,s);return});else this.openAndSendXhr(i,e,t)}openAndSendXhr(t,e,i){if(!t.readyState)t.open("GET",e.url,!0);let s=e.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=i.loadPolicy;if(s)for(let a in s)t.setRequestHeader(a,s[a]);if(e.rangeEnd)t.setRequestHeader("Range",`bytes=${e.rangeStart}-${e.rangeEnd-1}`);t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),i.timeout=r&&V(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),t.send()}readystatechange(){let{context:t,loader:e,stats:i}=this;if(!t||!e)return;let s=e.readyState,r=this.config;if(i.aborted)return;if(s>=2){if(i.loading.first===0){if(i.loading.first=Math.max(self.performance.now(),i.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-(i.loading.first-i.loading.start))}if(s===4){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;let o=e.status,u=e.responseType==="text"?e.responseText:null;if(o>=200&&o<300){let f=u!=null?u:e.response;if(f!=null){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);let g=e.responseType==="arraybuffer"?f.byteLength:f.length;i.loaded=i.total=g,i.bwEstimate=i.total*8000/(i.loading.end-i.loading.first);let m=(n=this.callbacks)==null?void 0:n.onProgress;if(m)m(i,t,f,e);let E={url:e.responseURL,data:f,code:o};if(t.rangeEnd&&g!==t.rangeEnd-t.rangeStart)st.warn(`Payload length ${g} does not match requested Range: bytes=${t.rangeStart}-${t.rangeEnd-1}`);(a=this.callbacks)==null||a.onSuccess(E,i,t,e);return}}let d=r.loadPolicy.errorRetry,c=i.retry,h={url:t.url,data:void 0,code:o};if(me(d,c,!1,h))this.retry(d);else{var l;st.error(`${o} while loading ${t.url}`),(l=this.callbacks)==null||l.onError({code:o,text:e.statusText},t,e,i)}}}}loadprogress(t){let e=this.stats;if(e.loaded=t.loaded,t.lengthComputable)e.total=t.total}getCacheAge(){let t=null;if(this.loader&&Fl.test(this.loader.getAllResponseHeaders())){let e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){if(this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders()))return this.loader.getResponseHeader(t);return null}}var lr={maxTimeToFirstByteMs:8000,maxLoadTimeMs:20000,timeoutRetry:null,errorRetry:null},Ml=Tt(Tt({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:0.25,maxBufferSize:60000000,maxFragLookUpTolerance:0.25,maxBufferHole:0.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:0.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:0.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5000,fpsDroppedMonitoringThreshold:0.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:rs,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:500000,abrEwmaDefaultEstimateMax:5000000,abrBandWidthFactor:0.95,abrBandWidthUpFactor:0.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:null,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!1,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!1,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:lr},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8000,maxLoadTimeMs:20000,timeoutRetry:{maxNumRetry:1,retryDelayMs:1000,maxRetryDelayMs:20000,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1000,maxRetryDelayMs:20000,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:20000,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1000,maxRetryDelayMs:8000}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:20000,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1000,maxRetryDelayMs:8000}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:120000,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1000,maxRetryDelayMs:8000}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:20000,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1000,maxRetryDelayMs:8000}}},interstitialAssetListLoadPolicy:{default:lr},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1000,manifestLoadingMaxRetryTimeout:64000,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1000,levelLoadingMaxRetryTimeout:64000,fragLoadingTimeOut:20000,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1000,fragLoadingMaxRetryTimeout:64000,streamController:$n,abrController:wr,bufferController:an,capLevelController:Zi,errorController:Mr,fpsController:un,id3TrackController:hn,gapController:cn,latencyController:fn},Nl()),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:on,iframeController:void 0,interstitialsController:void 0});function Nl(){return{cueHandler:na,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function $l(t,e,i){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(e.liveMaxUnchangedPlaylistRefresh!==void 0){let a=e.liveMaxUnchangedPlaylistRefresh,l=wl(a,2,1/0);if(l!==a)i.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${a} to ${l}.`);e.liveMaxUnchangedPlaylistRefresh=l}let s=$i(t),r=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return r.forEach((a)=>{let l=`${a==="level"?"playlist":a}LoadPolicy`,o=e[l]===void 0,u=[];if(n.forEach((d)=>{let c=`${a}Loading${d}`,h=e[c];if(h!==void 0&&o){u.push(c);let f=s[l].default;switch(e[l]={default:f},d){case"TimeOut":f.maxLoadTimeMs=h,f.maxTimeToFirstByteMs=h;break;case"MaxRetry":f.errorRetry.maxNumRetry=h,f.timeoutRetry.maxNumRetry=h;break;case"RetryDelay":f.errorRetry.retryDelayMs=h,f.timeoutRetry.retryDelayMs=h;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=h,f.timeoutRetry.maxRetryDelayMs=h;break}}}),u.length)i.warn(`hls.js config: "${u.join('", "')}" setting(s) are deprecated, use "${l}": ${yt(e[l])}`)}),Tt(Tt({},s),e)}function $i(t){if(t&&typeof t==="object"){if(Array.isArray(t))return t.map($i);return Object.keys(t).reduce((e,i)=>(e[i]=$i(t[i]),e),{})}return t}function Bl(t,e){let i=t.loader;if(i!==Ni&&i!==rs)e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else if(_l())t.loader=Ni,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader")}class Gn extends zr{constructor(t,e){super(t,"level-controller");this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){let{hls:t}=this;t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(v.LEVEL_LOADED,this.onLevelLoaded,this),t.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(v.FRAG_BUFFERED,this.onFragBuffered,this),t.on(v.ERROR,this.onError,this)}_unregisterListeners(){let{hls:t}=this;t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(v.LEVEL_LOADED,this.onLevelLoaded,this),t.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(v.FRAG_BUFFERED,this.onFragBuffered,this),t.off(v.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,this._iframeVariants=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){let i=this.hls.config.preferManagedMediaSource,s=[],r={},n={},a=!1,l=!1,o=!1,u=!1;e.levels.forEach((d)=>{let c=d.attrs,h=ur(d,i),{audioCodec:f,videoCodec:g,imageCodec:m,width:E,height:y}=d;if(!h){this.log(`Some or all CODECS not supported "${c.CODECS}"`);return}a||(a=!!(E&&y)),l||(l=!!g),o||(o=!!f),u||(u=!!m);let{CODECS:p,"FRAME-RATE":S,"HDCP-LEVEL":T,"PATHWAY-ID":x,RESOLUTION:A,"VIDEO-RANGE":b}=c,L=`${`${x||"."}-`}${d.bitrate}-${A}-${S}-${p}-${b}-${T}`;if(!r[L]){let _=this.createLevel(d);r[L]=_,n[L]=1,s.push(_)}else if(r[L].uri!==d.url&&!d.attrs["PATHWAY-ID"]){let _=n[L]+=1;d.attrs["PATHWAY-ID"]=Array(_+1).join(".");let P=this.createLevel(d);r[L]=P,s.push(P)}else if(!d.iframes)r[L].addGroupId("audio",c.AUDIO),r[L].addGroupId("text",c.SUBTITLES)}),this.filterAndSortMediaOptions(s,e,a,l,o,u)}createLevel(t){let e=new ji(t),i=t.supplemental;if(i!=null&&i.videoCodec&&!Kn(i.videoCodec,this.hls.config.preferManagedMediaSource)){let s=Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),e.supportedResult=Gt.getUnsupportedResult(s,[])}return e}filterAndSortMediaOptions(t,e,i,s,r,n){var a;let l=[],o=[],u=t,d=((a=e.stats)==null?void 0:a.parsing)||{},c=this.hls.config.preferManagedMediaSource;if((i||s)&&r)u=u.filter(({videoCodec:T,videoRange:x,width:A,height:b})=>(!!T||!!(A&&b))&&qa(x));if(s&&n)u=u.filter((T)=>!T.imageCodec);if(u.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",x=T;if(e.levels.length)x=`one or more CODECS in variant not supported: ${yt(e.levels.map((b)=>b.attrs.CODECS).filter((b,I,L)=>L.indexOf(b)===I))}`,this.warn(x),T+=` (${x})`;let A=Error(T);this.hls.trigger(v.ERROR,{type:q.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:A,reason:x})}}),d.end=performance.now();return}if(e.audioTracks)l=e.audioTracks.filter((T)=>!T.audioCodec||Vn(T.audioCodec,c)),dr(l);if(e.subtitles)o=e.subtitles,dr(o);let h=u.slice(0);u.sort((T,x)=>{if(T.attrs["HDCP-LEVEL"]!==x.attrs["HDCP-LEVEL"])return(T.attrs["HDCP-LEVEL"]||"")>(x.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&T.height!==x.height)return T.height-x.height;if(T.frameRate!==x.frameRate)return T.frameRate-x.frameRate;if(T.videoRange!==x.videoRange)return Ye.indexOf(T.videoRange)-Ye.indexOf(x.videoRange);if(T.videoCodec!==x.videoCodec){let A=Es(T.videoCodec),b=Es(x.videoCodec);if(A!==b)return b-A}if(T.uri===x.uri&&T.codecSet!==x.codecSet){let A=He(T.codecSet),b=He(x.codecSet);if(A!==b)return b-A}if(T.averageBitrate!==x.averageBitrate)return T.averageBitrate-x.averageBitrate;return 0});let f=h[0];if(this.steering){if(u=this.steering.filterParsedLevels(u),u.length!==h.length){for(let T=0;T<h.length;T++)if(h[T].pathwayId===u[0].pathwayId){f=h[T];break}}}this._levels=u;for(let T=0;T<u.length;T++)if(u[T]===f){var g;this._firstLevel=T;let x=f.bitrate,A=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${x}`),((g=this.hls.userConfig)==null?void 0:g.abrEwmaDefaultEstimate)===void 0){let b=Math.min(x,this.hls.config.abrEwmaDefaultEstimateMax);if(b>A&&A===this.hls.abrEwmaDefaultEstimate)this.hls.bandwidthEstimate=b}break}let m=e.iframeVariants.filter((T)=>ur(T,c));this._iframeVariants=m;let E=r&&!s,y=this.hls.config,p=!!(y.audioStreamController&&y.audioTrackController),S={levels:u,audioTracks:l,subtitleTracks:o,iframeVariants:m,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:r,video:s,altAudio:p&&!E&&l.some((T)=>!!T.url)};d.end=performance.now(),this.hls.trigger(v.MANIFEST_PARSED,S)}get iframeVariants(){if(this._iframeVariants.length===0)return null;return this._iframeVariants}get levels(){if(this._levels.length===0)return null;return this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){let e=this._levels;if(e.length===0)return;if(t<0||t>=e.length){let u=Error("invalid level idx"),d=t<0;if(this.hls.trigger(v.ERROR,{type:q.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:t,fatal:d,error:u,reason:u.message}),d)return;t=Math.min(t,e.length-1)}let i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,i===t&&s&&r===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${i}${r?" with Pathway "+r:""}`);let l={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(v.LEVEL_SWITCHING,l);let o=n.details;if(!o||o.live){let u=this.switchParams(n.uri,s==null?void 0:s.details,o);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){if(this.manualLevelIndex=t,this._startLevel===void 0)this._startLevel=t;if(t!==-1)this.level=t}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){let t=this.hls.config.startLevel;if(t!==void 0)return t;return this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){if(this.steering)return this.steering.pathways();return[]}get pathwayPriority(){if(this.steering)return this.steering.pathwayPriority;return null}set pathwayPriority(t){if(this.steering){let e=this.steering.pathways(),i=t.filter((s)=>e.indexOf(s)!==-1);if(t.length<1){this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);return}this.steering.pathwayPriority=i}}onError(t,e){if(e.fatal||!e.context)return;if(e.context.type===J.LEVEL&&e.context.level===this.level)this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(e.type===Q.MAIN){let i=e.elementaryStreams;if(!Object.keys(i).some((r)=>!!i[r]))return;let s=this._levels[e.level];if(s!=null&&s.loadError)this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0}}onLevelLoaded(t,e){var i;let{level:s,details:r}=e,n=e.levelInfo;if(!n){var a;if(this.warn(`Invalid level index ${s}`),(a=e.deliveryDirectives)!=null&&a.skip)r.deltaUpdateFailed=!0;return}if(n===this.currentLevel||e.withoutMultiVariant){if(n.fragmentError===0)n.loadError=0;let l=n.details;if(l===e.details&&l.advanced)l=void 0;this.playlistLoaded(s,e,l)}else if((i=e.deliveryDirectives)!=null&&i.skip)r.deltaUpdateFailed=!0}loadPlaylist(t){if(super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel))this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);let i=this.getUrlWithDirectives(t.uri,e),s=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],n=t.details,a=n==null?void 0:n.age;this.log(`Loading level index ${s}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${a&&n.live?" age "+a.toFixed(1)+(n.type?" "+n.type||"":""):""} ${i}`),this.hls.trigger(v.LEVEL_LOADING,{url:i,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){if(this.manualLevelIndex!==-1)return this.manualLevelIndex;else return this.hls.nextAutoLevel}set nextLoadLevel(t){let e=this.currentLevelIndex;if(this.manualLevelIndex===-1&&t!==e&&t!==-1){let s=this.hls.config.abrSwitchInterval;if(s>0){let r=performance.now(),n=r-this.lastABRSwitchTime,a=s*1000;if(this.lastABRSwitchTime>-1&&n<a){this.warn(`Preventing ABR level switch: ${e} -> ${t} (${Math.round(n)}ms < ${a}ms / ${s}s)`);return}this.lastABRSwitchTime=r,this.log(`Allowing ABR level switch: ${e} -> ${t} (${Math.round(n)}ms >= ${a}ms / ${s}s)`)}}if(this.level=t,this.manualLevelIndex===-1)this.hls.nextAutoLevel=t}removeLevel(t){var e;if(this._levels.length===1)return;let i=this._levels.filter((r,n)=>{if(n!==t)return!0;if(this.steering)this.steering.removeLevel(r);if(r===this.currentLevel){if(this.currentLevel=null,this.currentLevelIndex=-1,r.details)r.details.fragments.forEach((a)=>a.level=-1)}return!1});if(qr(i),this._levels=i,this.currentLevelIndex>-1&&(e=this.currentLevel)!=null&&e.details)this.currentLevelIndex=this.currentLevel.details.fragments[0].level;if(this.manualLevelIndex>-1)this.manualLevelIndex=this.currentLevelIndex;let s=i.length-1;if(this._firstLevel=Math.min(this._firstLevel,s),this._startLevel)this._startLevel=Math.min(this._startLevel,s);this.hls.trigger(v.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){let{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;if(this._maxAutoLevel!==e)this._maxAutoLevel=e,this.hls.trigger(v.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i})}}function Vn(t,e){return Ee(t,"audio",e)}function Kn(t,e){return Ee(t,"video",e)}function ur(t,e){let{audioCodec:i,videoCodec:s}=t;if(i)t.audioCodec=i=We(i,e)||void 0;if(s)s=t.videoCodec=Wa(s);let{unknownCodecs:r}=t;if((r==null?void 0:r.length)||0||i&&!Vn(i,e)||s&&!Kn(s,e))return!1;return!0}function dr(t){let e={};t.forEach((i)=>{let s=i.groupId||"";i.id=e[s]=e[s]||0,e[s]++})}class Hn extends wt{constructor(t,e){super("key-loader",e);this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=t}abort(t){for(let i in this.keyLoaderInfo){let s=this.keyLoaderInfo[i].loader;if(s){var e;if(t&&t!==((e=s.context)==null?void 0:e.frag.type))return;s.abort()}}}destroy(){for(let t in this.keyLoaderInfo){let e=this.keyLoaderInfo[t].loader;if(e)e.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(t,e,i){if(this.emeController)return this.emeController.loadClear(t,e,i);return null}load(t,e){if(!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled)return this.emeController.selectKeySystemFormat(t).then((i)=>this.loadInternal(t,e,i));return this.loadInternal(t,e)}loadInternal(t,e,i){let s=t.decryptdata;if(!s){let n=Error(i?`Expected frag.decryptdata to be defined after setting format ${i}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Kt(t,R.KEY_LOAD_ERROR,n))}let r=t;switch(s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":if(s.keyFormat==="identity")return this.loadKeyHTTP(r);return e?e.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(Kt(t,R.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(t){if(this.emeController&&this.config.emeEnabled){var e;if(!t.decryptdata.keyId&&(e=t.initSegment)!=null&&e.data){let i=Da(t.initSegment.data);if(i.length){let s=i[0],r=t.decryptdata.uri;if(s.some((n)=>n!==0))this.log(`Using keyId found in init segment ${ee(s)} keyUri: ${r}`),ve.setKeyIdForUri(r,s);else{let n=ve.addKeyIdForUri(r);this.log(`Patching empty keyId with ${ee(n)} keyUri: ${r}`),s=n}t.decryptdata.keyId=s}}return this.emeController.loadKey(t).then(()=>({frag:t,keyInfo:{decryptdata:t.decryptdata}}))}return Promise.reject(Kt(t,R.KEY_LOAD_ERROR,Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(t){let e=t.decryptdata,i=e.uri;if(!i)return Promise.reject(Kt(t,R.KEY_LOAD_ERROR,Error(`Invalid key URI: "${i}"`)));let s=this.keyLoaderInfo[i];if(s){if(s.decryptdata.key)return e.key=s.decryptdata.key,s.keyLoadPromise=null,Promise.resolve({frag:t,keyInfo:s});if(s.keyLoadPromise)return s.keyLoadPromise.then((o)=>(e.key=s.decryptdata.key,Tt(Tt({},o),{},{frag:t})))}this.log(`Loading${e.keyId?" keyId: "+ee(e.keyId):""} URI: ${e.uri} from ${t.type} ${t.level}`);let r=this.config,a=new r.loader(r);t.keyLoader=a;let l=this.keyLoaderInfo[i]={decryptdata:e,keyLoadPromise:null,loader:a};return l.keyLoadPromise=new Promise((o,u)=>{let d={type:J.KEY,keyInfo:l,frag:t,responseType:"arraybuffer",url:i},c=r.keyLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},f={onSuccess:(g,m,E,y)=>{let{frag:p,keyInfo:S,url:T}=E;if(!p.decryptdata||S!==this.keyLoaderInfo[T])return u(Kt(p,R.KEY_LOAD_ERROR,Error("after key load, decryptdata unset or changed"),y));S.decryptdata.key=p.decryptdata.key=new Uint8Array(g.data),p.keyLoader=S.loader=S.keyLoadPromise=null,o({frag:p,keyInfo:S})},onError:(g,m,E,y)=>{this.resetLoader(m),u(Kt(t,R.KEY_LOAD_ERROR,Error(`HTTP Error ${g.code} loading key ${g.text}`),E,Tt({url:i,data:void 0},g)))},onTimeout:(g,m,E)=>{this.resetLoader(m),u(Kt(t,R.KEY_LOAD_TIMEOUT,Error("key loading timed out"),E))},onAbort:(g,m,E)=>{this.resetLoader(m),u(Kt(t,R.INTERNAL_ABORTED,Error("key loading aborted"),E))}};a.load(d,h,f)})}resetLoader(t){let{frag:e,keyInfo:i,url:s}=t,r=i.loader;if(e.keyLoader===r)e.keyLoader=i.loader=i.keyLoadPromise=null;if(delete this.keyLoaderInfo[s],r)r.destroy()}}function Kt(t,e=R.KEY_LOAD_ERROR,i,s,r){return new Rt({type:q.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:r,error:i,networkDetails:s||null})}function cr(t){let{type:e}=t;switch(e){case J.AUDIO_TRACK:return Q.AUDIO;case J.SUBTITLE_TRACK:return Q.SUBTITLE;default:return Q.MAIN}}function Ti(t,e){let i=t.url;if(i===void 0||i.indexOf("data:")===0)i=e.url;return i}class Wn{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:t}=this;t.on(v.MANIFEST_LOADING,this.onManifestLoading,this),t.on(v.LEVEL_LOADING,this.onLevelLoading,this),t.on(v.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(v.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(v.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:t}=this;t.off(v.MANIFEST_LOADING,this.onManifestLoading,this),t.off(v.LEVEL_LOADING,this.onLevelLoading,this),t.off(v.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(v.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(v.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){let e=this.hls.config,{pLoader:i,loader:s}=e,n=new(i||s)(e);return this.loaders[t.type]=n,n}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){if(this.loaders[t])delete this.loaders[t]}destroyInternalLoaders(){for(let t in this.loaders){let e=this.loaders[t];if(e)e.destroy();this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){let{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:J.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){let{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:l}=e;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:J.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:l})}onAudioTrackLoading(t,e){let{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:J.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){let{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:J.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){let i=this.loaders[J.LEVEL];if(i){let s=i.context;if(s&&!e.levels.some((r)=>r===s.levelOrTrack))i.abort(),delete this.loaders[J.LEVEL]}}load(t){var e;let i=this.hls.config,s=this.getInternalLoader(t);if(s){let o=this.hls.logger,u=s.context;if((u==null?void 0:u.levelOrTrack)===t.levelOrTrack&&(u.url===t.url||u.deliveryDirectives&&!t.deliveryDirectives)){if(u.url===t.url)o.log(`[playlist-loader]: ignore ${t.url} ongoing request`);else o.log(`[playlist-loader]: ignore ${t.url} in favor of ${u.url}`);return}o.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),s.abort()}let r;if(t.type===J.MANIFEST)r=i.manifestLoadPolicy.default;else r=dt({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null});if(s=this.createInternalLoader(t),V((e=t.deliveryDirectives)==null?void 0:e.part)){let o;if(t.type===J.LEVEL&&t.level!==null)o=this.hls.levels[t.level].details;else if(t.type===J.AUDIO_TRACK&&t.id!==null)o=this.hls.audioTracks[t.id].details;else if(t.type===J.SUBTITLE_TRACK&&t.id!==null)o=this.hls.subtitleTracks[t.id].details;if(o){let u=o.partTarget,d=o.targetduration;if(u&&d){let c=Math.max(u*3,d*0.8)*1000;r=dt({},r,{maxTimeToFirstByteMs:Math.min(c,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,r.maxTimeToFirstByteMs)})}}}let n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},l={onSuccess:(o,u,d,c)=>{let h=this.getInternalLoader(d);this.resetInternalLoader(d.type);let f=o.data;if(u.parsing.start=performance.now(),Ot.isMediaPlaylist(f)||d.type!==J.MANIFEST)this.handleTrackOrLevelPlaylist(o,u,d,c||null,h);else this.handleMasterPlaylist(o,u,d,c)},onError:(o,u,d,c)=>{this.handleNetworkError(u,d,!1,o,c)},onTimeout:(o,u,d)=>{this.handleNetworkError(u,d,!0,void 0,o)}};s.load(t,a,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:t,startPosition:e},forceStartLoad:i}=this.hls;if(t||i)this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e)}handleMasterPlaylist(t,e,i,s){let r=this.hls,n=t.data,a=Ti(t,i),l=Ot.parseMasterPlaylist(n,a);if(l.playlistParsingError){e.parsing.end=performance.now(),this.handleManifestParsingError(t,i,l.playlistParsingError,s,e);return}let{contentSteering:o,levels:u,iframeVariants:d,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:g}=l;this.variableList=g,u.forEach((p)=>{let{unknownCodecs:S}=p;if(S){let{preferManagedMediaSource:T}=this.hls.config,{audioCodec:x,videoCodec:A}=p;for(let b=S.length;b--;){let I=S[b];if(Ee(I,"audio",T))p.audioCodec=x=x?`${x},${I}`:I,se.audio[x.substring(0,4)]=2,S.splice(b,1);else if(Ee(I,"video",T))p.videoCodec=A=A?`${A},${I}`:I,se.video[A.substring(0,4)]=2,S.splice(b,1)}}});let{AUDIO:m=[],SUBTITLES:E,"CLOSED-CAPTIONS":y}=Ot.parseMasterPlaylistMedia(n,a,l);if(m.length){if(!m.some((S)=>!S.url)&&u[0].audioCodec&&!u[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 nt({}),bitrate:0,url:""})}r.trigger(v.MANIFEST_LOADED,{levels:u,audioTracks:m,subtitles:E,iframeVariants:d,captions:y,contentSteering:o,url:a,stats:e,networkDetails:s,sessionData:c,sessionKeys:h,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,e,i,s,r){let n=this.hls,{id:a,level:l,type:o}=i,u=Ti(t,i),d=V(l)?l:V(a)?a:0,c=cr(i),h=Ot.parseLevelPlaylist(t.data,u,d,c,0,this.variableList);if(o===J.MANIFEST){let f={attrs:new nt({}),bitrate:0,details:h,name:"",url:u};h.requestScheduled=e.loading.start+Wr(h,0),n.trigger(v.MANIFEST_LOADED,{levels:[f],audioTracks:[],iframeVariants:[],url:u,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),i.levelDetails=h,this.handlePlaylistLoaded(h,t,e,i,s,r)}handleManifestParsingError(t,e,i,s,r){this.hls.trigger(v.ERROR,{type:q.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:e.type===J.MANIFEST,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:s,stats:r})}handleNetworkError(t,e,i=!1,s,r){let n=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;if(t.type===J.LEVEL)n+=`: ${t.level} id: ${t.id}`;else if(t.type===J.AUDIO_TRACK||t.type===J.SUBTITLE_TRACK)n+=` id: ${t.id} group-id: "${t.groupId}"`;let a=Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let l=R.UNKNOWN,o=!1,u=this.getInternalLoader(t);switch(t.type){case J.MANIFEST:l=i?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,o=!0;break;case J.LEVEL:l=i?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,o=!1;break;case J.AUDIO_TRACK:l=i?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,o=!1;break;case J.SUBTITLE_TRACK:l=i?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,o=!1;break}if(u)this.resetInternalLoader(t.type);let d={type:q.NETWORK_ERROR,details:l,fatal:o,url:t.url,loader:u,context:t,error:a,networkDetails:e,stats:r};if(s){let c=t.url;if(e&&"url"in e)c=e.url;d.response=Tt({url:c,data:void 0},s)}this.hls.trigger(v.ERROR,d)}handlePlaylistLoaded(t,e,i,s,r,n){let a=this.hls,{type:l,level:o,levelOrTrack:u,id:d,groupId:c,deliveryDirectives:h}=s,f=Ti(e,s),g=cr(s),m=typeof s.level==="number"&&g===Q.MAIN?o:void 0,E=t.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${t.url}`),!a.config.ignorePlaylistParsingErrors){a.trigger(v.ERROR,{type:q.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:e,context:s,level:m,parent:g,networkDetails:r,stats:i});return}t.playlistParsingError=null}if(!t.fragments.length){let y=t.playlistParsingError=Error("No Segments found in Playlist");a.trigger(v.ERROR,{type:q.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:e,context:s,level:m,parent:g,networkDetails:r,stats:i});return}if(t.live&&n){if(n.getCacheAge)t.ageHeader=n.getCacheAge()||0;if(!n.getCacheAge||isNaN(t.ageHeader))t.ageHeader=0}switch(l){case J.MANIFEST:case J.LEVEL:if(m){if(!u)m=0;else if(u!==a.levels[m]){let y=a.levels.indexOf(u);if(y>-1)m=y}}a.trigger(v.LEVEL_LOADED,{details:t,levelInfo:u||a.levels[0],level:m||0,id:d||0,stats:i,networkDetails:r,deliveryDirectives:h,withoutMultiVariant:l===J.MANIFEST,context:s});break;case J.AUDIO_TRACK:a.trigger(v.AUDIO_TRACK_LOADED,{details:t,track:u,id:d||0,groupId:c||"",stats:i,networkDetails:r,deliveryDirectives:h,context:s});break;case J.SUBTITLE_TRACK:a.trigger(v.SUBTITLE_TRACK_LOADED,{details:t,track:u,id:d||0,groupId:c||"",stats:i,networkDetails:r,deliveryDirectives:h,context:s});break}}}class Yt{static get version(){return ye}static isMSESupported(){return Nn()}static isSupported(){return Ll()}static getMediaSource(){return jt()}static get Events(){return v}static get MetadataSchema(){return vt}static get ErrorTypes(){return q}static get ErrorDetails(){return R}static get DefaultConfig(){if(!Yt.defaultConfig)return Ml;return Yt.defaultConfig}static set DefaultConfig(t){Yt.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new dn,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let e=this.logger=sa(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),i=this.config=$l(Yt.DefaultConfig,t,e);if(this.userConfig=t,i.progressive)Bl(i,e);let{streamController:s,abrController:r,bufferController:n,capLevelController:a,errorController:l,fpsController:o,id3TrackController:u,iframeController:d,gapController:c}=i,h=new l(this),f=this.abrController=new r(this),g=new Xr(this),m=i.interstitialsController,E=m?this.interstitialsController=new m(this,Yt):null,y=n?this.bufferController=new n(this,g):null,p=a?this.capLevelController=new a(this):null,S=o?new o(this):null,T=i.cmcdController,x=T?this.cmcdController=new T(this):null,A=new Wn(this),b=i.contentSteeringController,I=b?new b(this):null,L=this.levelController=new Gn(this,I),_=u?new u(this):void 0,P=new Hn(this.config,this.logger),O=this.streamController=new s(this,g,P),H=this.gapController=c?new c(this,g):void 0;if(p)p.setStreamController(O);let M=[A,L,O];if(E)M.splice(1,0,E);if(I)M.splice(1,0,I);this.networkControllers=M;let C=[f];if(y)C.push(y);if(H)C.push(H);if(p)C.push(p);if(S)S.setStreamController(O),C.push(S);if(_)C.push(_);C.push(g),this.audioTrackController=this.createController(i.audioTrackController,M);let k=i.audioStreamController;if(k)M.push(this.audioStreamController=new k(this,g,P));this.subtitleTrackController=this.createController(i.subtitleTrackController,M);let U=i.subtitleStreamController;if(U)M.push(this.subtititleStreamController=new U(this,g,P));if(this.createController(i.timelineController,C),P.emeController=this.emeController=this.createController(i.emeController,C),x)C.push(x);this.latencyController=this.createController(i.latencyController,C),this.coreComponents=C,this.iframeController=d?new d(this,Yt):void 0,M.push(h);let D=h.onErrorOut;if(typeof D==="function")this.on(v.ERROR,D,h);this.on(v.MANIFEST_LOADED,A.onManifestLoaded,A)}createController(t,e){if(t){let i=new t(this);if(e)e.push(i);return i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,s){this._emitter.off(t,e,i,s)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);else try{return this.emit(t,t,e)}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;let s=t===v.ERROR;this.trigger(v.ERROR,{type:q.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:s,event:t,error:i}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(v.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((e)=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach((e)=>e.destroy()),this.coreComponents.length=0,this.iframeController=void 0;let t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){let r=Error(`attachMedia failed: invalid argument (${t})`);this.trigger(v.ERROR,{type:q.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}if(this.logger.log("attachMedia"),this._media)this.logger.warn("media must be detached before attaching"),this.detachMedia();let e="media"in t,i=e?t.media:t,s=e?t:{media:i};this._media=i,this.trigger(v.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia");let t={};this.trigger(v.MEDIA_DETACHING,t),this._media=null,this.trigger(v.MEDIA_DETACHED,t)}transferMedia(){var t;this._media=null;let e=((t=this.bufferController)==null?void 0:t.transferMedia())||null,i={transferMedia:e};return this.trigger(v.MEDIA_DETACHING,i),this.trigger(v.MEDIA_DETACHED,i),e}loadSource(t){var e;this.stopLoad();let i=this.media,s=this._url,r=this._url=Bi.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});if(this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),i&&s&&(s!==r||(e=this.bufferController)!=null&&e.hasSourceTypes()))this.detachMedia(),this.attachMedia(i);this.trigger(v.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length;i++)if(this.networkControllers[i].startLoad(t,e),!this.started||!this.networkControllers)break}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length;t++)if(this.networkControllers[t].stopLoad(),this.started||!this.networkControllers)break}get loadingEnabled(){return this.started&&this.streamController.state!==w.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){if(!this.bufferingEnabled)this.logger.log("resume buffering"),this.networkControllers.forEach((t)=>{if(t.resumeBuffering)t.resumeBuffering()})}pauseBuffering(){if(this.bufferingEnabled)this.logger.log("pause buffering"),this.networkControllers.forEach((t)=>{if(t.pauseBuffering)t.pauseBuffering()})}get inFlightFragments(){let t={[Q.MAIN]:this.streamController.inFlightFrag};if(this.audioStreamController)t[Q.AUDIO]=this.audioStreamController.inFlightFrag;if(this.subtititleStreamController)t[Q.SUBTITLE]=this.subtititleStreamController.inFlightFrag;return t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let t=this._media,e=this.started,i=t==null?void 0:t.currentTime;if(this.detachMedia(),t){if(this.attachMedia(t),e){if(i)this.startLoad(i);else if(!this.config.autoStartLoad)this.startLoad()}}}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;if(!t)t=this._sessionId=da();return t}get levels(){let t=this.levelController.levels;return t?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(){let t=this.levelController.startLevel;if(t===-1&&this.abrController.forcedAutoLevel>-1)return this.abrController.forcedAutoLevel;return t}set startLevel(t){if(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){let e=this.capLevelController,i=!!t;if(e&&i!==this.config.capLevelToPlayerSize){if(i)e.startCapping();else e.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch();this.config.capLevelToPlayerSize=i}}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:t}=this.abrController;if(!t)return NaN;return t.getEstimate()}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){let{bwEstimator:t}=this.abrController;if(!t)return NaN;return t.defaultEstimate}get ttfbEstimate(){let{bwEstimator:t}=this.abrController;if(!t)return NaN;return t.getEstimateTTFB()}set autoLevelCapping(t){if(this._autoLevelCapping!==t)this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated()}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){if(ja(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(){let{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;let i=t.length;for(let s=0;s<i;s++)if(t[s].maxBitrate>=e)return s;return 0}get maxAutoLevel(){let{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this,s;if(e===-1&&t!=null&&t.length)s=t.length-1;else s=e;if(i)for(let r=s;r--;){let n=t[r].attrs["HDCP-LEVEL"];if(n&&n<=i)return r}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var t;return((t=this.audioStreamController)==null?void 0:t.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return((e=this.audioTrackController)==null?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return((e=this.subtitleTrackController)==null?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){let t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){let t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){let t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){let e=this.audioTrackController;if(e)e.audioTrack=t}get nextAudioTrack(){var t,e;return(t=(e=this.audioStreamController)==null?void 0:e.nextAudioTrack)!=null?t:-1}set nextAudioTrack(t){let{audioTrackController:e}=this;if(e)e.nextAudioTrack=t}get allSubtitleTracks(){let t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){let t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){let t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){let e=this.subtitleTrackController;if(e)e.subtitleTrack=t}get subtitleDisplay(){let t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){let e=this.subtitleTrackController;if(e)e.subtitleDisplay=t}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){var t,e;return(t=(e=this.latencyController)==null?void 0:e.liveSyncPosition)!=null?t:null}get latency(){var t;return((t=this.latencyController)==null?void 0:t.latency)||0}get maxLatency(){var t;return((t=this.latencyController)==null?void 0:t.maxLatency)||0}get targetLatency(){var t;return((t=this.latencyController)==null?void 0:t.targetLatency)||null}set targetLatency(t){if(!this.latencyController)return;this.latencyController.targetLatency=t}get drift(){var t;return((t=this.latencyController)==null?void 0:t.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){return null}get iframeVariants(){let t=this.levelController.iframeVariants;return t?t:[]}createIFramePlayer(t){return null}createImageIFramePlayer(t){return null}getMediaDecodingInfo(t,e=this.allAudioTracks){let i=Or(e);return Gt.getMediaDecodingInfoPromise(t,i,navigator.mediaCapabilities)}}Yt.defaultConfig=void 0;var{KeySystemFormats:Gl,KeySystems:Vl,SubtitleStreamController:Kl,TimelineController:Hl,requestMediaKeySystemAccess:Wl}=Gt;export{Yt as default};
|