1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9412],{93041:function(e,t,i){let r,s,a,n,l,o,h;i.d(t,{ZP:function(){return lg}});let d=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},u=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=f},f=Number.MAX_SAFE_INTEGER||9007199254740991,c=((R={}).NETWORK_ERROR="networkError",R.MEDIA_ERROR="mediaError",R.KEY_SYSTEM_ERROR="keySystemError",R.MUX_ERROR="muxError",R.OTHER_ERROR="otherError",R),g=((b={}).KEY_SYSTEM_NO_KEYS="keySystemNoKeys",b.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",b.KEY_SYSTEM_NO_SESSION="keySystemNoSession",b.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",b.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",b.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",b.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",b.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",b.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",b.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",b.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",b.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",b.MANIFEST_LOAD_ERROR="manifestLoadError",b.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",b.MANIFEST_PARSING_ERROR="manifestParsingError",b.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",b.LEVEL_EMPTY_ERROR="levelEmptyError",b.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",b.LEVEL_LOAD_ERROR="levelLoadError",b.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",b.LEVEL_PARSING_ERROR="levelParsingError",b.LEVEL_SWITCH_ERROR="levelSwitchError",b.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",b.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",b.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",b.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",b.FRAG_LOAD_ERROR="fragLoadError",b.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",b.FRAG_DECRYPT_ERROR="fragDecryptError",b.FRAG_PARSING_ERROR="fragParsingError",b.FRAG_GAP="fragGap",b.REMUX_ALLOC_ERROR="remuxAllocError",b.KEY_LOAD_ERROR="keyLoadError",b.KEY_LOAD_TIMEOUT="keyLoadTimeOut",b.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",b.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",b.BUFFER_APPEND_ERROR="bufferAppendError",b.BUFFER_APPENDING_ERROR="bufferAppendingError",b.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",b.BUFFER_STALLED_ERROR="bufferStalledError",b.BUFFER_FULL_ERROR="bufferFullError",b.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",b.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",b.ASSET_LIST_LOAD_ERROR="assetListLoadError",b.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",b.ASSET_LIST_PARSING_ERROR="assetListParsingError",b.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",b.INTERNAL_EXCEPTION="internalException",b.INTERNAL_ABORTED="aborted",b.ATTACH_MEDIA_ERROR="attachMediaError",b.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",b.UNKNOWN="unknown",b),m=((D={}).MEDIA_ATTACHING="hlsMediaAttaching",D.MEDIA_ATTACHED="hlsMediaAttached",D.MEDIA_DETACHING="hlsMediaDetaching",D.MEDIA_DETACHED="hlsMediaDetached",D.MEDIA_ENDED="hlsMediaEnded",D.STALL_RESOLVED="hlsStallResolved",D.BUFFER_RESET="hlsBufferReset",D.BUFFER_CODECS="hlsBufferCodecs",D.BUFFER_CREATED="hlsBufferCreated",D.BUFFER_APPENDING="hlsBufferAppending",D.BUFFER_APPENDED="hlsBufferAppended",D.BUFFER_EOS="hlsBufferEos",D.BUFFERED_TO_END="hlsBufferedToEnd",D.BUFFER_FLUSHING="hlsBufferFlushing",D.BUFFER_FLUSHED="hlsBufferFlushed",D.MANIFEST_LOADING="hlsManifestLoading",D.MANIFEST_LOADED="hlsManifestLoaded",D.MANIFEST_PARSED="hlsManifestParsed",D.LEVEL_SWITCHING="hlsLevelSwitching",D.LEVEL_SWITCHED="hlsLevelSwitched",D.LEVEL_LOADING="hlsLevelLoading",D.LEVEL_LOADED="hlsLevelLoaded",D.LEVEL_UPDATED="hlsLevelUpdated",D.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",D.LEVELS_UPDATED="hlsLevelsUpdated",D.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",D.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",D.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",D.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",D.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",D.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",D.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUp
1dated",D.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",D.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",D.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",D.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",D.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",D.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",D.CUES_PARSED="hlsCuesParsed",D.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",D.INIT_PTS_FOUND="hlsInitPtsFound",D.FRAG_LOADING="hlsFragLoading",D.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",D.FRAG_LOADED="hlsFragLoaded",D.FRAG_DECRYPTED="hlsFragDecrypted",D.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",D.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",D.FRAG_PARSING_METADATA="hlsFragParsingMetadata",D.FRAG_PARSED="hlsFragParsed",D.FRAG_BUFFERED="hlsFragBuffered",D.FRAG_CHANGED="hlsFragChanged",D.FPS_DROP="hlsFpsDrop",D.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",D.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",D.ERROR="hlsError",D.DESTROYING="hlsDestroying",D.KEY_LOADING="hlsKeyLoading",D.KEY_LOADED="hlsKeyLoaded",D.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",D.BACK_BUFFER_REACHED="hlsBackBufferReached",D.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",D.ASSET_LIST_LOADING="hlsAssetListLoading",D.ASSET_LIST_LOADED="hlsAssetListLoaded",D.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",D.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",D.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",D.INTERSTITIAL_STARTED="hlsInterstitialStarted",D.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",D.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",D.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",D.INTERSTITIAL_ENDED="hlsInterstitialEnded",D.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",D.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",D.EVENT_CUE_ENTER="hlsEventCueEnter",D);var p,E,v,y,T,S,A,I,L,R,b,D,k,P,_={exports:{}},C=(k||(k=1,p=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,E=/^(?=([^\/?#]*))\1([^]*)$/,v=/(?:\/|^)\.(?=\/)/g,y=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,T={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var r=T.parseURL(e);if(!r)throw Error("Error trying to parse base URL.");return r.path=T.normalizePath(r.path),T.buildURLFromParts(r)}var s=T.parseURL(t);if(!s)throw Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=T.normalizePath(s.path),T.buildURLFromParts(s)):t;var a=T.parseURL(e);if(!a)throw Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var n=E.exec(a.path);a.netLoc=n[1],a.path=n[2]}a.netLoc&&!a.path&&(a.path="/");var l={scheme:a.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(l.netLoc=a.netLoc,"/"!==s.path[0])){if(s.path){var o=a.path,h=o.substring(0,o.lastIndexOf("/")+1)+s.path;l.path=T.normalizePath(h)}else l.path=a.path,s.params||(l.params=a.params,s.query||(l.query=a.query))}return null===l.path&&(l.path=i.alwaysNormalize?T.normalizePath(s.path):s.path),T.buildURLFromParts(l)},parseURL:function(e){var t=p.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(v,"");e.length!==(e=e.replace(y,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},_.exports=T),_.exports);class O{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 M={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack",MEDIA_FRAGMENT:"media-fragment",KEY:"key",STEERING_MANIFEST:"steering-manifest",SERVER_CERTIFICATE:"server-certificate",INTERSTITIAL_ASSET_LIST:"interstitial-asset-list"},w={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},F={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class x{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){let i=function e(t,i){let r=Object.getPrototypeOf(t);if(r)return Object.getOwnPropertyDescriptor(r,i)||e(r,i)}(e,t);i&&(i.enumerable=!0,Object.defineProperty(e,t,i))}(this,"stats")}
1setByteRange(e,t){let i;let r=e.split("@",2);i=1===r.length?(null==t?void 0:t.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[F.AUDIO]:null,[F.VIDEO]:null,[F.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new O),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=C.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[F.AUDIO]=null,e[F.VIDEO]=null,e[F.AUDIOVIDEO]=null,this.url=null}}function N(e){return"initSegment"!==e.sn}function $(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level}function U(e,t){return e.sn===(null==t?void 0:t.sn)&&e.level===t.level&&e.cc===t.cc}class B extends x{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(d(e)&&d(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!(null!=(e=this._decryptdata)&&e.keyId)){let e=Object.keys(t);if(1===e.length){let i=this._decryptdata=t[e[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;let e=d(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e,t;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){let e=Object.keys(this.levelkeys),i=e.length;if(i>1||1===i&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!d(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return N(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var i;let r=t[e];r&&!(null!=(i=this._decryptdata)&&i.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,r,s,a=!1){let{elementaryStreams:n}=this,l=n[e];if(!l){n[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:s,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,s)}}class G extends x{constructor(e,t,i,r,s){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=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===w.SUBTITLE&&this.stats.loaded)}}function K(){return(K=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)({}).hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e}).apply(null,arguments)}function V(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function H(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};
1t%2?V(Object(i),!0).forEach(function(t){var r,s;r=t,s=i[t],(r=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=typeof r)return r;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(r))in e?Object.defineProperty(e,r,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[r]=s}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):V(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function Y(e,t){if(null==e)return{};var i,r,s=function(e,t){if(null==e)return{};var i={};for(var r in e)if(({}).hasOwnProperty.call(e,r)){if(-1!==t.indexOf(r))continue;i[r]=e[r]}return i}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)i=a[r],-1===t.indexOf(i)&&({}).propertyIsEnumerable.call(e,i)&&(s[i]=e[i])}return s}function W(e){switch(e.details){case g.FRAG_LOAD_TIMEOUT:case g.KEY_LOAD_TIMEOUT:case g.LEVEL_LOAD_TIMEOUT:case g.MANIFEST_LOAD_TIMEOUT:case g.AUDIO_TRACK_LOAD_TIMEOUT:case g.SUBTITLE_TRACK_LOAD_TIMEOUT:case g.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function j(e){return e.details.startsWith("key")}function q(e){return j(e)&&!!e.frag&&!e.frag.decryptdata}function X(e,t){let i=W(t);return e.default[`${i?"timeout":"error"}Retry`]}function z(e,t){return Math.min(("linear"===e.backoff?1:Math.pow(2,t))*e.retryDelayMs,e.maxRetryDelayMs)}function Q(e){return H(H({},e),{errorRetry:null,timeoutRetry:null})}function Z(e,t,i,r){if(!e)return!1;let s=null==r?void 0:r.code,a=t<e.maxNumRetry&&(J(s)||!!s&&(s<400||s>499)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,a):a}function J(e){return 0===e&&!1===navigator.onLine}function ee(e,t){return t>0&&e.loadError>0&&0!==e.loadErrorTime&&self.performance.now()-e.loadErrorTime>t}class et{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class ei{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_
1=new et(e),this.fast_=new et(t),this.defaultTTFB_=r,this.ttfb_=new et(e)}update(e,t){let{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==e&&(this.slow_=new et(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new et(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new et(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){if(t<=0)return;let i=Math.max(e,Math.min(this.minDelayMs_,t/1e5))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){this.ttfb_.sample(Math.sqrt(2)*Math.exp(-Math.pow(e/1e3,2)/2),Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class er{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let i=`[${e}]:`;this.trace=es,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}}let es=function(){},ea={trace:es,debug:es,log:es,warn:es,info:es,error:es};function en(){return K({},ea)}function el(e,t,i){return t[e]?t[e].bind(t):function(e,t){let i=self.console[e];return i?i.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):es}(e,i)}let eo=en();function eh(e=!0){if("undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ed(e,t){let i=Object.keys(e),r=Object.keys(t),s=i.length,a=r.length;return!s||!a||s===a&&!i.some(e=>-1===r.indexOf(e))}function eu(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}let ef="utf-16be",ec="utf-16le",eg="utf-8";function em(){try{return crypto.randomUUID()}catch(e){try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch(t){let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)})}}}function ep(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function eE(e,t){return(127&e[t])<<21|(127&e[t+1])<<14|(127&e[t+2])<<7|127&e[t+3]}function ev(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function ey(e,t){let i=t,r=0;for(;ep(e,t);)r+=10+eE(e,t+6),ev(e,t+10)&&(r+=10),t+=r;if(r>0)return e.subarray(i,i+r)}function eT(e,t=0,i=1/0){return function(e,t,i,r){let s=eu(e)?e:e.buffer,a=1;"BYTES_PER_ELEMENT"in r&&(a=r.BYTES_PER_ELEMENT);let n=e&&eu(e.buffer)&&void 0!==e.byteLength&&void 0!==e.byteOffset?e.byteOffset:0,l=(n+e.byteLength)/a,o=Math.floor(Math.max(0,Math.min((n+t)/a,l)));return new r(s,o,Math.floor(Math.min(o+Math.max(i,0),l))-o)}(e,t,i,Uint8Array)}function eS(e,t=!1){let i=t?e.indexOf(0):e.length,r=function(e,t={}){let i,r;i=eu(e)?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength);let s=0,{encoding:a}=t;if(!a){let e=i.getUint8(0),t=i.getUint8(1);239==e&&187==t&&191==i.getUint8(2)?(a=eg,s=3):254==e&&255==t?(a=ef,s=2):255==e&&254==t?(a=ec,s=2):a=eg}if("undefined"!=typeof TextDecoder)return new TextDecoder(a).decode(i);let{byteLength:n}=i,l=a!==ef,o="";for(;s<n;){switch(a){case eg:if((r=i.getUint8(s))<128)s++;else if(r>=194&&r<=223){if(s+1<n){let e=i.getUint8(s+1);e>=128&&e<=191?(r=(31&r)<<6|63&e,s+=2):s++}else s++}else if(r>=224&&r<=239){if(s+2<=n-1){let e=i.getUint8(s+1),t=i.getUint8(s+2);e>=128&&e<=191&&t>=128&&t<=191?(r=(15&r)<<12|(63&e)<<6|63&t,s+=3):s++}else s++}else if(r>=240&&r<=244){if(s+3<=n-1){let e=i.getUint8(s+1),t=i.getUint8(s+2),a=i.getUint8(s+3);e>=128&&e<=191&&t>=128&&t<=191&&a>=128&&a<=191?(r=(7&r)<<18|(63&e)<<12|(63&t)<<6|63&a,s+=4):s++}else s++}
1else s++;break;case ef:case"utf-16":case ec:r=i.getUint16(s,l),s+=2}o+=String.fromCodePoint(r)}return o}(new DataView(e.buffer,e.byteOffset,i),{encoding:eg});return t?r:r.replace(/\0/g,"")}function eA(e){let t=0,i=[];for(;ep(e,t);){let r=eE(e,t+6);e[t+5]>>6&1&&(t+=10);let s=(t+=10)+r;for(;t+10<s;){let r=function(e){let t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=eE(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}(e.subarray(t)),s="PRIV"===r.type?function(e){if(e.size<2)return;let t=eS(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}(r):"W"===r.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1,i=eS(e.data.subarray(t),!0);t+=i.length+1;let r=eS(e.data.subarray(t));return{key:e.type,info:i,data:r}}let t=eS(e.data);return{key:e.type,info:"",data:t}}(r):"APIC"===r.type?function(e){let t;let i={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0]){console.log("Ignore frame with unrecognized character encoding");return}let r=e.data.subarray(1).indexOf(0);if(-1===r)return;let s=eS(eT(e.data,1,r)),a=e.data[2+r],n=e.data.subarray(3+r).indexOf(0);if(-1===n)return;let l=eS(eT(e.data,3+r,n));if("-->"===s)t=eS(eT(e.data,4+r+n));else{var o;t=eu(o=e.data.subarray(4+r+n))?o:0==o.byteOffset&&o.byteLength==o.buffer.byteLength?o.buffer:new Uint8Array(o).buffer}return i.mimeType=s,i.pictureType=a,i.description=l,i.data=t,i}(r):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1,{data:i}=e,r=eS(i.subarray(t),!0);t+=r.length+1;let s=eS(i.subarray(t));return{key:e.type,info:r,data:s}}let t=eS(e.data.subarray(1));return{key:e.type,info:"",data:t}}(r);s&&i.push(s),t+=r.size+10}ev(e,t)&&(t+=10)}return i}function eI(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function eL(e){for(let t of eA(e))if(eI(t))return function(e){if(8===e.data.byteLength){let t=new Uint8Array(e.data),i=1&t[3],r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}(t)}function eR(e){let t="";for(let i=0;i<e.length;i++){let r=e[i].toString(16);r.length<2&&(r="0"+r),t+=r}return t}function eb(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function eD(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function ek(e){return String.fromCharCode.apply(null,e)}let eP={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},e_={video:1,audio:2,id3:3,text:4};function eC(e,t){let i=e[t]<<8|e[t+1];return i<0?65536+i:i}function eO(e,t){let i=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return i<0?4294967296+i:i}function eM(e,t){let i=eO(e,t);return i*=4294967296,i+=eO(e,t+4)}function ew(e,t){let i="";for(let r=t;r<e.length;r++)if(i+=String.fromCharCode(e[r]),0===e[r])return i;return null}function eF(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function ex(e,t,i){e[t]=i>>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i}function eN(e,t,i){let r=t.byteOffset-e.byteOffset-8,s=8+i,a=t.byteLength+8-s;a<8||(ex(e,r,s),ex(e,r+s,a),ex(e,r+s+4,eP.free))}function e$(e,t){return[e.byteOffset-t-8,e.byteOffset-t+e.byteLength]}function eU(e,t){t.sort((e,t)=>e[0]-t[0]);let i=t.reduce((e,[t,i])=>e+i-t,0),r=new Uint8Array(e.byteLength-i),s=0,a=0;for(let i=0;i<t.length;i++){let[n,l]=t[i];r.set(e.subarray(s,n),a),a+=n-s,s=l}return r.set(e.subarray(s),a),{result:r,dropped:i,droppedBefore:e=>t.reduce((t,[i,r])=>r<=e?t+r-i:t,0)}}function eB(e,t){let i=[];return t.length&&function e(t,i,r,s,a,n){let l=i[r];if((null==l?void 0:l.length)!==4)return;let o=l.charCodeAt(0),h=l.charCodeAt(1),d=l.charCodeAt(2),u=l.charCodeAt(3),f=i.length-1;for(let l=s;l<a;){let s=l+8<=a,c=l+4<=a?16777216*t[l]+(t[l+1]<<16|t[l+2]<<8|t[l+3]):eO(t,l),g=c>1?l+c:a;if(s&&t[l+4]===o&&t[l+5]===h&&t[l+6]===d&&t[l+7]===u){let s=Math.min(g,a);
1r===f?n.push(t.subarray(l+8,s)):e(t,i,r+1,l+8,s,n)}l=g}}(e,t,0,0,e.byteLength,i),i}function eG(e){let t=[],i=eB(e,["moov","trak"]);for(let e=0;e<i.length;e++){let r=i[e],s=eB(r,["tkhd"])[0];if(s){let e=s[0],i=eO(s,0===e?12:20),a=eB(r,["mdia","mdhd"])[0];if(a){e=a[0];let s=eO(a,0===e?12:20),n=eB(r,["mdia","hdlr"])[0];if(n){let e=ek(n.subarray(8,12)),a={soun:F.AUDIO,vide:F.VIDEO}[e],l=function(e){let t;let i=e.subarray(8),r=i.subarray(86),s=ek(i.subarray(4,8)),a=s,n="enca"===s||"encv"===s;if(n){let e=eB(i,[s])[0].subarray("enca"===s?28:78);eB(e,["sinf"]).forEach(e=>{let t=eB(e,["schm"])[0];if(t){let i=ek(t.subarray(4,8));if("cbcs"===i||"cenc"===i){let t=eB(e,["frma"])[0];t&&(a=ek(t))}}})}let l=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{let e=eB(r,["avcC"])[0];e&&e.length>3&&(a+="."+eH(e[1])+eH(e[2])+eH(e[3]),t=eK("avc1"===l?"dva1":"dvav",r));break}case"mp4a":{let e=eB(i,[s])[0],t=eB(e.subarray(28),["esds"])[0];if(t&&t.length>7){let e=4;if(3!==t[e++])break;e=eV(t,e)+2;let i=t[e++];if(128&i&&(e+=2),64&i&&(e+=t[e++]),4!==t[e++])break;e=eV(t,e);let r=t[e++];if(64===r)a+="."+eH(r);else break;if(e+=12,5!==t[e++])break;e=eV(t,e);let s=t[e++],n=(248&s)>>3;31===n&&(n+=1+((7&s)<<3)+((224&t[e])>>5)),a+="."+n}break}case"hvc1":case"hev1":{let e=eB(r,["hvcC"])[0];if(e&&e.length>12){let t=e[1],i=["","A","B","C"][t>>6],r=eO(e,2),s=e[12],n=e.subarray(6,12);a+="."+i+(31&t)+"."+(function(e){let t=0;for(let i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0})(r).toString(16).toUpperCase()+"."+((32&t)>>5?"H":"L")+s;let l="";for(let e=n.length;e--;){let t=n[e];(t||l)&&(l="."+t.toString(16).toUpperCase()+l)}a+=l}t=eK("hev1"==l?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=eK(a,r)||a;break;case"vp09":{let e=eB(r,["vpcC"])[0];if(e&&e.length>6){let t=e[4],i=e[5],r=e[6]>>4&15;a+="."+eY(t)+"."+eY(i)+"."+eY(r)}break}case"av01":{let e=eB(r,["av1C"])[0];if(e&&e.length>2){let i=e[1]>>>5,s=31&e[1],n=e[2]>>>7?"H":"M",l=(64&e[2])>>6,o=(32&e[2])>>5,h=(16&e[2])>>4,d=(8&e[2])>>3,u=(4&e[2])>>2,f=3&e[2];a+="."+i+"."+eY(s)+n+"."+eY(2===i&&l?o?12:10:l?10:8)+"."+h+"."+d+u+f+"."+eY(1)+"."+eY(1)+"."+eY(1)+".0",t=eK("dav1",r)}}}return{codec:a,encrypted:n,supplemental:t}}(eB(r,["mdia","minf","stbl","stsd"])[0]);a?(t[i]={timescale:s,type:a,stsd:l},t[a]=H({timescale:s,id:i},l)):t[i]={timescale:s,type:e,stsd:l}}}}}return eB(e,["moov","mvex","trex"]).forEach(e=>{let i=t[eO(e,4)];i&&(i.default={duration:eO(e,12),sampleSize:eO(e,16),flags:eO(e,20)})}),t}function eK(e,t){let i=eB(t,["dvvC"]),r=i.length?i[0]:eB(t,["dvcC"])[0];if(r){let t=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return e+"."+eY(t)+"."+eY(i)}}function eV(e,t){let i=t+5;for(;128&e[t++]&&t<i;);return t}function eH(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function eY(e){return(e<10?"0":"")+e}function eW(e,t){eB(e,["moov","trak"]).forEach(e=>{let i=eB(e,["mdia","minf","stbl","stsd"])[0];if(!i)return;let r=i.subarray(8),s=eB(r,["enca"]),a=s.length>0;a||(s=eB(r,["encv"])),s.forEach(e=>{eB(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{let i=ej(e);i&&t(i,a)})})})}function ej(e){let t=eB(e,["schm"])[0];if(t){let i=ek(t.subarray(4,8));if("cbcs"===i||"cenc"===i){let t=eB(e,["schi","tenc"])[0];if(t)return t}}}function eq(e,t,i,r,s){let a={},n=!1,l=function(e){let t=e.byteLength,i=[];for(let r=0;r<t;){let s=r+8<=t,a=r+4<=t?16777216*e[r]+(e[r+1]<<16|e[r+2]<<8|e[r+3]):eO(e,r),n=a>1?r+a:t;if(s&&109===e[r+4]&&111===e[r+5]&&111===e[r+6]&&102===e[r+7]){let s=Math.min(n,t);for(let t=r+8;t<s;){let a=t+8<=s,n=t+4<=s?16777216*e[t]+(e[t+1]<<16|e[t+2]<<8|e[t+3]):eO(e,t),l=n>1?t+n:s;if(a&&116===e[t+4]&&114===e[t+5]&&97===e[t+6]&&102===e[t+7]){let a,n;let o=Math.min(l,s),h=[];for(let i=t+8;i<o;){let t=i+8<=o,r=i+4<=o?16777216*e[i]+(e[i+1]<<16|e[i+2]<<8|e[i+3]):eO(e,i),s=r>1?i+r:o;if(t&&116===e[i+4]){let t=Math.min(s,o);102===e[i+5]&&104===e[i+6]&&100===e[i+7]?n||(n=e.subarray(i+8,t)):102===e[i+5]&&100===e[i+6]&&116===e[i+7]?a||(a=e.subarray(i+8,t)):114===e[i+5]&&117===e[i+6]&&110===e[i+7]&&h.push(e.subarray(i+8,t))}i=s}i.push({moofOffset:e.byteOffset+r,tfdt:a,tfhd:n,truns:h})}t=l}}r=n}return i}(e),o=e.byteLength;for(let f=0;f<l.length;f++){let c,g;
1let{moofOffset:m,tfdt:p,tfhd:E,truns:v}=l[f],y=eO(E,4),T=t[y];if(!T)continue;let S=a[y]||(a[y]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:T.timescale,type:T.type});if(p){let e=p[0];c=eO(p,4),1===e&&(4294967295===c?i.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(c*=4294967296,c+=eO(p,8))),d(c)&&(!d(S.start)||c<S.start)&&(S.start=c),s&&d(c)&&(s.timeOffset=c/s.timescale)}let A=(null==s?void 0:s.trackId)===y&&T.type===F.VIDEO,I=T.default,L=16777215&eO(E,0),R=(null==I?void 0:I.duration)||0,b=(null==I?void 0:I.sampleSize)||0,D=8;1&L&&(D+=8),2&L&&(D+=4),8&L&&(R=eO(E,D),g=E.byteOffset-e.byteOffset+D,D+=4),16&L&&(b=eO(E,D));let k=0,P=(1&L)!=0,_=!P&&(131072&L)!=0;P?k=4294967296*eO(E,8)+eO(E,12):_&&(k=m);let C=c||0,O=0,M=R;for(let t=0;t<v.length;t++){let i,a,n;let l=v[t],f=eO(l,4),c=S.sampleCount;S.sampleCount+=f;let m=1&l[3],p=0,E=4&l[3],y=1&l[2],T=2&l[2],I=4&l[2],L=8&l[2],D=8;m&&(p=eF(l,D),D+=4),E&&(1&l[D+1]||void 0!==S.keyFrameIndex||(S.keyFrameIndex=c),D+=4);let P=k+p;if(!r&&0===l[1]&&6===l[2]&&1===l[3]){var h,u;let t=C,i=P,r=D,a=-1,n=0,c=0,g=null!=(h=null==s?void 0:s.timeOffset)?h:0,m=R/(null!=(u=null==s?void 0:s.timescale)?u:1),p=(null==s?void 0:s.isHEVCFlavor)===!0,E=p?2:1;for(let t=0;t<f;t++){let i=0===l[D]?l[D+1]<<16|l[D+2]<<8|l[D+3]:eO(l,D),r=-1===a&&void 0===S.keyFrameIndex&&(1&l[D+5])==0;D+=8;let o=P+i;if(A){if(i>0){let t=P;do{let i=0===e[t]?e[t+1]<<16|e[t+2]<<8|e[t+3]:eO(e,t),r=e[t+=4],a=p?r>>1&63:31&r;(p?39===a||40===a:6===a)&&eZ(e.subarray(t,t+i),E,g,s.samples),t+=i}while(t<o)}g+=m}P=o,r&&(a=t,n=P)}if(P<=o)c=f;else{let e=i,t=r;for(let i=0;i<f&&!((e+=0===l[t]?l[t+1]<<16|l[t+2]<<8|l[t+3]:eO(l,t))>o);i++)c=i+1,t+=8}if(A&&(s.timeOffset=g),-1!==a&&n<=o&&void 0===S.keyFrameIndex&&(S.keyFrameIndex=a,S.keyFrameStart=t+a*R),c){(!d(S.ptsMin)||t<S.ptsMin)&&(S.ptsMin=t);let e=t+c*R;(!d(S.ptsMax)||e>S.ptsMax)&&(S.ptsMax=e)}let v=R*f;C=t+v,O+=v;continue}r&&(a={sampleOffset:P,samples:i=[],defaultSampleDurationOffset:g},P<=o&&S.trun.push(a));for(let t=0;t<f;t++){let h,u,f;y?(r&&(h=l.byteOffset-e.byteOffset+D),M=eO(l,D),D+=4):M=R,T?(n=eO(l,D),D+=4):n=b,I&&(f=1&l[D+1]?1:0,r&&(u={isNonSync:f,dependsOn:(3&l[D])==1?1:2}),D+=4);let c=0;if(L&&(c=0===l[0]?eO(l,D):eF(l,D),D+=4),A){let t=P,i=0;for(;i<n;){let r=eO(e,t);t+=4,eQ(s.isHEVCFlavor,e[t])&&eZ(e.subarray(t,t+r),s.isHEVCFlavor?2:1,s.timeOffset+c/s.timescale,s.samples),t+=r,i+=r+4}s.timeOffset+=M/s.timescale}if((P+=n)<=o){a&&void 0!==h&&(a.lastSampleDurationOffset=h),0===f&&void 0===S.keyFrameIndex&&(S.keyFrameIndex=t,S.keyFrameStart=C);let e=C+c;(!d(S.ptsMin)||e<S.ptsMin)&&(S.ptsMin=e),(!d(S.ptsMax)||e+M>S.ptsMax)&&(S.ptsMax=e+M),i&&(i[t]={cts:c,duration:M,flags:u,size:n})}C+=M,O+=M}!O&&R&&(O+=R*f)}S.duration+=O,S.duration&&(n=!0)}if(!n){let t=1/0,i=0,r=eB(e,["sidx"]);for(let e=0;e<r.length;e++){let s=function(e){let t=[],i=e[0],r=8,s=eO(e,8);r+=4;let a=0,n=0;0===i?(a=eO(e,r),n=eO(e,r+4),r+=8):(a=eM(e,r),n=eM(e,r+8),r+=16),r+=2;let l=e.length+n,o=eC(e,r);r+=2;for(let i=0;i<o;i++){let i=r,a=eO(e,i);i+=4;let n=2147483647&a;if(1==(2147483648&a)>>>31)return eo.warn("SIDX has hierarchical references (not supported)"),null;let o=eO(e,i);i+=4,t.push({referenceSize:n,subsegmentDuration:o,info:{duration:o/s,start:l,end:l+n-1}}),l+=n,i+=4,r=i}return{earliestPresentationTime:a,timescale:s,version:i,referencesCount:o,references:t}}(r[e]);if(null!=s&&s.references){t=Math.min(t,s.earliestPresentationTime/s.timescale);let e=s.references.reduce((e,t)=>e+t.info.duration||0,0);i=Math.max(i,e+s.earliestPresentationTime/s.timescale)}}i&&d(i)&&Object.keys(a).forEach(e=>{a[e].duration||(a[e].duration=i*a[e].timescale-a[e].start)})}return a}function eX(e,t){let i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function ez(e){if(!e)return!1;let t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function eQ(e,t){if(!e)return 6==(31&t);{let e=t>>1&63;return 39===e||40===e}}function eZ(e,t,i,s){let a;let n=eJ(e);a=0+t;let l=0,o=0,h=0;for(;a<n.length;){l=0;do{if(a>=n.length)break;l+=h=n[a++]}while(255===h);o=0;do{if(a>=n.length)break;o+=h=n[a++]}while(255===h);let e=n.length-a,t=a;if(o<e)a+=o;else if(o>e){eo.error(`Malformed SEI payload. ${o} is too small, only ${e} bytes left to parse.`);break}if(4===l){if(181===n[t++]){let e=eC(n,t);if(t+=2,49===e){let e=eO(n,t);if(t+=4,1195456820===e){let e=n[t++];if(3===e){let r=n[t++],a=31&r,o=64&r,h=o?2+3*a:0,d=new Uint8Array(h);if(o){d[0]=r;for(let e=1;e<h;e++)d[e]=n[t++]}s.push({type:e,payloadType:l,pts:i,bytes:d})}}}}}else if(5===l&&o>16){let e=[];for(let i=0;i<16;i++){let r=n[t++].toString(16);e.push(1==r.length?"0"+r:r),(3===i||5===i||7===i||9===i)&&e.push("-")}let a=o-16,h=new Uint8Array(a);for(let e=0;e<a;e++)h[e]=n[t++];s.push({payloadType:l,pts:i,uuid:e.join(""),userData:"undefined"==typeof TextDecoder?eS(h):(r||(r=new TextDecoder("utf-8"))).decode(h).replace(/\0/g,""),userDataBytes:h})}}}function eJ(e){let t;let i=e.byteLength,r=e.indexOf(3,3);for(;-1!==r;)0===e[r-1]&&0===e[r-2]&&(t||(t=[])).push(r),r=e.indexOf(3,r+1);if(!t)return e;let s=i-t.length,a=new Uint8Array(s),n=0,l=0;for(let i=0;i<s;l++,i++)l===t[n]&&(l++,n++),a[i]=e[l];return a}function e0(e){let t=[];if(e instanceof ArrayBuffer){let i=e.byteLength,r=0;for(;r+32<i;){let i=function(e){let t=e.getUint32(0),i=e.byteOffset,r=e.byteLength;if(r<t)return{offset:i,size:r};if(1886614376!==e.getUint32(4))return{offset:i,size:t};let s=e.getUint32(8)>>>24;if(0!==s&&1!==s)return{offset:i,size:t};let a=e.buffer,n=eR(new Uint8Array(a,i+12,16)),l=null,o=null,h=0;if(0===s)h=28;else{let s=e.getUint32(28);if(!s||r<32+16*s)return{offset:i,size:t};l=[];for(let e=0;e<s;e++)l.push(new Uint8Array(a,i+32+16*e,16));h=32+16*s}if(!h)return{offset:i,size:t};let d=e.getUint32(h);return t-32<d?{offset:i,size:t}:(o=new Uint8Array(a,i+h+4,d),0===s&&(l=function(e){let t=[];for(let i=0;i<e.length;){let r=e[i++],s=7&r;if(0===s){for(;128&e[i++];);continue}if(2!==s){i+=1===s?8:4;continue}let a=0;for(let t=0,r=128;128&r;t+=7)a|=(127&(r=e[i++]))<<t;if(r>>3==2){if(32===a){let r=new Uint8Array(16);for(let t=0;t<16;t++)r[t]=parseInt(String.fromCharCode(e[i+2*t],e[i+2*t+1]),16);t.push(r)}else 16===a&&t.push(e.subarray(i,i+16))}i+=a}return t}(o)),{version:s,systemId:n,kids:l,data:o,offset:i,size:t})}(new DataView(e,r));t.push(i),r+=i.size}}return t}let e1=e4("userAgent"),e2=e4("vendor");function e4(e){try{return navigator[e]||""}catch(e){}return""}function e3(){if(void 0===s){let e=e1.match(/Chrome\/(\d+)/i);s=e?parseInt(e[1]):0}return s}function e8(){return/\(Windows.+Firefox\//i.test(e1)}let e5={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv
160:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function e6(e,t){let i=e5[t];return!!i&&!!i[e.slice(0,4)]}function e9(e,t,i=!0){return!e.split(",").some(e=>!e7(e,t,i))}function e7(e,t,i=!0){var r;let s=eh(i);return null!=(r=null==s?void 0:s.isTypeSupported(te(e,t)))&&r}function te(e,t){return`${t}/mp4;codecs=${e}`}function tt(e){if(e){let t=e.substring(0,4);return e5.video[t]}return 2}function ti(e){let t=e8();return e.split(",").reduce((e,i)=>{let r=t&&ez(i)?9:e5.video[i];return r?(2*r+e)/(e?3:2):(e5.audio[i]+e)/(e?2:1)},0)}let tr={},ts=/flac|opus|mp4a\.40\.34/i;function ta(e,t=!0){return e.replace(ts,e=>(function(e,t=!0){if(tr[e])return tr[e];let i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let s=0;s<i.length;s++){var r;if(e7(i[s],"audio",t))return tr[e]=i[s],i[s];if("mp3"===i[s]&&null!=(r=eh(t))&&r.isTypeSupported("audio/mpeg"))return""}return e})(e.toLowerCase(),t))}function tn(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(tl(e,"audio")||tl(e,"video")))return e;if(t){let i=t.split(",");if(i.length>1){if(e){for(let t=i.length;t--;)if(i[t].substring(0,4)===e.substring(0,4))return i[t]}return i[0]}}return t||e}function tl(e,t){return e6(e,t)&&e7(e,t)}function to(e){let t=eh(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function th(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}let td={supported:!1,smooth:!1,powerEfficient:!1},tu={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function tf(e,t){return{supported:!1,configurations:t,decodingInfoResults:[td],error:e}}function tc(e,t,i,r={}){let s=e.videoCodec;if(!s&&!e.audioCodec||!i)return Promise.resolve(tu);let a=[],n=function(e){var t;let i=null==(t=e.videoCodec)?void 0:t.split(","),r=tm(e),s=e.width||640,a=e.height||480,n=e.frameRate||30,l=e.videoRange.toLowerCase();return i?i.map(e=>{let t={contentType:te(function(e){if(e.startsWith("av01.")){let t=e.split("."),i=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=i[e-4];return t.join(".")}return e}(e),"video"),width:s,height:a,bitrate:r,framerate:n};return"sdr"!==l&&(t.transferFunction=l),t}):[]}(e),l=n.length,o=function(e,t,i){var r;let s=null==(r=e.audioCodec)?void 0:r.split(","),a=tm(e);return s&&e.audioGroups?e.audioGroups.reduce((e,r)=>{var n;let l=r?null==(n=t.groups[r])?void 0:n.tracks:null;return l?l.reduce((e,t)=>{if(t.groupId===r){let r=parseFloat(t.channels||"");s.forEach(t=>{let s={contentType:te(t,"audio"),bitrate:i?tg(t,a):a};r&&(s.channels=""+r),e.push(s)})}return e},e):e},[]):[]}(e,t,l>0),h=o.length;for(let e=l||1*h||1;e--;){let t={type:"media-source"};if(l&&(t.video=n[e%l]),h){t.audio=o[e%h];let i=t.audio.bitrate;t.video&&i&&(t.video.bitrate-=i)}a.push(t)}if(s){let e=navigator.userAgent;if(s.split(",").some(e=>ez(e))&&e8())return Promise.resolve(tf(Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),a))}return Promise.all(a.map(e=>{let t=function(e){let t="",{audio:i,video:r}=e;if(r){let e=th(r.contentType);t+=`${e}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(i){let e=th(i.contentType);t+=`${r?"_":""}${e}_c${i.channels}`}return t}(e);return r[t]||(r[t]=i.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:a,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:a,decodingInfoResults:[],error:e}))}function tg(e,t){if(t<=1)return 1;let i=128e3;return"ec-3"===e?i=768e3:"ac-3"===e&&(i=64e4),Math.min(t/2,i)}function tm(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}function tp(e,t,i){let r=encodeURIComponent(t),s=`${r}=${encodeURIComponent(i)}`,a=!1,n=[];e.search.substring(1).split("&").forEach(e=>{e===r||e.startsWith(r+"=")?a||(n.push(s),a=!0):e&&n.push(e)}),a||n.push(s),e.search=n.join("&")}let tE=["NONE","TYPE-0","TYPE-1",null],tv=["SDR","PQ","HLG"];var ty={No:"",Yes:"YES",v2:"v2"};function tT(e){let{canSkipUntil:t,canSkipDateRanges:i,age:r}=e;return t&&r<t/2?i?ty.v2:ty.Yes:ty.No}class tS{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){let t=new self.URL(e);return void 0!==this.msn&&tp(t,"_HLS_msn",this.msn.toString()),void 0!==this.part&&tp(t,"_HLS_part",this.part.toString()),this.skip&&tp(t,"_HLS_skip",this.skip),t.href}}class tA{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.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=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,"imageCodec"in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}
1"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return tI(this._audioGroups,e)}hasSubtitleGroup(e){return tI(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function tI(e,t){return!!t&&!!e&&-1!==e.indexOf(t)}let tL=e=>{let t=new WeakSet;return(i,r)=>{if(e&&(r=e(i,r)),"object"==typeof r&&null!==r){if(t.has(r))return;t.add(r)}return r}},tR=(e,t)=>JSON.stringify(e,tL(t));function tb(e,t){eo.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function tD(e){return e.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);let r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function tk(e){if(!e)return e;let{lang:t,assocLang:i,characteristics:r,channels:s,audioCodec:a}=e;return{lang:t,assocLang:i,characteristics:r,channels:s,audioCodec:a}}function tP(e,t,i){if("attrs"in e){let i=t.indexOf(e);if(-1!==i)return i}for(let r=0;r<t.length;r++)if(t_(e,t[r],i))return r;return -1}function t_(e,t,i){let{groupId:r,name:s,lang:a,assocLang:n,default:l}=e,o=e.forced;return(void 0===r||t.groupId===r)&&(void 0===s||t.name===s)&&(void 0===a||function(e,t="--"){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}(a,t.lang))&&(void 0===a||t.assocLang===n)&&(void 0===l||t.default===l)&&(void 0===o||t.forced===o)&&(!("characteristics"in e)||function(e,t=""){let i=e.split(","),r=t.split(",");return i.length===r.length&&!i.some(e=>-1===r.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function tC(e,t){let{audioCodec:i,channels:r}=e;return(void 0===i||(t.audioCodec||"").substring(0,4)===i.substring(0,4))&&(void 0===r||r===(t.channels||"2"))}function tO(e,t,i){for(let r=t;r>-1;r--)if(i(e[r]))return r;for(let r=t+1;r<e.length;r++)if(i(e[r]))return r;return -1}function tM(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}function tw(e,t){return!t||-1!==t.indexOf(e)}function tF(e,t){if(t||e){let i=K({},t);return e&&(e.videoCodec&&(i.videoCodec=e.videoCodec),e.videoRange&&(i.allowedVideoRanges=[e.videoRange])),i}}class tx extends er{constructor(e){super("abr",e.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.co
1decTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;let i;let{fragCurrent:r,partCurrent:s,hls:a}=this;if(!a)return;let{autoLevelEnabled:n,media:l}=a;if(!r||!l)return;let o=performance.now(),h=s?s.stats:r.stats,u=s?s.duration:r.duration,f=o-h.loading.start,c=a.minAutoLevel,g=r.level,p=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=c){this.clearTimer(),this._nextAutoLevel=-1;return}if(!n)return;let E=p>-1&&p!==g,v=!!e||E;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;let y=a.mainForwardBufferInfo;if(!v&&null===y)return;let T=this.bwEstimator.getEstimateTTFB(),S=Math.abs(l.playbackRate);if(f<=Math.max(T,u/(2*S)*1e3))return;let A=y?y.len/S:0,I=h.loading.first?h.loading.first-h.loading.start:-1,L=h.loaded&&I>-1,R=this.getBwEstimate(),b=a.levels,D=b[g],k=Math.max(h.loaded,Math.round(u*(r.bitrate||D.averageBitrate)/8)),P=L?f-I:f;P<1&&L&&(P=Math.min(f,8*h.loaded/R));let _=L?1e3*h.loaded/P:0,C=T/1e3,O=_?(k-h.loaded)/_:8*k/R+C;if(O<=A)return;let M=_?8*_:R,w=(null==(t=(null==e?void 0:e.details)||a.latestLevelDetails)?void 0:t.live)===!0,F=a.config.abrBandWidthUpFactor,x=Number.POSITIVE_INFINITY;for(i=g-1;i>c;i--){let e=b[i].maxBitrate,t=!b[i].details||w;if((x=this.getTimeToLoadFrag(C,M,u*e,t))<Math.min(A,u+C))break}if(x>=O||x>10*u)return;L?this.bwEstimator.sample(f-Math.min(T,I),h.loaded):this.bwEstimator.sampleTTFB(f);let N=b[i].maxBitrate;this.getBwEstimate()*F>N&&(this.firstAutoFloor=Math.min(i,a.firstLevel),this.resetEstimator(N));let $=this.findBestLevel(N,c,i,0,A,1,1);$>-1&&(i=$),this.warn(`Fragment ${r.sn}${s?" part "+s.index:""} of level ${g} is loading too slowly; 2 Fragment duration: ${r.duration.toFixed(3)} 3 Time to underbuffer: ${A.toFixed(3)} s 4 Estimated load time for current fragment: ${O.toFixed(3)} s 5 Estimated load time for down switch fragment: ${x.toFixed(3)} s 6 TTFB estimate: ${0|I} ms 7 Current BW estimate: ${d(R)?0|R:"Unknown"} bps 8 New BW estimate: ${0|this.getBwEstimate()} bps 9 Switching to level ${i} @ ${0|N} bps`),a.nextLoadLevel=a.nextAutoLevel=i,this.clearTimer();let U=()=>{this.clearTimer();let e=this.hls;if(this.fragCurrent===r&&e.loadLevel===i&&i>0){let t=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${i>0?"and switching down":""} 10 Fragment duration: ${r.duration.toFixed(3)} s 11 Time to underbuffer: ${t.toFixed(3)} s`),r.abortRequests(),this.fragCurrent=this.partCurrent=null,i>c){let r=this.findBestLevel(e.levels[c].bitrate,c,i,0,t,1,1);-1===r&&(r=c),e.nextLoadLevel=e.nextAutoLevel=r,this.firstAutoFloor=Math.min(r,e.firstLevel),this.resetEstimator(e.levels[r].bitrate)}}};E||O>2*x?U():this.timer=self.setInterval(U,1e3*x),a.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:s,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){this.hls&&(e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){let e=this.hls.config;return new ei(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let e=this.hls;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(m.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){let i=t.frag;
11if(!this.ignoreFragment(i)){if(!i.bitrateTest){var r;this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case g.BUFFER_ADD_CODEC_ERROR:case g.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case g.FRAG_LOAD_TIMEOUT:{let e=t.frag,{fragCurrent:i,partCurrent:r}=this;if(e&&U(e,i)){let t=performance.now(),i=r?r.stats:e.stats,s=t-i.loading.start,a=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&a>-1){let e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(e,a),i.loaded)}else this.bwEstimator.sampleTTFB(s)}}}}getTimeToLoadFrag(e,t,i,r){let s=r?e+this.lastLevelLoadSec:0;return e+i/t+s}onLevelLoaded(e,t){let i=this.hls.config,{loading:r}=t.stats,s=r.end-r.first;d(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var i;let{frag:r,part:s}=t,a=s?s.stats:r.stats;if(r.type===w.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(i=this.hls)&&i.config.abrMaxWithRealBitrate){let e=s?s.duration:r.duration,t=this.hls.levels[r.level],i=(t.loaded?t.loaded.bytes:0)+a.loaded,n=(t.loaded?t.loaded.duration:0)+e;t.loaded={bytes:i,duration:n},t.realBitrate=Math.round(8*i/n)}if(r.bitrateTest){let e={stats:a,frag:r,part:s,id:r.type};this.onFragBuffered(m.FRAG_BUFFERED,e),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}onFragBuffered(e,t){let{frag:i,part:r}=t,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(s.aborted||this.ignoreFragment(i))return;let a=((i.bitrate||0)>=1e5?s.parsing.end:s.loading.end)-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==w.MAIN||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{hls:e}=this;if(!e)return 0;let{maxAutoLevel:t,minAutoLevel:i}=e,r=this.getBwEstimate(),s=this.getStarvationDelay(),a=e.config.maxStarvationDelay,n=this.findBestLevel(r,i,t,s/2,a,1,1);if(n>-1)return n;let l=e.firstLevel,o=Math.min(Math.max(l,i),t,-1===this.firstAutoFloor?1/0:this.firstAutoFloor);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return -1;let e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(-1!==e&&(!t||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){let t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}
11_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(!i)return -1;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:r,config:s,minAutoLevel:a}=i,n=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),o=this.getStarvationDelay(),h=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(o){let e=this.findBestLevel(l,a,r,o,0,h,d);if(e>=0)return this.rebufferNotice=-1,e}let u=n?Math.min(n,s.maxStarvationDelay):s.maxStarvationDelay;if(!o){let e=this.bitrateTestDelay;e&&(u=(n?Math.min(n,s.maxLoadingDelay):s.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=d=1)}let f=this.findBestLevel(l,a,r,o,u,h,d);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${o?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let c=i.levels[a],g=i.loadLevelObj;return g&&(null==c?void 0:c.bitrate)<g.bitrate?a:i.loadLevel}getStarvationDelay(){let e=this.hls,t=null==e?void 0:e.media;if(!t)return 1/0;let i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,i,r,s,a,n){var l;let o;let{hls:h,lastLoadedFragLevel:u,fragCurrent:f,partCurrent:c}=this;if(!h)return -1;let g=r+s,m=-1===u?h.firstLevel:u,{levels:p,allAudioTracks:E,loadLevel:v,latestLevelDetails:y,config:T}=h;if(1===p.length)return 0;let S=p[m],A=!!(null!=y&&y.live),I=-1===v||-1===u,L="SDR",R=(null==S?void 0:S.frameRate)||0,{audioPreference:b,videoPreference:D}=T,k=this.audioTracksByGroup||(this.audioTracksByGroup=tD(E)),P=-1;if(I){if(-1!==this.firstSelection)return this.firstSelection;let r=function(e,t,i,r,s){let a=Object.keys(e),n=null==r?void 0:r.channels,l=null==r?void 0:r.audioCodec,o=null==s?void 0:s.videoCodec,h=n&&2===parseInt(n),u=!1,f=!1,c=1/0,g=1/0,m=1/0,p=1/0,E=0,v=[],{preferHDR:y,allowedVideoRanges:T}=function(e,t){let i=!1,r=[];if(e&&(i="SDR"!==e,r=[e]),t){let e="SDR"!==(r=t.allowedVideoRanges||tv.slice(0)).join("")&&!t.videoCodec;(i=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){let e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}(t,s);for(let t=a.length;t--;){let i=e[a[t]];u||(u=i.channels[2]>0),c=Math.min(c,i.minHeight),g=Math.min(g,i.minFramerate),m=Math.min(m,i.minBitrate),T.filter(e=>i.videoRanges[e]>0).length>0&&(f=!0)}c=d(c)?c:0,g=d(g)?g:0;let S=Math.max(1080,c),A=Math.max(30,g);i=Math.max(m=d(m)?m:i,i),f||(t=void 0);let I=a.length>1;return{codecSet:a.reduce((t,r)=>{let s=e[r];if(r===t)return t;if(v=f?T.filter(e=>s.videoRanges[e]>0):[],I){if(s.minBitrate>i)return tb(r,`min bitrate of ${s.minBitrate} > current estimate of ${i}`),t;if(!s.hasDefaultAudio)return tb(r,"no renditions with default or auto-select sound found"),t;if(l&&r.indexOf(l.substring(0,4))%5!=0)return tb(r,`audio codec preference "${l}" not found`),t;if(n&&!h){if(!s.channels[n])return tb(r,`no renditions with ${n} channel sound found (channels options: ${Object.keys(s.channels)})`),t}else if((!l||h)&&u&&0===s.channels["2"])return tb(r,"no renditions with stereo sound found"),t;if(s.minHeight>S)return tb(r,`min resolution of ${s.minHeight} > maximum of ${S}`),t;if(s.minFramerate>A)return tb(r,`min framerate of ${s.minFramerate} > maximum of ${A}`),t;if(!v.some(e=>s.videoRanges[e]>0))return tb(r,`no variants with VIDEO-RANGE of ${tR(v)} found`),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return tb(r,`video codec preference "${o}" not found`),t;if(s.maxScore<E)return tb(r,`max score of ${s.maxScore} < selected max of ${E}`),t}return t&&(ti(r)>=ti(t)||s.fragmentError>e[t].fragmentError)?t:(p=s.minIndex,E=s.maxScore,r)},void 0),videoRanges:v,preferHDR:y,minFramerate:g,minBitrate:m,minIndex:p}}(this.codecTiers||(this.codecTiers=p.slice(t,i+1).reduce((e,t,i)=>{if(!t.codecSet)return e;let r=t.audioGroups,s=e[t.codecSet];s||(e[t.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}
11),s.minBitrate=Math.min(s.minBitrate,t.bitrate);let a=Math.min(t.height,t.width);return s.minHeight=Math.min(s.minHeight,a),s.minFramerate=Math.min(s.minFramerate,t.frameRate),s.minIndex=Math.min(s.minIndex,i),s.maxScore=Math.max(s.maxScore,t.score),s.fragmentError+=t.fragmentError,s.videoRanges[t.videoRange]=(s.videoRanges[t.videoRange]||0)+1,r&&r.forEach(e=>{if(!e)return;let t=k.groups[e];t&&(s.hasDefaultAudio=s.hasDefaultAudio||k.hasDefaultAudio?t.hasDefault:t.hasAutoSelect||!k.hasDefaultAudio&&!k.hasAutoSelectAudio,Object.keys(t.channels).forEach(e=>{s.channels[e]=(s.channels[e]||0)+t.channels[e]}))}),e},{})),L,e,b,D),{codecSet:s,videoRanges:a,minFramerate:n,minBitrate:l,minIndex:h,preferHDR:u}=r;P=h,o=s,L=u?a[a.length-1]:a[0],R=n,e=Math.max(e,l),this.log(`picked start tier ${tR(r)}`)}else o=null==S?void 0:S.codecSet,L=null==S?void 0:S.videoRange;let _=c?c.duration:f?f.duration:0,C=this.bwEstimator.getEstimateTTFB()/1e3,O=[];for(let h=i;h>=t;h--){let t;let f=p[h],E=h>m;if(!f)continue;if(T.useMediaCapabilities&&!f.supportedResult&&!f.supportedPromise){let t=navigator.mediaCapabilities;"function"==typeof(null==t?void 0:t.decodingInfo)&&function(e,t,i,r,s,a){let n=e.videoCodec,l=e.audioCodec?e.audioGroups:null,o=null==a?void 0:a.audioCodec,h=null==a?void 0:a.channels,u=h?parseInt(h):o?1/0:2,f=null;if(null!=l&&l.length)try{f=1===l.length&&l[0]?t.groups[l[0]].channels:l.reduce((e,i)=>{if(i){let r=t.groups[i];if(!r)throw Error(`Audio track group ${i} not found`);Object.keys(r.channels).forEach(t=>{e[t]=(e[t]||0)+r.channels[t]})}return e},{2:0})}catch(e){return!0}return void 0!==n&&(n.split(",").some(e=>ez(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(s,8e6))||!!f&&d(u)&&Object.keys(f).some(e=>parseInt(e)>u)}(f,k,L,R,e,b)?(f.supportedPromise=tc(f,k,t,this.supportedCache),f.supportedPromise.then(e=>{if(!this.hls)return;f.supportedResult=e;let t=this.hls.levels,i=t.indexOf(f);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${i} ${tR(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${i} not smooth or powerEfficient: ${tR(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${tR(e)}`),i>-1&&t.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):f.supportedResult=tu}if((o&&f.codecSet!==o||L&&f.videoRange!==L||E&&R>f.frameRate||!E&&R>0&&R<f.frameRate||null!=(l=f.supportedResult)&&null!=(l=l.decodingInfoResults)&&l.some(e=>!1===e.smooth))&&(!I||h!==P)){O.push(h);continue}let y=f.details,S=(c?null==y?void 0:y.partTarget:null==y?void 0:y.averagetargetduration)||_||1;t=E?n*e:a*e;let D=_&&r>=2*_&&0===s?f.averageBitrate:f.maxBitrate,M=this.getTimeToLoadFrag(C,t,D*S,!y||y.live);if(t>=D&&(h===u||0===f.loadError&&0===f.fragmentError||ee(f,T.errorPenaltyExpireMs))&&(M<=C||!d(M)||A&&!this.bitrateTestDelay||M<g)){let e=this.forcedAutoLevel;return h!==v&&(-1===e||e!==v)&&(O.length&&this.trace(`Skipped level(s) ${O.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${p[O[0]].codecs}" ${p[O[0]].videoRange}; not compatible with "${o}" ${L}`),this.info(`switch candidate:${m}->${h} adjustedbw(${Math.round(t)})-bitrate=${Math.round(t-D)} ttfb:${C.toFixed(1)} avgDuration:${S.toFixed(1)} maxFetchDuration:${g.toFixed(1)} fetchDuration:${M.toFixed(1)} firstSelection:${I} codecSet:${f.codecSet} videoRange:${f.videoRange} hls.loadLevel:${v}`)),I&&(this.firstSelection=h),h}}return -1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){if(!this.hls)return -1;let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}}let tN={search:function(e,t){let i=0,r=e.length-1,s=null,a=null;for(;i<=r;){let n=t(a=e[s=(i+r)/2|0]);if(n>0)i=s+1;else{if(!(n<0))return a;r=s-1}}return null}};function t$(e,t,i=0,r=0,s=.005){let a=null;if(e){a=t[1+e.sn-t[0].sn]||null;let r=e.endDTS-i;r>0&&r<15e-7&&(i+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===tU(i,r,a)||function(e,t,i){if((null==t?void 0:t.start)===0&&t.level<e.level&&(t.endPTS||0)>0){let r=t.tagList.reduce((e,t)=>
11("INF"===t[0]&&(e+=parseFloat(t[1])),e),i);return e.start<=r}return!1}(a,e,Math.min(s,r))))return a;let n=tN.search(t,tU.bind(null,i,r));return n&&(n!==e||!a)?n:a}function tU(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;let r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function tB(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){let r,s=e.fragments,{fragmentHint:a}=e;return a&&(s=s.concat(a)),tN.search(s,e=>e.cc<t?1:e.cc>t?-1:(r=e,e.end<=i)?1:e.start>i?-1:0),r||null}return null}function tG(e,t,i){return i&&t===e.endSN&&e.fragmentHint?e.fragmentHint:e.fragments[1+t-e.startSN]||null}var tK={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},tV={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};class tH extends er{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(m.ERROR,this.onError,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(m.ERROR,this.onError,this),e.off(m.ERROR,this.onErrorOut,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(null==e?void 0:e.type)===w.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,i=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===i?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if(null!=(i=e.details)&&i.hasKey(t))return!0;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(e=>r.indexOf(e.groupId)>=0).some(e=>{var i;return null==(i=e.details)?void 0:i.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,r;if(t.fatal)return;let s=this.hls,a=t.context;switch(t.details){case g.FRAG_LOAD_ERROR:case g.FRAG_LOAD_TIMEOUT:case g.KEY_LOAD_ERROR:case g.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case g.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap){t.errorAction=tj();return}case g.FRAG_GAP:case g.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=tK.SendAlternateToPenaltyBox;return;case g.PLAYLIST_UNCHANGED_ERROR:case g.LEVEL_EMPTY_ERROR:case g.LEVEL_PARSING_ERROR:{let e=t.parent===w.MAIN?t.level:s.loadLevel;t.details===g.LEVEL_EMPTY_ERROR&&null!=(r=t.context)&&null!=(r=r.levelDetails)&&r.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case g.LEVEL_LOAD_ERROR:case g.LEVEL_LOAD_TIMEOUT:"number"==typeof(null==a?void 0:a.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.level));return;case g.AUDIO_TRACK_LOAD_ERROR:case g.AUDIO_TRACK_LOAD_TIMEOUT:case g.SUBTITLE_LOAD_ERROR:case g.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){let e=s.loadLevelObj;e&&(a.type===M.AUDIO_TRACK&&e.hasAudioGroup(a.groupId)||a.type===M.SUBTITLE_TRACK&&e.hasSubtitleGroup(a.groupId))&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.loadLevel),t.errorAction.action=tK.SendAlternateToPenaltyBox,t.errorAction.flags=tV.MoveAllAlternatesMatchingHost)}return;case g.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:tK.SendAlternateToPenaltyBox,flags:tV.MoveAllAlternatesMatchingHDCP};return;case g.KEY_SYSTEM_SESSION_UPDATE_FAILED:case g.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case g.KEY_SYSTEM_NO_SESSION:t.errorAction={action:tK.SendAlternateToPenaltyBox,flags:tV.MoveAllAlternatesMatchingKey};return;case g.BUFFER_ADD_CODEC_ERROR:case g.REMUX_ALLOC_ERROR:case g.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level));return;case g.MEDIA_SOURCE_REQUIRES_RESET:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),t.errorAction.flags|=tV.ResetMediaSource|tV.SwitchToSDR;return;case g.INTERNAL_EXCEPTION:case g.BUFFER_APPENDING_ERROR:case g.BUFFER_APPEND_NO_PROGRESS:case g.BUFFER_FULL_ERROR:case g.LEVEL_SWITCH_ERROR:case g.BUFFER_STALLED_ERROR:case g.BUFFER_SEEK_OVER_HOLE:case g.BUFFER_NUDGE_ON_STALL:t.errorAction=tj();return}t.type===c.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=tj())}getPlaylistRetryOrSwitchAction(e,t){let i=X(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(Z(i,r,W(e),e.response))return{action:tK.RetryRequest,flags:tV.None,retryConfig:i,retryCount:r};let s=this.getLevelSwitchAction(e,t);return i&&(s.retryConfig=i,s.retryCount=r),s}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:a}=t.config,n=X(j(e)?a:s,e),l=t.levels.reduce((e,t)=>
11e+t.fragmentError,0);if(r&&(e.details!==g.FRAG_GAP&&r.fragmentError++,!q(e)&&Z(n,l,W(e),e.response)))return{action:tK.RetryRequest,flags:tV.None,retryConfig:n,retryCount:l};let o=this.getLevelSwitchAction(e,i);return n&&(o.retryConfig=n,o.retryCount=l),o}getLevelSwitchAction(e,t){let i=this.hls;null==t&&(t=i.loadLevel);let r=this.hls.levels[t];if(r){var s,a,n,l;let t=e.details;r.loadError++,r.loadErrorTime=self.performance.now(),t===g.BUFFER_APPEND_ERROR&&r.fragmentError++;let o=-1,{levels:h,loadLevel:d,minAutoLevel:u,maxAutoLevel:f}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);let c=null==(s=e.frag)?void 0:s.type,m=(c===w.AUDIO&&t===g.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&tY(e))&&h.some(({audioCodec:e})=>r.audioCodec!==e),p="video"===e.sourceBufferName&&tY(e)&&h.some(({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t),{type:E,groupId:v}=null!=(a=e.context)?a:{};for(let s=h.length;s--;){let a=(s+d)%h.length;if(a!==d&&a>=u&&a<=f&&(0===h[a].loadError||ee(h[a],i.config.errorPenaltyExpireMs))){let i=h[a];if(t===g.FRAG_GAP&&c===w.MAIN&&e.frag){let t=h[a].details;if(t){let i=t$(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else if(E===M.AUDIO_TRACK&&i.hasAudioGroup(v)||E===M.SUBTITLE_TRACK&&i.hasSubtitleGroup(v))continue;else if(c===w.AUDIO&&null!=(n=r.audioGroups)&&n.some(e=>i.hasAudioGroup(e))||c===w.SUBTITLE&&null!=(l=r.subtitleGroups)&&l.some(e=>i.hasSubtitleGroup(e))||m&&r.audioCodec===i.audioCodec||p&&r.codecSet===i.codecSet||!m&&r.audioCodec!==i.audioCodec)continue;o=a;break}}if(o>-1&&i.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:tK.SendAlternateToPenaltyBox,flags:tV.None,nextAutoLevel:o}}return{action:tK.SendAlternateToPenaltyBox,flags:tV.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i,r;switch(null==(i=t.errorAction)?void 0:i.action){case tK.DoNothing:break;case tK.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===g.FRAG_GAP||t.details===g.PLAYLIST_UNCHANGED_ERROR||tW(t)||(t.fatal=!0);case tK.RetryRequest:}if(((null==(r=t.errorAction)?void 0:r.flags)||0)&tV.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let r=i.nextAutoLevel;if(i.flags===tV.None)this.switchLevel(e,r);else if(i.flags&tV.SwitchToSDR){let e=this.hls.levels,t=e.length;for(let i=t;i--;)"SDR"!==e[i].videoRange?(e[i].fragmentError++,e[i].loadError++):void 0===r&&(r=i)}else if(i.flags&tV.MoveAllAlternatesMatchingHDCP){let r=this.getVariantLevelIndex(e.frag),s=t.levels[r],a=null==s?void 0:s.attrs["HDCP-LEVEL"];i.hdcpLevel=a;let n="NONE"===a;a&&!n?(t.maxHdcpLevel=tE[tE.indexOf(a)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(n&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),i.flags|=tV.MoveAllAlternatesMatchingKey)}if(i.flags&tV.MoveAllAlternatesMatchingKey){let t=e.decryptdata;if(t){let r=this.hls.levels,n=r.length;for(let i=n;i--;)if(this.variantHasKey(r[i],t)){var s,a;this.log(`Banned key found in level ${i} (${r[i].bitrate}bps) or audio group "${null==(s=r[i].audioGroups)?void 0:s.join(",")}" (${null==(a=e.frag)?void 0:a.type} fragment) ${eR(t.keyId||[])}`),r[i].fragmentError++,r[i].loadError++,this.log(`Removing level ${i} with key error (${e.error})`),this.hls.removeLevel(i)}let l=e.frag;if(this.hls.levels.length<n)i.resolved=!0;else if(l&&l.type!==w.MAIN){let e=l.decryptdata;e&&!t.matches(e)&&(i.resolved=!0)}}}i.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===g.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){let t=th(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${r} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(r))}}}function tY(e){let t=e.details;return!(t!==g.BUFFER_ADD_CODEC_ERROR&&t!==g.MEDIA_SOURCE_REQUIRES_RESET&&(t!==g.BUFFER_APPEND_ERROR||tW(e)))}function tW(e){return e.details===g.BUFFER_APPEND_ERROR&&("QuotaExceededError"===e.error.name||"InvalidStateError"===e.error.name)}function tj(e){let t={action:tK.DoNothing,flags:tV.None};return e&&(t.resolved=!0),t}var tq={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class tX{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){let{hls:e}=this;e&&(e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let t=i.length;t--;){let r=i[t];if(!r)break;
11if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,i){let{fragments:r}=this,s=Object.keys(r);for(let a=s.length;a--;){let n=r[s[a]];if((null==n?void 0:n.body.type)===t&&(!i||n.buffered)){let t=n.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,r,s,a){this.timeRanges&&(this.timeRanges[e]=t);let n=(null==s?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach(s=>{let l=this.fragments[s];if(!l||!this.hls)return;let o=l.body;if(n>=o.sn)return;if(!l.buffered&&(!l.loaded||a)){o.type===i&&this.removeFragment(o);return}let h=l.range[e];if(h){if(0===h.time.length){this.removeFragment(o);return}if(h.time.some(e=>{let i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(o),i}),r&&r!==o&&e3()){let e=r.endPTS,t=o.startPTS;if(e&&t&&l.range.video){let i=t-e;i<0&&i>-.1&&(this.removeFragment(o),this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(e){let t=this.timeRanges,{frag:i,part:r,id:s}=e;if(!t||!N(i))return;let a=tQ(i),n=this.fragments[a];if(!n||n.buffered&&i.gap)return;let l=!i.relurl;Object.keys(t).forEach(e=>{let a=i.elementaryStreams[e];if(!a)return;let o=t[e],h=l||!0===a.partial;n.range[e]=this.getBufferedTimes(i,r,h,o),this.detectEvictedFragments(e,o,s,i,r)}),n.loaded=null;let o=Object.keys(n.range);if(o.length){if(this.bufferedEnd(n,i),tz(n)||this.removeParts(i.sn-1,i.type),!r){let e=Math.min(.004,i.duration);o.some(t=>{var r;let s=null==(r=n.range[t])?void 0:r.time,a=0===s.length||1===s.length&&s[0].endPTS-s[0].startPTS<e;return a&&this.addAsGap(i),a})}}else this.removeFragment(i)}addAsGap(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=tZ(i,t=>t.fragment.sn>=e))}fragBuffered(e,t){let i=tQ(e),r=this.fragments[i];return!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e)),r}getBufferedTimes(e,t,i,r){let s={time:[],partial:i},a=e.start,n=e.end,l=e.minEndPTS||n,o=e.maxStartPTS||a;for(let e=0;e<r.length;e++){let t=r.start(e)-this.bufferPadding,i=r.end(e)+this.bufferPadding;if(o>=t&&l<=i){s.time.push({startPTS:Math.max(a,r.start(e)),endPTS:Math.min(n,r.end(e))});break}if(a<i&&n>t){let t=Math.max(a,r.start(e)),i=Math.min(n,r.end(e));i>t&&(s.partial=!0,s.time.push({startPTS:t,endPTS:i}))}else if(n<=t)break}return s}getPartialFragment(e){let t,i,r,s=null,a=0,{bufferPadding:n,fragments:l}=this;return Object.keys(l).forEach(o=>{let h=l[o];h&&tz(h)&&(i=h.body.start-n,r=h.body.end+n,e>=i&&e<=r&&a<=(t=Math.min(e-i,r-e))&&(s=h.body,a=t))}),s}isEndListAppended(e){let t=this.endListFragments[e];return void 0!==t&&(t.buffered||tz(t))}getState(e){let t=tQ(e),i=this.fragments[t];return i?i.buffered?tz(i)?tq.PARTIAL:tq.OK:tq.APPENDING:tq.NOT_LOADED}isTimeBuffered(e,t,i){let r,s;for(let a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,s=i.end(a)+this.bufferPadding,e>=r&&t<=s)return!0;if(t<=r)break}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!N(t.frag)||t.frag.bitrateTest)return;let i=t.frag,r=t.part?null:t,s=tQ(i);this.fragments[s]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:r,timeRanges:s}=t;if(!N(i))return;let a=i.type;if(r){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(r)}this.timeRanges=s}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=tQ(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let r=i.length;r--;){let s=t[i[r]];if((null==s?void 0:s.body.type)===e)return!0}return!1}hasParts(e){var t;return!!(null!=(t=this.activePartLists[e])&&t.length)}getBackBufferEvictionEnd(e,t,i){let{fragments:r}=this,s=0,a=0,n=Object.keys(r);for(let l=0;l<n.length;l++){let o=r[n[l]];if(!o||!o.buffered||o.body.type!==t)continue;let h=o.body;if(h.gap)return 0;let d=h.hasStats&&h.stats.loaded||h.byteLength||h.bitrate&&8*h.bitrate*h.duration;if(h.end<=e&&d&&(s+=d,a=Math.max(a,h.end),s>=i))return a}return a>0?a:0}removeFragmentsInRange(e,t,i,r,s){(!r||this.hasGaps)&&Object.keys(this.fragments).forEac
11h(a=>{let n=this.fragments[a];if(!n)return;let l=n.body;l.type===i&&(!r||l.gap)&&l.start<t&&l.end>e&&(n.buffered||s)&&this.removeFragment(l)})}removeFragment(e){let t=tQ(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let t=e.sn;this.activePartLists[e.type]=tZ(i,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}}function tz(e){var t,i,r,s;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(i=e.range.audio)&&i.partial||null!=(r=e.range.audiovideo)&&r.partial||null!=(s=e.range.subs)&&s.partial)}function tQ(e){return`${e.type}_${e.level}_${e.sn}`}function tZ(e,t){return e.filter(e=>{let i=t(e);return i||e.clearElementaryStreamInfo(),i})}var tJ={cbc:0,ctr:1};class t0{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case tJ.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case tJ.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class t1{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],s=i[1],a=i[2],n=i[3],l=this.invSubMix,o=l[0],h=l[1],d=l[2],u=l[3],f=new Uint32Array(256),c=0,g=0,m=0;for(m=0;m<256;m++)m<128?f[m]=m<<1:f[m]=m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,e[c]=i,t[i]=c;let l=f[c],m=f[l],p=f[m],E=257*f[i]^16843008*i;r[c]=E<<24|E>>>8,s[c]=E<<16|E>>>16,a[c]=E<<8|E>>>24,n[c]=E,E=16843009*p^65537*m^257*l^16843008*c,o[i]=E<<24|E>>>8,h[i]=E<<16|E>>>16,d[i]=E<<8|E>>>24,u[i]=E,c?(c=l^f[f[f[p^l]]],g^=f[f[g]]):c=g=1}}expandKey(e){let t,i,r,s;let a=this.uint8ArrayToUint32Array_(e),n=!0,l=0;for(;l<a.length&&n;)n=a[l]===this.key[l],l++;if(n)return;this.key=a;let o=this.keySize=a.length;if(4!==o&&6!==o&&8!==o)throw Error("Invalid aes key size="+o);let h=this.ksRows=(o+6+1)*4,d=this.keySchedule=new Uint32Array(h),u=this.invKeySchedule=new Uint32Array(h),f=this.sBox,c=this.rcon,g=this.invSubMix,m=g[0],p=g[1],E=g[2],v=g[3];for(t=0;t<h;t++){if(t<o){r=d[t]=a[t];continue}s=r,t%o==0?s=(f[(s=s<<8|s>>>24)>>>24]<<24|f[s>>>16&255]<<16|f[s>>>8&255]<<8|f[255&s])^c[t/o|0]<<24:o>6&&t%o==4&&(s=f[s>>>24]<<24|f[s>>>16&255]<<16|f[s>>>8&255]<<8|f[255&s]),d[t]=r=(d[t-o]^s)>>>0}for(i=0;i<h;i++)t=h-i,s=3&i?d[t]:d[t-4],i<4||t<=4?u[i]=s:u[i]=m[f[s>>>24]]^p[f[s>>>16&255]]^E[f[s>>>8&255]]^v[f[255&s]],u[i]=u[i]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,i){let r,s,a,n,l,o,h,d,u,f,c,g,m,p;let E=this.keySize+6,v=this.invKeySchedule,y=this.invSBox,T=this.invSubMix,S=T[0],A=T[1],I=T[2],L=T[3],R=this.uint8ArrayToUint32Array_(i),b=R[0],D=R[1],k=R[2],P=R[3],_=new Int32Array(e),C=new Int32Array(_.length),O=this.networkToHostOrderSwap;for(;t<_.length;){for(p=1,u=O(_[t]),f=O(_[t+1]),c=O(_[t+2]),g=O(_[t+3]),l=u^v[0],o=g^v[1],h=c^v[2],d=f^v[3],m=4;p<E;p++)r=S[l>>>24]^A[o>>16&255]^I[h>>8&255]^L[255&d]^v[m],s=S[o>>>24]^A[h>>16&255]^I[d>>8&255]^L[255&l]^v[m+1],a=S[h>>>24]^A[d>>16&255]^I[l>>8&255]^L[255&o]^v[m+2],n=S[d>>>24]^A[l>>16&255]^I[o>>8&255]^L[255&h]^v[m+3],l=r,o=s,h=a,d=n,m+=4;r=y[l>>>24]<<24^y[o>>16&255]<<16^y[h>>8&255]<<8^y[255&d]^v[m],s=y[o>>>24]<<24^y[h>>16&255]<<16^y[d>>8&255]<<8^y[255&l]^v[m+1],a=y[h>>>24]<<24^y[d>>16&255]<<16^y[l>>8&255]<<8^y[255&o]^v[m+2],n=y[d>>>24]<<24^y[l>>16&255]<<16^y[o>>8&255]<<8^y[255&h]^v[m+3],C[t]=O(r^b),C[t+1]=O(n^D),C[t+2]=O(a^k),C[t+3]=O(s^P),b=u,D=f,k=c,P=g,t+=4}return C.buffer}}class t2{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){let e=function(e){switch(e){case tJ.cbc:return"AES-CBC";case tJ.ctr:return"AES-CTR";default:throw Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class t4{constructor(e,t){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.enableSoftw
11areAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,!0!==t)try{let e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}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:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let i=new Uint8Array(e);this.reset();let r=this.decryptRange;return r?0===r.start&&r.end>=i.length?i:i.slice(r.start,r.end):function(e){let t=e.byteLength,i=t&&new DataView(e.buffer).getUint8(t-1);return i?e.slice(0,t-i):e}(i)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,r,s){return(this.decryptRange=s,this.useSoftware||s)?new Promise((s,a)=>{let n=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(n,t,i,r);let l=this.flush();l?s(l.buffer):a(Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)}softwareDecrypt(e,t,i,r){let{currentIV:s,currentResult:a,remainderData:n}=this;if(r!==tJ.cbc||16!==t.byteLength)return eo.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),n&&(e=eX(n,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;s&&(i=s);let o=this.softwareDecrypter;return(o||(o=this.softwareDecrypter=new t1),o.expandKey(t),this.currentResult=o.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,a)?a:null}webCryptoDecrypt(e,t,i,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new t2(this.subtle,t,r)}return this.fastAesKey.expandKey().then(t=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new t0(this.subtle,new Uint8Array(i),r).decrypt(e.buffer,t)):Promise.reject(Error("web crypto not initialized"))).catch(s=>(eo.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,i,r)))}onWebCryptoError(e,t,i,r){let s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);let s=this.flush();if(s)return s.buffer}throw Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(eo.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}class t3{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t,i,r){let s=e.url;if(!s)return Promise.reject(new t9({type:c.NETWORK_ERROR,details:g.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();let a=this.config,n=a.fLoader,l=a.loader;return new Promise((o,h)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>"GAP"===e[0])){h(t6(e));return}e.gap=!1}let d=this.loader=n?new n(a):new l(a),u=t8(e,null,t);e.loader=d;let f=Q(a.fragLoadPolicy.default),m={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:131072};d.stats.retry=e.stats.retry,e.stats=d.stats;let p={onSuccess:(t,i,r,s)=>{this.resetLoader(e,d);let a=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),o({frag:e,part:null,payload:a,networkDetails:s})},onError:(t,i,r,a)=>{this.resetLoader(e,d),h(new t9({type:c.NETWORK_ERROR,details:g.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:H({url:s,data:void 0},t),error:Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:r,stats:a}))},onAbort:(t,i,r)=>{this.resetLoader(e,d),h(new t9({type:c.NETWORK_ERROR,details:g.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,i,r)=>{this.resetLoader(e,d),h(new t9({type:c.NETWORK_ERROR,details:g.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${m.timeout}ms`),networkDetails:r,stats:t}))}};if(i){let t=this.gateProgress(i,r);p.onProgress=(i,r,s,a)=>t({frag:e,part:null,payload:s,networkDetails:a})}d.load(u,m,p)})}gateProgress(e,t){let i=e;if(t){let r=[],s=!1;t.then(()=>{s=!0,r.forEach(t=>e(t)),r.length=0}
11).catch(()=>{}),i=t=>{s?e(t):r.push(t)}}return i}loadPart(e,t,i){this.abort();let r=this.config,s=r.fLoader,a=r.loader;return new Promise((n,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(t6(e,t));return}let o=this.loader=s?new s(r):new a(r),h=t8(e,t);e.loader=o;let d=Q(r.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:131072};t.stats=o.stats,o.load(h,u,{onSuccess:(r,s,a,l)=>{this.resetLoader(e,o),this.updateStatsFromPart(e,t);let h={frag:e,part:t,payload:r.data,networkDetails:l};i(h),n(h)},onError:(i,r,s,a)=>{this.resetLoader(e,o),l(new t9({type:c.NETWORK_ERROR,details:g.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:H({url:h.url,data:void 0},i),error:Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:s,stats:a}))},onAbort:(i,r,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,o),l(new t9({type:c.NETWORK_ERROR,details:g.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(e,o),l(new t9({type:c.NETWORK_ERROR,details:g.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:i}))}})})}updateStatsFromPart(e,t){let i=e.stats,r=t.stats,s=r.total;if(i.loaded+=r.loaded,s){let r=Math.round(e.duration/t.duration),a=Math.min(Math.round(i.loaded/s),r),n=(r-a)*Math.round(i.loaded/a);i.total=i.loaded+n}else i.total=Math.max(i.loaded,i.total);let a=i.loading,n=r.loading;a.start?a.first+=n.first-n.start:(a.start=n.start,a.first=n.first),a.end=n.end}resetLoader(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function t8(e,t=null,i){let r=t||e,s={type:M.MEDIA_FRAGMENT,frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},a=t5(e,t,i);return a.resetIV&&(s.resetIV=!0),a.byteRange&&(s.rangeStart=a.byteRange.start,s.rangeEnd=a.byteRange.end),s}function t5(e,t=null,i){let r={},s=t||e,a=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(d(a)&&d(n)){var l,o;if(("initSegment"===e.sn||i)&&("AES-128"===(o=null==(l=e.decryptdata)?void 0:l.method)||"AES-256"===o)){let e=16*Math.floor(a/16);r.decryptRange={start:a-e,end:n-e},e>=16&&(r.resetIV=!0,e-=16),r.byteRange={start:e,end:16*Math.ceil(n/16)}}else r.byteRange={start:a,end:n}}return r}function t6(e,t){let i=Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:c.MEDIA_ERROR,details:g.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new t9(r)}class t9 extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class t7 extends er{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount?(this.doTick(),this._tickCallCount>1&&this.tickImmediate()):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 ie{constructor(e,t,i,r=0,s=-1,a=!1,n,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=it(),this.buffering={audio:it(),video:it(),audiovideo:it()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=s,this.partial=a,this.duration=n||0,this.decryptRange=o,this.iframe=l||!1}}function it(){return{start:0,executeStart:0,executeEnd:0,end:0}}let ii={length:0,start:()=>0,end:()=>0};class ir{static isBuffered(e,t){if(e){let i=ir.getBuffered(e);for(let e=i.length;e--;)if(t>=i.start(e)&&t<=i.end(e))return!0}return!1}static bufferedRanges(e){if(e){let t=ir.getBuffered(e);return ir.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){let r=ir.bufferedRanges(e);if(r.length)return ir.bufferedInfo(r,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){let r;t=Math.max(0,t),e.length>1&&e.sort((e,t)=>
11e.start-t.start||t.end-e.end);let s=-1,a=[];if(i)for(let r=0;r<e.length;r++){t>=e[r].start&&t<=e[r].end&&(s=r);let n=a.length;if(n){let t=a[n-1].end;e[r].start-t<i?e[r].end>t&&(a[n-1].end=e[r].end):a.push(e[r])}else a.push(e[r])}else a=e;let n=0,l=t,o=t;for(let e=0;e<a.length;e++){let h=a[e].start,d=a[e].end;if(-1===s&&t>=h&&t<=d&&(s=e),t+i>=h&&t<d)l=h,n=(o=d)-t;else if(t+i<h){r=h;break}}return{len:n,start:l||0,end:o||0,nextStart:r,buffered:e,bufferedIndex:s}}static getBuffered(e){try{return e.buffered||ii}catch(e){return eo.log("failed to get media.buffered",e),ii}}}let is=/\{\$([a-zA-Z0-9-_]+)\}/g;function ia(e,t){if(null!==e.variableList||e.hasVariableRefs){let i=e.variableList;return t.replace(is,t=>{let r=t.substring(2,t.length-1),s=null==i?void 0:i[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):s})}return t}function il(e,t,i){let r,s,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{let e=new self.URL(i).searchParams;if(e.has(r))s=e.get(r);else throw Error(`"${r}" does not match any query parameter in URI: "${i}"`)}catch(t){e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,s=t.VALUE;r in a?e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):a[r]=s||""}let io=/^(\d+)x(\d+)$/,ih=/(.+?)=(".*?"|.*?)(?:,|$)/g;class id{constructor(e,t){"string"==typeof e&&(e=id.parseAttrList(e,t)),K(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2),i=new Uint8Array((t=(1&t.length?"0":"")+t).length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+2),16);return i}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){let t=io.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i;let r={};for(ih.lastIndex=0;null!==(i=ih.exec(e));){let s=i[1].trim(),a=i[2],n=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,l=!1;if(n)a=a.slice(1,-1);else switch(s){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(n||l))a=ia(t,a);else if(!l&&!n)switch(s){case"CLOSED-CAPTIONS":if("NONE"===a)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":eo.warn(`${e}: attribute ${s} is missing quotes`)}r[s]=a}return r}}class iu{constructor(e,t,i=0){var r;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(r=null==t?void 0:t.tagOrder)?r:i,t){let i=t.attr;for(let t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){eo.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=K(new id({}),i,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){let i=(null==t?void 0:t.endDate)||new Date(e["END-DATE"]);d(i.getTime())&&(this._endDate=i)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return null===e||null===e.programDateTime?(eo.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(d(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&d(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:d(this.startDate.getTime())?this.isInterstitial&&!("X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)?"Interstitial Date range missing X-ASSET-(LIST|URI)":this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Date range invalid start date":"Missing ID"}}class ic{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.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.drift
11StartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&d(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(-1!==t){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function ig(e,t){return e.length===t.length&&!e.some((e,i)=>e!==t[i])}function im(e,t){return!e&&!t||!!e&&!!t&&ig(e,t)}function ip(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function iE(e){switch(e){case"AES-128":case"AES-256":return tJ.cbc;case"AES-256-CTR":return tJ.ctr;default:throw Error(`invalid full segment method ${e}`)}}function iv(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function iy(e){let t=function(e,t,i){let r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function iT(e){let t=e.split(":"),i=null;if("data"===t[0]&&2===t.length){let e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){let t="base64"===r[0],s=r[1];t?(e.splice(-1,1),i=eD(s)):i=function(e){let t=iv(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(s)}}return i}let iS="undefined"!=typeof self?self:void 0;var iA={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},iI={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function iL(e){switch(e){case iI.FAIRPLAY:return iA.FAIRPLAY;case iI.PLAYREADY:return iA.PLAYREADY;case iI.WIDEVINE:return iA.WIDEVINE;case iI.CLEARKEY:return iA.CLEARKEY}}var iR={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function ib(e){switch(e){case iA.FAIRPLAY:return iI.FAIRPLAY;case iA.PLAYREADY:return iI.PLAYREADY;case iA.WIDEVINE:return iI.WIDEVINE;case iA.CLEARKEY:return iI.CLEARKEY}}function iD(e){let{drmSystems:t,widevineLicenseUrl:i}=e,r=t?[iA.FAIRPLAY,iA.WIDEVINE,iA.PLAYREADY,iA.CLEARKEY].filter(e=>!!t[e]):[];return!r[iA.WIDEVINE]&&i&&r.push(iA.WIDEVINE),r}let ik=null!=iS&&null!=(S=iS.navigator)&&S.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function iP(e){let t=ek(new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2)),i=t.substring(t.indexOf("<"),t.length),r=new DOMParser().parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(r){let e=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute("VALUE");if(e){let t=eD(e).subarray(0,16);return iy(t),t}}return null}let i_={};class iC{static clearKeyUriToKeyIdMap(){i_={}}static setKeyIdForUri(e,t){i_[e]=t}static addKeyIdForUri(e){let t=Object.keys(i_).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),i_[e]=i,i}constructor(e,t,i,r=[1],s=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pss
11h=null,this.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!ip(e),null!=a&&a.startsWith("0x")&&(this.keyId=new Uint8Array(eb(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&ig(e.keyFormatVersions,this.keyFormatVersions)&&im(e.iv,this.iv)&&im(e.keyId,this.keyId)}isSupported(){if(this.method){if(ip(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case iI.FAIRPLAY:case iI.WIDEVINE:case iI.PLAYREADY:case iI.CLEARKEY:return -1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,t){var i,r;if(!this.encrypted||!this.uri)return null;if(ip(this.method)){let t=this.iv;return t||("number"!=typeof e&&(eo.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){let t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(e)),new iC(this.method,this.uri,"identity",this.keyFormatVersions,t)}if(this.keyId){let e=i_[this.uri];if(e&&!ig(this.keyId,e)&&iC.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let s=iT(this.uri);if(s)switch(this.keyFormat){case iI.WIDEVINE:if(this.pssh=s,!this.keyId){let e=e0(s.buffer).filter(e=>e.systemId===iR.WIDEVINE);if(e.length){let t=e[0];this.keyId=null!=(r=t.kids)&&r.length?t.kids[0]:null}}this.keyId||(this.keyId=iO(t));break;case iI.PLAYREADY:{let e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(e,t,i){let r,s;if(16!==e.byteLength)throw RangeError("Invalid system id");r=new Uint8Array,s=new Uint8Array;let a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(e,...t){let i=t.length,r=8,s=i;for(;s--;)r+=t[s].byteLength;let a=new Uint8Array(r);for(a[0]=r>>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=255&r,a.set(e,4),s=0,r=8;s<i;s++)a.set(t[s],r),r+=t[s].byteLength;return a}([112,115,115,104],new Uint8Array([0,0,0,0]),e,s,r,a,i)}(e,0,s),this.keyId=iP(s);break}default:{let e=s.subarray(0,16);if(16!==e.length){let t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e}}if((null==(i=this.keyId)?void 0:i.byteLength)!==16){let e;(e=function(e){let t=null==e?void 0:e[iI.WIDEVINE];return t?t.keyId:null}(t))||(e=iO(t))||(e=i_[this.uri]),e&&(this.keyId=e,iC.setKeyIdForUri(this.uri,e))}return this}}function iO(e){let t=null==e?void 0:e[iI.PLAYREADY];if(t){let e=iT(t.uri);if(e)return iP(e)}return null}let iM=/#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,iw=/#EXT-X-MEDIA:(.*)/g,iF=/^#EXT(?:INF|-X-TARGETDURATION):/m,ix=RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),iN=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 i${static findGroup(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r.id===t)return r}}static resolve(e,t){return C.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return iF.test(e)}static parseMasterPlaylist(e,t){let i;let r={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:is.test(e)},s=[];if(iM.lastIndex=0,!e.startsWith("#EXTM3U"))return r.playlistParsingError=Error("no EXTM3U delimiter"),r;for(;null!=(i=iM.exec(e));)if(i[1]){let e=iU(new id(i[1],r),i[2],t,r,s);e&&r.levels.push(e)}else if(i[3]){let e=i[3],a=i[4];switch(e){case"I-FRAME-STREAM-INF":{let e=new id(a,r),i=iU(e,e.URI,t,r,s,!0);i&&r.iframeVariants.push(i)}break;case"SESSION-DATA":{let e=new id(a,r),t=e["DATA-ID"];t&&(null===r.sessionData&&(r.sessionData={}),r.sessionData[t]=e);break}case"SESSION-KEY":{let e=iG(a,t,r);e.encrypted&&e.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(e)):eo.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${a}"`);break}case"DEFINE":{let e=new id(a,r);il(r,e,t)}break;case"CONTENT-STEERING":{let e=new id(a,r);r.contentSteering={uri:i$.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=iK(a)}}let a=s.length>0&&s.length<r.levels.length;return r.levels=a?s:r.levels,0===r.levels.length&&(r.playlistParsingError=Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(e,t,i){let r;let s={},a=i.levels,n={AUDIO:a.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:a.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(iw.lastIndex=0;null!==(r=iw.exec(e));){let e=new id(r[1],i),a=e.TYPE;if(a){let i=n[a],r=s[a]||[];s[a]=r;let o=e.LANGUAGE,h=e["ASSOC-LANGUAGE"],d=e.CHANNELS,u=e.CHARACTERISTICS,f=e["INSTREAM-ID"],c={attrs:e,bitrate:0,id:l++,groupId:e["GROUP-ID"]||"",name:e.NAME||o||"",type:a,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:o,url:e.URI?i$.resolve(e.URI,t):""};if(h&&(c.assocLang=h),d&&(c.channels=d),u&&(c.characteristics=u),f&&(c.instreamId=f),null!=i&&i.length){let e=i$.findGroup(i,c.groupId)||i[0];iH(c,e,"audioCodec"),iH(c,e,"textCodec")}r.push(c)}}return s}static parseLevelPlaylist(e,t,i,r,s,a){var n,l,o;let h,u,f,c;let g={url:t},m=new ic(t),p=m.fragments,E=[],v=null,y=0,T=0,S=0,A=0,I=0,L=null,R=new B(r,g),b=-1,D=!1,k=null;if(ix.lastIndex=0,m.m3u8=e,m.hasVariableRefs=is.test(e),(null==(n=ix.exec(e))?void 0:n[0])!=="#EXTM3U")return m.playlistParsingError=Error("Missing format identifier #EXTM3U"),m;
11for(;null!==(h=ix.exec(e));){D&&(D=!1,(R=new B(r,g)).playlistOffset=S,R.setStart(S),R.sn=y,R.cc=A,I&&(R.bitrate=I),R.level=i,v&&(R.initSegment=v,v.rawProgramDateTime&&(R.rawProgramDateTime=v.rawProgramDateTime,v.rawProgramDateTime=null),k&&(R.setByteRange(k),k=null)));let e=h[1];if(e){R.duration=parseFloat(e);let t=(" "+h[2]).slice(1);R.title=t||null,R.tagList.push(t?["INF",e,t]:["INF",e])}else if(h[3]){if(d(R.duration)){R.playlistOffset=S,R.setStart(S),f&&ij(R,f,m),R.sn=y,R.level=i,R.cc=A;let e=(" "+h[3]).slice(1);R.relurl=ia(m,e),iY(R,L,E),L=R,S+=R.duration,y++,T=0;let t=R.byteRange;if(2===t.length&&(R.bitrate=(t[1]-t[0])*8/R.duration|0),m.iframesOnly&&t[0]&&(null==(l=v)?void 0:l.cc)!==A){let e=new B(r,g);e.relurl=R.relurl,e.setByteRange(`${Math.min(t[0],1316)}@0`),e.level=i,e.sn="initSegment",f&&(e.levelkeys=f,f.identity&&(e._decryptdata=f.identity.getDecryptData(0))),v=e,R.initSegment=v}p.push(R),D=!0}}else{if(!(h=h[0].match(iN))){eo.warn("No matches on slow regex match for level playlist!");continue}for(u=1;u<h.length&&void 0===h[u];u++);let e=(" "+h[u]).slice(1),s=(" "+h[u+1]).slice(1),n=h[u+2]?(" "+h[u+2]).slice(1):null;switch(e){case"BYTERANGE":L?R.setByteRange(s,L):R.setByteRange(s);break;case"PROGRAM-DATE-TIME":R.rawProgramDateTime=s,R.tagList.push(["PROGRAM-DATE-TIME",s]),-1===b&&(b=p.length);break;case"PLAYLIST-TYPE":m.type&&iq(m,e,h),m.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":0!==m.startSN?iq(m,e,h):null!==L&&(o=h,m.playlistParsingError=Error(`#EXT-X-${e} must appear before the first Media Segment (${o[0]})`)),m.startSN=parseInt(s),y=m.startSN+m.skippedSegments;break;case"SKIP":{m.skippedSegments&&iq(m,e,h);let t=new id(s,m),i=t.decimalInteger("SKIPPED-SEGMENTS");if(d(i)){m.skippedSegments+=i;for(let e=i;e--;)p.push(null);y+=i}let r=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(m.recentlyRemovedDateranges=(m.recentlyRemovedDateranges||[]).concat(r.split(" ")));break}case"TARGETDURATION":0!==m.targetduration&&iq(m,e,h),m.targetduration=Math.max(parseInt(s),1);break;case"VERSION":null!==m.version&&iq(m,e,h),m.version=parseInt(s);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":m.iframesOnly=!0;break;case"ENDLIST":m.live||iq(m,e,h),m.live=!1;break;case"#":(s||n)&&R.tagList.push(n?[s,n]:[s]);break;case"DISCONTINUITY":A++,R.tagList.push(["DIS"]);break;case"GAP":R.gap=!0,R.tagList.push([e]);break;case"BITRATE":R.tagList.push([e,s]),d(I=1e3*parseInt(s))?R.bitrate=I:I=0;break;case"DATERANGE":{let e=new id(s,m),t=new iu(e,m.dateRanges[e.ID],m.dateRangeTagCount);m.dateRangeTagCount++,t.isValid||m.skippedSegments?m.dateRanges[t.id]=t:eo.log(`Ignoring invalid DATERANGE tag: ${t.invalidReason}: ${s}`),R.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{let e=new id(s,m);"IMPORT"in e?function(e,t,i){let r=t.IMPORT;if(i&&r in i){let t=e.variableList;t||(e.variableList=t={}),t[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}(m,e,a):il(m,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==m.startCC&&iq(m,e,h),m.startCC=A=parseInt(s),p.forEach(e=>e&&(e.cc=A));break;case"KEY":{let e=iG(s,t,m);if(e.isSupported()){if("NONE"===e.method){f=void 0;break}f||(f={});let t=f[e.keyFormat];null!=t&&t.matches(e)||(t&&(f=K({},f)),f[e.keyFormat]=e)}else eo.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${s}"`);break}case"START":m.startTimeOffset=iK(s);break;case"MAP":{let e=new id(s,m);if(R.duration){let t=new B(r,g);iW(t,e,i,f),v=t,R.initSegment=v,v.rawProgramDateTime&&!R.rawProgramDateTime&&(R.rawProgramDateTime=v.rawProgramDateTime)}else{let t=R.byteRangeEndOffset;if(t){let e=R.byteRangeStartOffset;k=`${t-e}@${e}`}else k=null;iW(R,e,i,f),v=R,D=!0}v.cc=A;break}case"SERVER-CONTROL":c&&iq(m,e,h),c=new id(s),m.canBlockReload=c.bool("CAN-BLOCK-RELOAD"),m.canSkipUntil=c.optionalFloat("CAN-SKIP-UNTIL",0),m.canSkipDateRanges=m.canSkipUntil>0&&c.bool("CAN-SKIP-DATERANGES"),m.partHoldBack=c.optionalFloat("PART-HOLD-BACK",0),m.holdBack=c.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{m.partTarget&&iq(m,e,h);let t=new id(s);m.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let e=m.partList;e||(e=m.partList=[]);let t=T>0?e[e.length-1]:void 0,i=T++,r=new G(new id(s,m),R,g,i,t);e.push(r),R.duration+=r.duration;break}case"PRELOAD-HINT":{let e=new id(s,m);m.preloadHint=e;break}case"RENDITION-REPORT":{let e=new id(s,m);m.renditionReports=m.renditionReports||[],m.renditionReports.push(e);break}default:eo.warn(`line parsed but not handled: ${h}`)}}}L&&!L.relurl?(p.pop(),S-=L.duration,m.partList&&(m.fragmentHint=L)):m.partList&&(iY(R,L,E),R.cc=A,m.fragmentHint=R,f&&ij(R,f,m)),m.targetduration||(m.playlistParsingError=Error("Missing Target Duration"));let P=p.length,_=p[0],C=p[P-1];
11if((S+=m.skippedSegments*m.targetduration)>0&&P&&C){m.averagetargetduration=S/P;let e=C.sn;m.endSN="initSegment"!==e?e:0,m.live||(C.endList=!0),b>0&&(function(e,t,i){if(i||(i=e[t]),i)for(let r=t;r--;){let t=e[r];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(p,b,b>P-1?R:null),_&&E.unshift(_))}return m.fragmentHint&&(S+=m.fragmentHint.duration),m.totalduration=S,E.length&&m.dateRangeTagCount&&_&&iB(E,m),m.endCC=A,m}}function iU(e,t,i,r,s,a){var n;if(void 0===t)return null;let l=ia(r,t),o={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:i$.resolve(l,i)},h=e.decimalResolution("RESOLUTION");h&&(o.width=h.width,o.height=h.height),iV(e.CODECS,o);let d=e["SUPPLEMENTAL-CODECS"];return d&&(o.supplemental={},iV(d,o.supplemental)),null!=(n=o.unknownCodecs)&&n.length||s.push(o),a&&(o.iframes=!0),o}function iB(e,t){let i=e.length;if(!i){if(!t.hasProgramDateTime)return;{let r=t.fragments[t.fragments.length-1];e.push(r),i++}}let r=e[i-1],s=t.live?1/0:t.totalduration,a=Object.keys(t.dateRanges);for(let l=a.length;l--;){let o=t.dateRanges[a[l]],h=o.startDate.getTime();o.tagAnchor=r.ref;for(let r=i;r--;){var n;if((null==(n=e[r])?void 0:n.sn)<t.startSN)break;let i=function(e,t,i,r,s){let a=i[r];if(a){let l=a.programDateTime;if(t>=l||0===r){var n;if(t<=l+1e3*(((null==(n=i[r+1])?void 0:n.start)||s)-a.start)){let s=i[r].sn-e.startSN;if(s<0)return -1;let a=e.fragments;if(a.length>i.length){let n=(i[r+1]||a[a.length-1]).sn-e.startSN;for(let e=n;e>s;e--){let i=a[e].programDateTime;if(t>=i&&t<i+1e3*a[e].duration)return e}}return s}}}return -1}(t,h,e,r,s);if(-1!==i){o.tagAnchor=t.fragments[i].ref;break}}}}function iG(e,t,i){var r,s;let a=new id(e,i),n=null!=(r=a.METHOD)?r:"",l=a.URI,o=a.hexadecimalInteger("IV"),h=a.KEYFORMATVERSIONS,d=null!=(s=a.KEYFORMAT)?s:"identity";return l&&a.IV&&!o&&eo.error(`Invalid IV: ${a.IV}`),new iC(n,l?i$.resolve(l,t):"",d,(h||"1").split("/").map(Number).filter(Number.isFinite),o,a.KEYID)}function iK(e){let t=new id(e).decimalFloatingPoint("TIME-OFFSET");return d(t)?t:null}function iV(e,t){let i=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text","image"].forEach(e=>{let r=i.filter(t=>e6(t,e));r.length&&(t[`${e}Codec`]=r.map(e=>e.split("/")[0]).join(","),i=i.filter(e=>-1===r.indexOf(e)))}),t.unknownCodecs=i}function iH(e,t,i){let r=t[i];r&&(e[i]=r)}function iY(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function iW(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function ij(e,t,i){e.levelkeys=t;let{encryptedFragments:r}=i;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(e=>t[e].isCommonEncryption)&&r.push(e)}function iq(e,t,i){e.playlistParsingError=Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function iX(e,t){let i=t.startPTS;if(d(i)){let r,s=0;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&r.setDuration(s)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function iz(e,t,i,r,s,a,n,l){let o;r-i<=0&&(l.warn("Fragment should have a positive duration",t),r=i+t.duration,a=s+t.duration);let h=i,u=r,f=t.startPTS,c=t.endPTS;if(d(f)){let n=Math.abs(f-i);e&&n>e.totalduration?l.warn(`media timestamps and playlist times differ by ${n}s for level ${t.level} ${e.url}`):d(t.deltaPTS)?t.deltaPTS=Math.max(n,t.deltaPTS):t.deltaPTS=n,h=Math.max(i,f),i=Math.min(i,f),s=void 0!==t.startDTS?Math.min(s,t.startDTS):s,u=Math.min(r,c),r=Math.max(r,c),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}let g=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(r-t.start),t.startPTS=i,t.maxStartPTS=h,t.startDTS=s,t.endPTS=r,t.minEndPTS=u,t.endDTS=a;let m=t.sn;if(!e||m<e.startSN||m>e.endSN)return 0;let p=m-e.startSN,E=e.fragments;for(E[p]=t,o=p;o>0;o--)iX(E[o],E[o-1]);for(o=p;o<E.length-1;o++)iX(E[o],E[o+1]);return e.fragmentHint&&iX(E[E.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,g}function iQ(e,t,i,r,s){return Error(`${e} ${s.url} 12Playlist starting @${t.startSN} 13${t.m3u8} 14 15Playlist starting @${i.startSN} 16${i.m3u8}`)}function iZ(e,t,i=!0,r){let s=t.startSN+t.skippedSegments-e.startSN,a=e.fragments,n=s>=0,l=0;if(n&&s<a.length)l=a[s].start,null==r||r.log(`Aligning playlists based on SN ${t.startSN} (diff: ${l})`);else if(n&&t.startSN===e.endSN+1)l=e.fragmentEnd,null==r||r.log(`Aligning playlists based on first/last SN ${t.startSN} (diff: ${l})`);else if(n&&i)l=e.fragmentStart+s*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return l;l=e.fragmentStart,null==r||r.log(`Aligning playlists based on first SN ${t.startSN} (diff: ${l})`)}return function(e,t){if(t){let i=e.fragments;for(let r=e.skippedSegments;r<i.length;r++)i[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}(t,l),l}function iJ(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){let r=e.fragments;if(r.length&&4*i>t){let e=1e3*r[r.length-1].duration;e<i&&(i=e)}}else i/=2;return Math.round(i)}function i0(e,t,i){var r;if(!e)return null;let s=e.fragments[t-e.startSN];return s||(null==(r=s=e.fragmentHint)?void 0:r.sn)===t?s:i&&t<e.startSN&&i.sn===t?i:null}function i1(e,t,i){return e?i2(e.partList,t,i):null}function i2(e,t,i){if(e)for(let r=e.length;r--;){let s=e[r];if(s.index===i&&s.fragment.sn===t)return s}return null}function i4(e){e.forEach((e,t)=>{var i;
16null==(i=e.details)||i.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function i3(e){return e.replace(/\?[^?]*$/,"")}function i8(e,t){for(let r=0,s=e.length;r<s;r++){var i;if((null==(i=e[r])?void 0:i.cc)===t)return e[r]}return null}function i5(e,t){let i=e.start+t;e.setStart(i)}function i6(e,t){let i=t.fragments;for(let t=0,r=i.length;t<r;t++)i5(i[t],e);t.fragmentHint&&i5(t.fragmentHint,e),t.alignedSliding=!0}function i9(e,t,i){e&&(function(e,t,i){if(!t||!(e.startCC<t.endCC)||!(e.endCC>t.startCC))return;let r=Math.min(t.endCC,e.endCC),s=i8(t.fragments,r),a=i8(e.fragments,r);if(!s||!a)return;let n=s.start-a.start;i.log(`Aligning playlists using dicontinuity sequence ${r} (diff: ${n})`),i6(n,e)}(t,e,i),t.alignedSliding||function(e,t,i){let r,s;if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;let a=e.fragments,n=t.fragments;if(!a.length||!n.length)return;let l=Math.min(t.endCC,e.endCC);t.startCC<l&&e.startCC<l&&(r=i8(n,l),s=i8(a,l)),r&&s||(s=i8(a,(r=n[Math.floor(n.length/2)]||n.filter(e=>!!e)[0]).cc)||a[Math.floor(a.length/2)]);let o=r.programDateTime,h=s.programDateTime;if(!o||!h)return;let d=(h-o)/1e3;if(Math.abs(d)>Math.max(60,e.totalduration)){i.log(`Cannot align playlists using PDT without overlap (${Math.abs(d)} > ${e.totalduration})`);return}let u=d-(s.start-r.start);i.log(`Aligning playlists using PDT (diff: ${u})`),i6(u,e)}(t,e,i),t.alignedSliding||t.skippedSegments||iZ(e,t,!1,i))}function i7(e,t,i){re(e,t,i),e.addEventListener(t,i)}function re(e,t,i){e.removeEventListener(t,i)}function rt(e){let t="",i=e.length;for(let r=0;r<i;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t}let ri={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class rr extends t7{constructor(e,t,i,r,s){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ri.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:e,fragCurrent:t,media:i,mediaBuffer:r,state:s}=this,a=i?i.currentTime:0,n=ir.bufferInfo(r||i,a,e.maxBufferHole),l=n.len;if(this.log(`Media seeking to ${a}, state: ${s}, ${l?"in":"out of"} buffer`),this.state===ri.ENDED)this.resetLoadingState();else if(t){let i=e.maxFragLookUpTolerance,r=t.start-i,s=t.start+t.duration+i;if(!l||s<n.start||r>n.end){let e=a<r,i=a>s;(e||i)&&(t.loader&&(i||!this.isFragmentNearlyDownloaded(t))?(this.log(`Cancelling fragment load for seek (sn: ${t.sn}) - ${e?"backward":"forward"} seek`),t.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(i&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),a>this.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts)){let e=Math.max(n.end,a),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${a} with buffer @${e}`),this.loadingParts=t)}let o=!ir.isBuffered(i,a);(!this.hls.hasEnoughToStart||o)&&(this.log(`Setting ${o?"startPosition":"nextLoadPosition"} to ${a} for seek without enough to start`),this.nextLoadPosition=a,o&&(this.startPosition=a)),l<1&&this.state===ri.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=e,this.fragmentLoader=new t3(e.config),this.initFragmentLoader=new t3(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new t4(e.config)}registerListeners(){let{hls:e}=this;
16e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===ri.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=ri.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;if(-1===t&&e){let t=this.getLevelDetails();return null!=t&&t.live?(this.hls.liveSyncPosition||t.fragmentStart)+this.timelineOffset:e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;let s=e.buffered;this.config.maxBufferHole&&s&&s.length>1&&(e=ir.bufferedInfo(s,e.start,0));let a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;let n=t.partList;if(null!=n&&n.length){let e=n[n.length-1];return ir.isBuffered(this.media,e.start+e.duration/2)}let l=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(l.type)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let i=this.media=this.mediaBuffer=t.media;i7(i,"seeking",this.onMediaSeeking),i7(i,"ended",this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===ri.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;let i=!!t.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),re(r,"seeking",this.onMediaSeeking),re(r,"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(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=ri.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){this._doFragLoad(e,t,i,e=>{let t=e.frag;if(this.fragContextChanged(t)){this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)} was dropped during download.`),this.fragmentTracker.removeFragment(t);return}let i=++t.stats.chunkCount;this.log(`load progress ${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)} chunk: ${i}`),this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;let t=this.state,i=e.frag;if(this.fragContextChanged(i)){t!==ri.FRAG_LOADING&&(this.fragCurrent||t!==ri.PARSING)||(this.fragmentTracker.removeFragment(i),this.state=ri.IDLE);return}"payload"in e&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level} (bytes ${i.stats.loaded})`),this.hls.trigger(m.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e)}).catch(t=>{this.state!==ri.STOPPED&&this.state!==ri.ERROR&&(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${(null==t?void 0:t.message)||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===tq.APPENDING){let t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,r?r.len:this.config.maxBufferLength),a=this.backtrackFragment;(1==(a?e.sn-a.sn:0)||this.reduceMaxBufferLength(s,e.duration))&&i.removeFragment(e)}else(null==(t=this.mediaBuffer)?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===tq.PARTIAL&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=this.fragmentTracker,i=e.fragments[e.fragments.length-1];if(i.endList&&!t.isEndListAppended(this.playlistType)){let e=t.getPartialFragment(i.end);e&&(t.removeFragment(e),t.fragBuffered(i,!0))}t.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return(null==t?void 0:t.live)&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){e-t&&this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:t,type:i})}_loadInitSegment(e){let{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(e=>{var t;let i=e.frag;if(!this.levels||!U(i,null==(t=this.fragCurrent)?void 0:t.initSegment))throw new t9({type:c.NETWORK_E
16RROR,details:g.INTERNAL_ABORTED,error:Error("init load aborted"),fatal:!1,frag:i,networkDetails:null});return e}).then(e=>{let{frag:i,payload:r}=e,s=i.decryptdata;if(r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&ip(s.method)){let a=self.performance.now(),{decryptRange:n}=t5(i,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,iE(s.method),n).catch(e=>{throw t.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),this.fragmentLoader.abort(),e}).then(r=>{let s=self.performance.now();return t.trigger(m.FRAG_DECRYPTED,{frag:i,part:null,payload:r,stats:{tstart:a,tdecrypt:s}}),e.payload=r,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)})}completeInitSegmentLoad(e){let t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){let{initSegment:t}=e;if(!this.bitrateTest&&N(e)&&t&&!t.data){var i;return(t.encrypted&&!(null!=(i=t.decryptdata)&&i.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(t=>{if(this.state===ri.STOPPED||this.state===ri.ERROR)throw t;throw"data"in t&&(t.data.frag=e,this.fragmentLoader.abort(),this.handleFragLoadError(t)),this.resetFragmentLoading(e),t})}}unhandledEncryptionError(e,t){var i,r;let s=e.tracks;if(s&&!t.encrypted&&(null!=(i=s.audio)&&i.encrypted||null!=(r=s.video)&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let e=this.media,i=Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(i.message),!!e&&!e.mediaKeys&&(this.hls.trigger(m.ERROR,{type:c.KEY_SYSTEM_ERROR,details:g.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!U(e,t)}fragBufferedComplete(e,t){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?rt(ir.getBuffered(i)):"(detached)"})`),N(e)){var r;if(e.type!==w.SUBTITLE){let t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e])){this.state=ri.IDLE;return}}let i=null==(r=this.levels)?void 0:r[e.level];null!=i&&i.fragmentError&&(t||this.fragmentTracker.getState(e)!==tq.PARTIAL)&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0,e.stats.retry=0)}this.state=ri.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let i=e.frag,{part:r,partsLoaded:s}=e,a=!s||0===s.length||s.some(e=>!e),{decryptRange:n}=t5(i,r),l=new ie(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a,i.duration,this.iframesOnly,n);this.log(`load complete ${i.type} sn: ${i.sn}${r?" part: "+r.index:""} of ${this.fragInfo(i,!1,r)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,i){var r;let s=null;return e.encrypted&&!(null!=(r=e.decryptdata)&&r.key)?(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=ri.KEY_LOADING,s=this.keyLoader.load(e,i).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(m.KEY_LOADED,e),this.state===ri.KEY_LOADING&&(this.state=ri.IDLE),e}),this.hls.trigger(m.KEY_LOADING,{frag:e})):!e.encrypted&&(s=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested))&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`),s}_doFragLoad(e,t,i=null,r){var s,a;let n;this.fragCurrent=e;let l=t.details;if(!this.levels||!l)throw Error(`frag load aborted, missing level${l?"":" detail"}s`);let o=this.fragPrevious;if(!$(e,o)){let i=this.shouldLoadParts(t.details,e.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${e.sn}`),this.loadingParts=i)}if(i=Math.max(e.start,i||0),this.loadingParts){let s=l.partList;if(s&&r){i>l.fragmentEnd&&l.fragmentHint&&(e=l.fragmentHint);let a=this.getNextPart(s,e,i);if(a>-1){let n;let h=s[a];if(!$(e=this.fragCurrent=h.fragment,o)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,h)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(h,t.details))return Promise.resolve(null);let d=this.loadKeyFor(e,l);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${h.index} (${a}/${s.length-1}) of ${this.fragInfo(e,!1,h)} cc: ${e.cc} [${l.startSN}-${l.endSN}], target: ${i}${h.byteRange.length?` range:${h.byteRange.join("-")}`:""}`),this.nextLoadPosition=h.start+h.duration,this.state=ri.FRAG_LOADING;let u=this.loadInitSegmentIfNeeded(e);if(d||u){let i=!!d;n=Promise.all([d,u]).then(([s])=>i&&(!s||this.fragContextChanged(s.frag))?null:this.doFragPartsLoad(e,h,t,r)).catch(e=>this.handleFragLoadError(e))}else n=this.doFragPartsLoad(e,h,t,r).catch(e=>this.handleFragLoadError(e));return(this.hls.trigger(m.FRAG_LOADING,{frag:e,part:h,targetBufferTime:i}),null===this.fragCurrent)?Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING parts")):n}if(!e.url||this.loadedEndOfParts(s,i))return Promise.resolve(null)}}if(this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i} Check buffer at sn: ${e.sn} loaded parts: ${null==(s=l.partList)?void 0:s.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);let h=this.loadInitSegmentIfNeeded(e),u=this.loadKeyFor(e,l,h);if(this.fragContextChanged(e))return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${null==(a=this.fragCurrent)?void 0:a.relurl}`),null==h||h.catch(()=>null),null==u||u.catch(()=>null),Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+l.startSN+"-"+l.endSN+"]"}, target: ${i}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),d(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=ri.FRAG_LOADING;let f=this.config.progressive&&e.type!==w.SUBTITLE;return(n=f&&u?u.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,r,h)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,this.iframesOnly,f?r:void 0,f?h:void 0),u,h]).then(([e])=>(!f&&r&&r(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent)?Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([n,h]).then(([e])=>e)}doFragPartsLoad(e,t,i,r){return new Promise((s,a)=>{var n;let l=[],o=null==(n=i.details)?void 0:n.partList,h=t=>{this.fragmentLoader.loadPart(e,t,r).then(r=>{l[t.index]=r;let a=r.part;this.hls.trigger(m.FRAG_LOADED,r);let n=i1(i.details,e.sn,t.index+1)||i2(o,e.sn,t.index+1);if(!n)return s({frag:e,part:a,partsLoaded:l});h(n)}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===g.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===c.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:c.OTHER_ERROR,details:g.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==ri.PARSING){this.fragCurrent||this.state===ri.STOPPED||this.state===ri.ERROR||(this.state=ri.IDLE);return}let{frag:i,part:r,level:s}=t,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let n=this.getLevelDetails(),l=n&&i.sn>n.endSN||this.shouldLoadParts(n,i.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${i.end}`),this.loadingParts=l),this.updateLevelTiming(i,r,s,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var i;let r=e.partList[0];if(t>=r.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)&&this.playhead>r.start-r.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:r,sn:s,part:a}=e;if(!(null!=t&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let n=t[r],l=n.details,o=a>-1?i1(l,s,a):null,h=o?o.fragment:i0(l,s,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:o,level:n}):null}bufferFragmentData(e,t,i,r,s){if(this.state!==ri.PARSING)return;N(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);let{data1:a,data2:n}=e,l=a;if(n&&(l=eX(a,n)),!l.length)return;let o=this.initPTS[t.cc],h=o?-o.baseTime/o.timescale:void 0,d={type:e.type,frag:t,part:i,chunkMeta:r,offset:h,parent:t.type,data:l};if(this.hls.trigger(m.BUFFER_APPENDING,d),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!ir.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let i=t.currentTime,r=ir.bufferInfo(t,i,0),s=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),n=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-n>a&&this.flushMainBuffer(n,e.start)}getFwdBufferInfo(e,t){var i;let r=this.playhead,s=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,s)}getFwdBufferInfoAtPos(e,t,i,r){let s=ir.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(s.nextStart<=a.end||a.gap)){let i=Math.max(Math.min(s.nextStart,a.end)-t,r);return ir.bufferInfo(e,t,i)}}return s}
16getMaxBufferLength(e){let{config:t}=this;return Math.min(e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){let r=e.nextStart;if(r&&i.start>r){let r=e.buffered;if(r){let s=e.len,a=e.bufferedIndex;for(let e=r.length-1;e>a;e--)r[e].start<i.start&&(s+=r[e].end-r[e].start);return s>=t}}return!1}reduceMaxBufferLength(e,t){let i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t/2),s=Math.max(e-3*t,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0)}getAppendedFrag(e){let t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}getNextFragment(e,t){let i=t.fragments,r=i.length;if(!r)return null;let{config:s}=this,a=t.fragmentStart,n=s.lowLatencyMode&&!!t.partList,l=null;if(t.live){let i=s.initialLiveManifestSize;if(r<i)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${i})`),null;if(this.startFragRequested||!n||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a){var o;let i,r;l=this.getInitialLiveFragment(t);let s=this.config.startPosition,n=this.hls.startPosition,h=this.hls.liveSyncPosition,d=(null==(o=l)?void 0:o.start)||0;if(-1!==n&&n>=a?(i=n,r=n===s?"config":"next load start"):h?(i=h,r="live edge"):(i=e,r="buffer pos"),i<d&&(i=d,r="live frag start"),i<a&&(i=a,r="playlist start"),this.startPosition!=i||this.nextLoadPosition!=i){let o=t.live&&!this.filterReplacedPrimary(l,t)?-1:i;this.log(`Setting startPosition to ${o} next load ${i} ${-1===n?"":`(from ${s}) `}based on ${r}. live edge: ${h} live frag start: ${d} playlist start: ${a} buffer pos: ${e}`),this.startPosition=o,this.nextLoadPosition=i}}}else e<=a&&(l=i[0]);if(!l){let i=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,i,t)}let h=this.filterReplacedPrimary(l,t);return!h&&l&&(h=tG(t,l.sn,this.loadingParts))&&(this.nextLoadPosition=h.start),h}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let i=this.fragmentTracker.getState(e);return i===tq.OK||i===tq.PARTIAL&&(!!e.gap||e.stats.retry>1)}getNextFragmentLoopLoading(e,t,i,r,s){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&i.nextStart){let e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==e&&i.len+e.len>=s){let e=a.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(ra(this.config)){var e;if(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(ra(this.config)&&("type"in e?e:e.fragment).type!==w.SUBTITLE){let i=this.hls.interstitialsManager,r=null==i?void 0:i.bufferingItem;if(r){let i=r.event;if(i){if(!i.appendInPlace&&(Math.abs(e.start-r.start)>1||0===r.start))return null}else if(e.end<=r.start&&(null==t?void 0:t.live)===!1||e.start>=r.end&&r.nextEvent&&(r.nextEvent.appendInPlace&&!r.nextEvent.hasPlayed||e.start-r.end>1))return null}if(rs(e,null==i?void 0:i.playerQueue,this.playhead))return null}return e}getNextPart(e,t,i){let r=-1,s=!1,a=!0;for(let n=0,l=e.length;n<l;n++){let l=e[n];if(a=a&&!l.independent,r>-1&&i<l.start)break;let o=l.loaded||l.gap;o?r=-1:(s||(l.independent||a)&&l.fragment===t)&&(r=n),s=o&&!l.gap}let n=e[r];return n&&n.fragment!==t&&this.log(`Need buffer at ${i} but next unloaded part starts at ${n.start} (sn: ${t.sn} -> ${n.fragment.sn})`),r}loadedEndOfParts(e,t){let i;for(let r=e.length;r--&&(i=e[r]).loaded;)if(t>i.start)return!0;return!1}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!d(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let r=0;r<e.length;++r){let s=e[r];if(function(e,t,i){let r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}(t,i,s))return s}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance))&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),!r){let s=i.sn+1;if(s>=e.startSN&&s<=e.endSN){let a=t[s-e.startSN];i.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}!r&&(r=tB(e,i.cc,i.end))&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`)}}else{let t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){let r;let{config:s}=this,{fragPrevious:a}=this,{fragments:n,endSN:l}=i,{fragmentHint:o}=i,{maxFragLookUpTolerance:h}=s,d=i.partList,u=!!(this.loadingParts&&null!=d&&d.length&&o);if(u&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),l=o.sn),a&&this.fragmentTracker.getState(a)===tq.NOT_LOADED&&(a=null),e<t){var f;let i=e<this.lastCurrentTime||e>t-h||null!=(f=this.media)&&f.paused||!this.startFragRequested?0:h;r=t$(a,n,e,i)}else r=n[n.length-1];if(r){let e=r.sn-i.startSN,t=this.fragmentTracker.getState(r);
16if((t===tq.OK||t===tq.PARTIAL&&r.gap)&&(a=r),$(r,a)&&(!u||d[0].fragment.sn>r.sn||!i.live)){let t=n[e+1];r=r.sn<l&&this.fragmentTracker.getState(t)!==tq.OK?t:null}}return r}alignPlaylists(e,t,i){let r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;let s=e.fragmentStart,a=e.alignedSliding&&d(s);if(!t||!a&&!s){i9(i,e,this);let s=e.fragmentStart;return this.log(`Live playlist sliding: ${s} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),s}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);let r=this.timelineOffset;if(-1===i){let s=null!==this.startTimeOffset,a=s?this.startTimeOffset:e.startTimeOffset;if(null!==a&&d(a))i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${s?"multivariant":"media"} playlist`),this.startPosition=i;else if(e.live){let e=this.hls.liveSyncPosition;i=e||t,this.log(`Setting startPosition to -1 to start at ${e?"live edge":"playlist start"} ${i}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=i=0;this.lastCurrentTime=i+r}this.nextLoadPosition=i+r}getLoadPosition(){var e;let{media:t}=this,i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t&&!this.iframesOnly?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}get playhead(){var e,t;if(null!=(e=this.hls)&&e.hasEnoughToStart){let e=null==(t=this.media)?void 0:t.currentTime;return d(e)?e:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==w.MAIN)return!1;let t=this.getLevelDetails();return t?t.iframesOnly:null==(e=this.levelLastLoaded)?void 0:e.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&N(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===ri.FRAG_LOADING_WAITING_RETRY)||(this.state=ri.IDLE)}onFragmentOrKeyLoadError(e,t){var i,r;if(t.chunkMeta&&!t.frag){let e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}let{frag:s,part:a}=t;if(!s||!this.levels||s.type!==e)return;if(this.fragContextChanged(s)){this.warn(`Frag load error must match current frag to retry ${s.relurl} > ${null==(i=this.fragCurrent)?void 0:i.relurl}`);return}let n=t.details===g.FRAG_GAP;n&&this.fragmentTracker.addAsGap(s);let l=t.errorAction;if(!l){this.state=ri.ERROR;return}let{action:o,flags:h,retryCount:d=0,retryConfig:u}=l,f=!!u,c=f&&o===tK.RetryRequest,m=f&&!l.resolved&&h&tV.MoveAllAlternatesMatchingHost,p=this.hls.latestLevelDetails,E=null==p?void 0:p.live;if(!c&&m&&N(s)&&E&&s.sn<p.endSN&&!q(t))this.resetFragmentErrors(e),a?a.gap=!0:this.treatAsGap(s),l.resolved=!0;else if((c||m)&&d<u.maxNumRetry){let i=J(null==(r=t.response)?void 0:r.code),a=z(u,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+a,this.state=ri.FRAG_LOADING_WAITING_RETRY,l.resolved=!0,i){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${d+1}/${u.maxNumRetry} in ${a}ms`)}else if(u){if(this.resetFragmentErrors(e),d<u.maxNumRetry)n||o===tK.RemoveAlternatePermanently||(l.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${d})`);return}}else o===tK.SendAlternateToPenaltyBox?this.state=ri.WAITING_LEVEL:this.state=ri.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!J(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=ri.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===ri.PARSING||this.state===ri.PARSED){let t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,(null==t?void 0:t.duration)||10);let a=!s;return a?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${i} buffer`):r.nextStart&&t&&r.nextStart>t.start&&this.flushMainBuffer(r.nextStart,Number.POSITIVE_INFINITY,i===w.AUDIO?i:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===w.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==ri.STOPPED&&(this.state=ri.IDLE)}afterBufferFlushed(e,t){if(!e)return;let i=ir.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,this.playlistType),this.state===ri.ENDED&&this.resetLoadingState()}
vendor: 1,397 bytes, line 16
16resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==ri.STOPPED&&(this.state=ri.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.getLevelDetails();null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){let s=i.details;if(!s){this.warn("level.details undefined");return}if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((t,a)=>{let n=e.elementaryStreams[a];if(n){let l=n.endPTS-n.startPTS;if(l<=0)return this.warn(`Could not parse fragment ${e.sn} ${a} duration reliably (${l})`),t||!1;let o=r.partial?0:iz(s,e,n.startPTS,n.endPTS,n.startDTS,n.endDTS,this.iframesOnly,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:s,level:i,drift:
16o,type:a,frag:e,start:n.startPTS,end:n.endPTS}),!0}return t},!1)){var a,n,l,o;let r=(null==(a=this.transmuxer)?void 0:a.error)===null,s=(null==(n=this.transmuxer)?void 0:n.error)!=null,h=(null!=(l=null==(o=this.levels)?void 0:o.length)?l:0)>1;if((0===i.fragmentError||r&&(i.fragmentError<2||e.endList)||s&&h)&&this.treatAsGap(e,i),r){let r=Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(r.message),this.hls.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.FRAG_PARSING_ERROR,fatal:!1,error:r,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=ri.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(m.FRAG_PARSED,{frag:e,part:t,chunkMeta:r})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,i){var r,s;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${null!=(r=t&&!i?e.startPTS:(i||e).start)?r:NaN}-${null!=(s=t&&!i?e.endPTS:(i||e).end)?s:NaN}]${i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}isFragmentNearlyDownloaded(e){var t;let i=null==(t=e.loader)?void 0:t.stats;if(!i)return!1;let r=i.loading.first>0,s=(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return r&&s<=.15}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let i=0,{hls:r,media:s,config:a,levels:n,playlistType:l}=this,o=this.getLevelDetails();if(s&&!s.paused&&n){var h;let t=l===w.AUDIO?tg(e.audioCodec,128e3):e.maxBitrate,s=1+r.ttfbEstimate/1e3,n=r.bandwidthEstimate*a.abrBandWidthUpFactor;i=s+t*(o&&(this.loadingParts?o.partTarget:o.averagetargetduration)||(null==(h=this.fragCurrent)?void 0:h.duration)||6)/n,e.details||(i+=s)}let d=this.playhead,u=!(null!=o&&o.live)||t.end-d>1.5*i;return{fetchdelay:i,okToFlushForwardBuffer:u}}scheduleTrackSwitch(e,t,i){let{media:r,playlistType:s}=this;if(!r||!e)return;let a=i?this.getBufferedFrag(this.playhead+t):null;if(a){let e=this.followingBufferedFrag(a);if(e){var n;this.abortCurrentFrag();let t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,r=Math.max(a.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));if(((null==(n=this.getLevelDetails())?void 0:n.fragmentStart)||0)>r)return;let l=s===w.MAIN?null:"audio";this.flushMainBuffer(r,Number.POSITIVE_INFINITY,l),this.cleanupBackBuffer()}}}cleanupBackBuffer(){let{media:e,playlistType:t}=this;if(!e)return;let i=this.getAppendedFrag(this.playhead);if(i&&i.start>1){let e=t===w.AUDIO;this.flushMainBuffer(0,i.start-(e?0:1),e?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case ri.KEY_LOADING:case ri.FRAG_LOADING:case ri.FRAG_LOADING_WAITING_RETRY:case ri.PARSING:case ri.PARSED:this.state=ri.IDLE}this.nextLoadPosition=this.playhead}checkFragPlaying(){let e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){let i=e.currentTime;if(ir.isBuffered(e,i)?t=this.getAppendedFrag(i):ir.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t&&(this.backtrackFragment=void 0,!$(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){let{levels:e,media:t,hls:i,config:r,playlistType:s}=this;if(null!=t&&t.readyState&&e&&i&&r){let t=this.getBufferOutput(),r=this.getFwdBufferInfo(t,s);if(!r)return;let a=e[s===w.AUDIO?i.nextAudioTrack:i.nextLoadLevel],{fetchdelay:n,okToFlushForwardBuffer:l}=this.calculateOptimalSwitchPoint(a,r);this.scheduleTrackSwitch(r,n,l)}this.tickImmediate()}}function rs(e,t,i){if(t)for(let r=t.length;r--;){let s=t[r].interstitial,a=s.startTime,n=Math.min(a+s.duration,s.resumeTime);if(s.appendInPlace&&(e.start>=a&&e.end<=n||i>e.start&&e.end>a&&e.start<n))return!0}return!1}function ra(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class rn{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let e;let{chunks:t,dataLength:i}=this;return t.length?(e=1===t.length?t[0]:function(e,t){let i=new Uint8Array(t),r=0;for(let t=0;t<e.length;t++){let s=e[t];i.set(s,r),r+=s.length}return i}(t,i),this.reset(),e):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var rl={exports:{}},ro=(P||(P=1,function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function s(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,r,a,n){if("function"!=typeof r)throw TypeError("The listener must be a function");
16var l=new s(r,a||e,n),o=i?i+t:t;return e._events[o]?e._events[o].fn?e._events[o]=[e._events[o],l]:e._events[o].push(l):(e._events[o]=l,e._eventsCount++),e}function n(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function l(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(i=!1)),l.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},l.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,a=r.length,n=Array(a);s<a;s++)n[s]=r[s].fn;return n},l.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},l.prototype.emit=function(e,t,r,s,a,n){var l=i?i+e:e;if(!this._events[l])return!1;var o,h,d=this._events[l],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,s),!0;case 5:return d.fn.call(d.context,t,r,s,a),!0;case 6:return d.fn.call(d.context,t,r,s,a,n),!0}for(h=1,o=Array(u-1);h<u;h++)o[h-1]=arguments[h];d.fn.apply(d.context,o)}else{var f,c=d.length;for(h=0;h<c;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),u){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,t);break;case 3:d[h].fn.call(d[h].context,t,r);break;case 4:d[h].fn.call(d[h].context,t,r,s);break;default:if(!o)for(f=1,o=Array(u-1);f<u;f++)o[f-1]=arguments[f];d[h].fn.apply(d[h].context,o)}}return!0},l.prototype.on=function(e,t,i){return a(this,e,t,i,!1)},l.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},l.prototype.removeListener=function(e,t,r,s){var a=i?i+e:e;if(!this._events[a])return this;if(!t)return n(this,a),this;var l=this._events[a];if(l.fn)l.fn!==t||s&&!l.once||r&&l.context!==r||n(this,a);else{for(var o=0,h=[],d=l.length;o<d;o++)(l[o].fn!==t||s&&!l[o].once||r&&l[o].context!==r)&&h.push(l[o]);h.length?this._events[a]=1===h.length?h[0]:h:n(this,a)}return this},l.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&n(this,t)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=i,l.EventEmitter=l,e.exports=l}(rl)),(A=rl.exports)&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default"))?A.default:A;let rh="1.7.0",rd={};function ru(e,t){return 255===e[t]&&(246&e[t+1])==240}function rf(e,t){return 1&e[t+1]?7:9}function rc(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function rg(e,t){return t+1<e.length&&ru(e,t)}function rm(e,t,i,r,s){if(!e.samplerate){let a=function(e,t,i,r){let s;let a=t[i+2],n=a>>2&15;if(n>12){let t=Error(`invalid ADTS sampling index:${n}`);e.emit(m.ERROR,m.ERROR,{type:c.MEDIA_ERROR,details:g.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message});return}let l=(a>>6&3)+1,o=t[i+3]>>6&3|(1&a)<<2,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][n],d=n;(5===l||29===l)&&(d-=3);let u=(14&d)>>1,f=(1&d)<<7|o<<3,p=0;if(1===l&&n>=6){let e=n-3;s=[(p=5)<<3|u,f|(14&e)>>1,(1&e)<<7|8,0]}else s=[l<<3|u,f];let E="mp4a.40."+(p||l);return eo.log(`manifest codec:${r}, parsed codec:${E}, channels:${o}, rate:${h} (ADTS object type:${l} sampling index:${n} esds config:[${s.join(",")}])`),{config:s,samplerate:h,channelCount:o,codec:E,parsedCodec:E,manifestCodec:r}}(t,i,r,s);a&&K(e,a)}}function rp(e,t,i,r,s){let a;let n=r+9216e4/e.samplerate*s,l=function(e,t){let i=rf(e,t);if(t+i<=e.length){let r=rc(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);if(l){let{frameLength:r,headerLength:s}=l,o=s+r,h=Math.max(0,i+o-t.length);h?(a=new Uint8Array(o-s)).set(t.subarray(i+s,t.length),0):a=t.subarray(i+s,i+o);let d={unit:a,pts:n};return h||e.samples.push(d),{sample:d,length:o,missing:h}}let o=t.length-i;return(a=new Uint8Array(o)).set(t.subarray(i,t.length),0),{sample:{unit:a,pts:n},length:o,missing:-1}}let rE=((I={}).audioId3="org.id3",I.dateRange="com.apple.quicktime.HLS",I.emsg="https://aomedia.org/emsg/ID3",I.misbklv="urn:misb:KLV:bin:1910.1",I);function rv(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class ry{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){let i;this.cachedData&&(e=eX(this.cachedData,e),this.cachedData=null);let r=ey(e,0),s=r?r.length:0,a=this._audioTrack,n=this._id3Track,l=r?eL(r):void 0,o=e.length;for((null===this.basePTS||0===this.frameIndex&&d(l))&&(this.basePTS=rT(l,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&n.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:rE.audioId3,duration:Number.POSITIVE_INFINITY});s<o;){if(this.canParse(e,s)){let t=this.appendFrame(a,e,s);t?(this.frameIndex++,this.lastPTS=t.sample.pts,s+=t.length,i=s):s=o}else{var h,u;ep(h=e,u=s)&&eE(h,u+6)+10<=h.length-u?(r=ey(e,s),n.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:rE.audioId3,duration:Number.POSITIVE_INFINITY}),s+=r.length,i=s):s++}if(s===o&&i!==o){let t=e.slice(i);this.cachedData?this.cachedData=eX(this.cachedData,t):this.cachedData=t}}return{audioTrack:a,videoTrack:rv(),id3Track:n,textTrack:rv()}}demuxSampleAes(e,t,i){return Promise.reject(Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:rv(),id3Track:this._id3Track,textTrack:rv()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}let rT=(e,t,i)=>d(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0),rS=[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],rA=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],rI=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],rL=[0,1,1,4];function rR(e,t,i,r,s){if(i+24>t.length)return;let a=rb(t,i);if(a&&i+a.frameLength<=t.length){let n=r+9e4*a.samplesPerFrame/a.sampleRate*s,l={unit:t.subarray(i,i+a.frameLength),pts:n,dts:n};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(l),{sample:l,length:a.frameLength,missing:0}}}function rb(e,t){let i=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==a){let n=e[t+2]>>1&1,l=e[t+3]>>6,o=1e3*rS[14*(3===i?3-r:3===r?3:4)+s-1],h=rA[3*(3===i?0:2===i?1:2)+a],d=rI[i][r],u=rL[r],f=Math.floor(d*o/h+n)*u,c=e3();return c&&c<=87&&2===r&&o>=224e3&&0===l&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:3===l?1:2,frameLength:f,samplesPerFrame:8*d*u}}}
16function rD(e,t){return 255===e[t]&&(224&e[t+1])==224&&(6&e[t+1])!=0}function rk(e,t){return t+1<e.length&&rD(e,t)}function rP(e,t){if(t+1<e.length&&rD(e,t)){let i=rb(e,t),r=4;null!=i&&i.frameLength&&(r=i.frameLength);let s=t+r;return s===e.length||rk(e,s)}return!1}class r_{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new t4(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,tJ.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,i){let r=e[t].unit;if(r.length<=16)return;let s=r.subarray(16,r.length-r.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(a).then(s=>{let a=new Uint8Array(s);r.set(a,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=new Int8Array(16*Math.floor((e.length-48)/160)+16),i=0;for(let r=32;r<e.length-16;r+=160,i+=16)t.set(e.subarray(r,r+16),i);return t}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(i.subarray(r,r+16),t);return e}decryptAvcSample(e,t,i,r,s){let a=eJ(s.data),n=this.getAvcEncryptedData(a);this.decryptBuffer(n.buffer).then(n=>{s.data=this.getAvcDecryptedUnit(a,n),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)}).catch(r)}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){r();return}let s=e[t].units;for(;!(i>=s.length);i++){let a=s[i];if(!(a.data.length<=48)&&(1===a.type||5===a.type)&&(this.decryptAvcSample(e,t,i,r,a),!this.decrypter.isSync()))return}}}}class rC extends ry{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let i=ey(e,0),r=(null==i?void 0:i.length)||0;if(rP(e,r))return!1;for(let i=e.length;r<i;r++)if(function(e,t){if(rg(e,t)){let i=rf(e,t);if(t+i>=e.length)return!1;let r=rc(e,t);if(r<=i)return!1;let s=t+r;return s===e.length||rg(e,s)}return!1}(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return t+5<e.length&&ru(e,t)&&rc(e,t)<=e.length-t}appendFrame(e,t,i){rm(e,this.observer,t,i,e.manifestCodec);let r=rp(e,t,i,this.basePTS,this.frameIndex);if((null==r?void 0:r.missing)===0)return r}demuxSampleAes(e,t,i){let r=this.demux(e,i),s=this.sampleAes=new r_(this.observer,this.config,t);return new Promise(e=>{s.decryptAacSamples(r.audioTrack.samples,0,()=>{e(r)})})}}let rO=(e,t)=>{let i=0,r=5;t+=5;let s=new Uint32Array(1),a=new Uint32Array(1),n=new Uint8Array(1);for(;r>0;){n[0]=e[t];let l=Math.min(r,8),o=8-l;a[0]=4278190080>>>24+o<<o,s[0]=(n[0]&a[0])>>o,i=i?i<<l|s[0]:s[0],t+=1,r-=l}return i};class rM extends ry{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){let r=rw(e,t,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;let t=ey(e,0);if(!t)return!1;let i=t.length;if(11===e[i]&&119===e[i+1]&&void 0!==eL(t)){if(16>rO(e,i))return!0;throw Error("Containerless ec-3 is not supported")}return!1}}function rw(e,t,i,r,s){if(i+8>t.length||11!==t[i]||119!==t[i+1])return -1;let a=t[i+4]>>6;if(a>=3)return -1;let n=[48e3,44100,32e3][a],l=63&t[i+4],o=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*l+a];if(i+o>t.length)return -1;let h=t[i+6]>>5,d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));let u=(t[i+6]<<8|t[i+7])>>12-d&1,f=[2,1,2,3,3,4,4,5][h]+u,c=t[i+5]>>3,g=7&t[i+5],m=new Uint8Array([a<<6|c<<1|g>>2,(3&g)<<6|h<<3|u<<2|l>>4,l<<4&224]),p=t.subarray(i,i+o);return e.config=m,e.channelCount=f,e.samplerate=n,e.samples.push({unit:p,pts:r+1536/n*9e4*s}),o}class rF extends ry{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=ey(e,0),i=(null==t?void 0:t.length)||0;
16if(t&&11===e[i]&&119===e[i+1]&&void 0!==eL(t)&&16>=rO(e,i))return!1;for(let t=e.length;i<t;i++)if(rP(e,i))return eo.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return rD(e,t)&&4<=e.length-t}appendFrame(e,t,i){if(null!==this.basePTS)return rR(e,t,i,this.basePTS,this.frameIndex)}}let rx=/\/emsg[-/]ID3/i;class rN{constructor(e,t,i,r=eo){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=t,this.logger=r}resetTimeStamp(){}resetInitSegment(e,t,i,r){let s=this.videoTrack=rv("video",1),a=this.audioTrack=rv("audio",1),n=this.txtTrack=rv("text",1);if(this.id3Track=rv("id3",1),this.initData=void 0,this.timeOffset=0,!(null!=e&&e.byteLength))return;let l=this.initData=eG(e);if(l.video){let{id:e,timescale:t,codec:i,supplemental:r}=l.video;s.id=e,s.timescale=n.timescale=t,s.codec=i,s.supplemental=r}if(l.audio){let{id:e,timescale:t,codec:i}=l.audio;a.id=e,a.timescale=t,a.codec=i}n.id=e_.text,s.sampleDuration=0,s.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return function(e,t){let i=e.byteLength;for(let r=0;r<i;){let s=eO(e,r);if(s>8&&eO(e,r+4)===eP[t])return!0;r=s>1?r+s:i}return!1}(e,"moof")}demux(e,t,i){this.timeOffset=t;let r=e,s=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=eX(this.remainderData,e));let t=function(e){let t={valid:null,remainder:null},i=eB(e,["moof"]);if(i.length<2)return t.remainder=e,t;let r=i[i.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}(r);this.remainderData=t.remainder,s.samples=t.valid||new Uint8Array}else s.samples=r;let n=this.extractID3Track(s,t),l=this.parseFragment(s,a,t,i);return{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){let i=this.timeOffset,r=this.videoTrack,s=this.txtTrack;r.samples=this.remainderData||new Uint8Array,this.remainderData=null;let a=this.extractID3Track(r,this.timeOffset),n=this.parseFragment(r,s,i,t);return{videoTrack:r,audioTrack:rv(),id3Track:a,textTrack:rv(),initData:this.initData,sampleData:n}}parseFragment(e,t,i,r){let s=this.initData;if(s&&r){let{samples:a,sampleData:n}=function(e,t,i,r,s=!1){let a=[],n=eq(t.samples,i,r,s,{isHEVCFlavor:ez(t.codec),samples:a,timeOffset:e,timescale:t.timescale,trackId:t.id});return{samples:a,sampleData:{includeSampleDetails:s,tracks:n}}}(i,e,s,this.logger,r.iframe);return t.samples=a,n}t.samples=function(e,t){let i=[],r=t.samples,s=t.timescale,a=t.id,n=!1;
16return eB(r,["moof"]).map(l=>{let o=l.byteOffset-8;eB(l,["traf"]).map(l=>{let h=eB(l,["tfdt"]).map(e=>{let t=e[0],i=eO(e,4);return 1===t&&(i*=4294967296,i+=eO(e,8)),i/s})[0];return void 0!==h&&(e=h),eB(l,["tfhd"]).map(h=>{let d=eO(h,4),u=16777215&eO(h,0),f=(1&u)!=0,c=0,g=0,m=0,p=8;d===a&&(f?(c=eO(h,p),p+=4,c*=4294967296,c+=eO(h,p),p+=4):f||(131072&u)==0||(c=o),(2&u)!=0&&(p+=4),(8&u)!=0&&(g=eO(h,p),p+=4),(16&u)!=0&&(m=eO(h,p),p+=4),(32&u)!=0&&(p+=4),"video"===t.type&&(n=ez(t.codec)),eB(l,["trun"]).map(a=>{let l=a[0],o=16777215&eO(a,0),h=0,d=(256&o)!=0,u=0,f=(512&o)!=0,p=0,E=(1024&o)!=0,v=(2048&o)!=0,y=0,T=eO(a,4),S=8;(1&o)!=0&&(h=eO(a,S),S+=4),(4&o)!=0&&(S+=4);let A=c+h;for(let o=0;o<T;o++){if(d?(u=eO(a,S),S+=4):u=g,f?(p=eO(a,S),S+=4):p=m,E&&(S+=4),v&&(y=0===l?eO(a,S):eF(a,S),S+=4),t.type===F.VIDEO){let t=0;for(;t<p;){let a=eO(r,A);A+=4,eQ(n,r[A])&&eZ(r.subarray(A,A+a),n?2:1,e+y/s,i),A+=a,t+=a+4}}e+=u/s}}))})})}),i}(i,e)}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let r=eB(e.samples,["emsg"]);r&&r.forEach(e=>{let r=function(e){let t;let i=e[0],r="",s="",a=0,n=0,l=0,o=0,h=4;if(0===i){let t=ew(e,h),i=null!==t?ew(e,h+t.length):null;null!==t&&null!==i?(r=t,s=i,h+=t.length+i.length,a=eO(e,h),h+=4,n=eO(e,h),h+=4,l=eO(e,h),h+=4,o=eO(e,h),h+=4):(eo.warn(`Unterminated ${null===t?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),h=e.length)}else if(1===i){a=eO(e,h);let i=eO(e,h+=4),n=eO(e,h+=4);h+=4,u(t=4294967296*i+n)||(t=Number.MAX_SAFE_INTEGER,eo.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=eO(e,h),h+=4,o=eO(e,h);let d=ew(e,h+=4),f=null!==d?ew(e,h+d.length):null;null!==d&&(r=d,h+=d.length),null!==f?(s=f,h+=f.length):(eo.warn(`Unterminated ${null===d?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${null===d?"strings and payload":"value and payload"}`),h=e.length)}return{schemeIdUri:r,value:s,timeScale:a,presentationTime:t,presentationTimeDelta:n,eventDuration:l,id:o,payload:e.subarray(h,e.byteLength)}}(e);if(rx.test(r.schemeIdUri)){let e=r$(r,t),s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);let a=r.payload;i.samples.push({data:a,len:a.byteLength,dts:e,pts:e,type:rE.emsg,duration:s})}else if(this.config.enableEmsgKLVMetadata){let e=this.config.emsgKLVSchemaUri||rE.misbklv;if(r.schemeIdUri.startsWith(e)){let e=r$(r,t);i.samples.push({data:r.payload,len:r.payload.byteLength,dts:e,pts:e,type:rE.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return i}demuxSampleAes(e,t,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 r$(e,t){return d(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class rU{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i;let r=this.VideoSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){let e=r.units;i=e[e.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){let i=t.samples,r=i.length;if(r){let t=i[r-1];e.pts=t.pts,e.dts=t.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,i){let r=t.byteLength;if(0===r)return[];let s=e.naluState||0,a=-1===s?0:s,n=[],l=0,o=0,h=-1,d=0;for(-1===s&&(h=0,d=this.getNALuType(t,0),o=1);o<r;){let i=t.indexOf(1,o);if(-1===i)break;o=i+1;let s=i;for(;s>0&&0===t[s-1];)s--;if(!(i-s+(0===s?a:0)<2)){if(h>=0)n.push({data:t.subarray(h,s),type:d});else{let i=this.getLastNalUnit(e.samples);i&&(s>0?i.data=eX(i.data,t.subarray(0,s)):a>0&&(i.data=i.data.subarray(0,i.data.byteLength-a)),i.state=0)}if(o<r)h=o,d=this.getNALuType(t,o);else{l=-1,h=-1;break}}}if(-1!==l){let e=r;for(;e>0&&0===t[e-1];)e--;l=r-e+(0===e?a:0)}if(h>=0)n.push({data:t.subarray(h),type:d,state:l});else if(0===n.length&&-1!==l){let i=this.getLastNalUnit(e.samples);i&&(i.data=eX(i.data,t),i.state=l)}return e.naluState=l,n}}class rB{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw Error("no bytes available");r.set(e.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e||(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord()),this.word<<=e,this.bitsAvailable-=e}readBits(e){let t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&eo.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw Error("no bits available");return(t=e-t)>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!=0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}}class rG extends rU{parsePES(e,t,i,r,s){let a;let n=s.iframe,l=this.parseNALu(e,i.data,r),o=this.VideoSample,h=!1;i.data=null,o&&l.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),l.forEach(r=>{var s,l,d,u,f;switch(r.type){case 1:{if(n)break;let t=!1;a=!0;let s=r.data;if(h&&s.length>4){let e=this.readSliceType(s);(2===e||4===e||7===e||9===e)&&(t=!0)}t&&null!=(d=o)&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.frame=!0,o.key=t;break}case 5:a=!0,null!=(s=o)&&s.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),o.key=!0,o.frame=!0;break;case 6:if(n)break;a=!0,eZ(r.data,1,i.pts,t.samples);break;case 7:{a=!0,h=!0;let t=r.data,i=this.readSPS(t);if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(u=e.pixelRatio)?void 0:u[0])!==i.pixelRatio[0]||(null==(f=e.pixelRatio)?void 0:f[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t];let r=t.subarray(1,4),s="avc1.";for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t="0"+t),s+=t}e.codec=s}break}case 8:a=!0,e.pps=[r.data];break;case 9:a=!0,e.audFound=!0,null!=(l=o)&&l.frame&&(this.pushAccessUnit(o,e),o=null),o||(o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:a=!0;break;default:a=!1}o&&a&&o.units.push(r)}),r&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}
16getNALuType(e,t){return 31&e[t]}readSliceType(e){let t=new rB(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,r=8;for(let s=0;s<e;s++)0!==r&&(r=(i+t.readEG()+256)%256),i=0===r?i:r}readSPS(e){let t,i,r;let s=new rB(e),a=0,n=0,l=0,o=0,h=s.readUByte.bind(s),d=s.readBits.bind(s),u=s.readUEG.bind(s),f=s.readBoolean.bind(s),c=s.skipBits.bind(s),g=s.skipEG.bind(s),m=s.skipUEG.bind(s),p=this.skipScalingList.bind(this);h();let E=h();if(d(5),c(3),h(),m(),100===E||110===E||122===E||244===E||44===E||83===E||86===E||118===E||128===E){let e=u();if(3===e&&c(1),m(),m(),c(1),f())for(r=0,i=3!==e?8:12;r<i;r++)f()&&p(r<6?16:64,s)}m();let v=u();if(0===v)u();else if(1===v)for(c(1),g(),g(),t=u(),r=0;r<t;r++)g();m(),c(1);let y=u(),T=u(),S=d(1);0===S&&c(1),c(1),f()&&(a=u(),n=u(),l=u(),o=u());let A=[1,1];if(f()&&f())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:A=[h()<<8|h(),h()<<8|h()]}return{width:Math.ceil((y+1)*16-2*a-2*n),height:(2-S)*(T+1)*16-(S?2:4)*(l+o),pixelRatio:A}}}class rK extends rU{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,r){let s;let a=this.parseNALu(e,i.data,r),n=this.VideoSample,l=!1;i.data=null;let o=e=>n=this.VideoSample=this.createVideoSample(e,i.pts,i.dts);a.forEach((r,a)=>{var h,d,u;switch(this.startsNewAccessUnit(n,e,r,a)&&(this.pushAccessUnit(n,e),n=o(r.type>=16&&r.type<=23),l=!1),r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=o(!1)),n.frame=!0,s=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:s=!0,l&&null!=(u=n)&&u.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=o(!0)),n.key=!0,n.frame=!0;break;case 19:case 20:s=!0,null!=(h=n)&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=o(!0)),n.key=!0,n.frame=!0;break;case 39:s=!0,eZ(r.data,2,i.pts,t.samples);break;case 32:s=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=K(e.params,this.readVPS(r.data)),this.initVPS=r.data),e.vps=[r.data];break;case 33:if(s=!0,l=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],r.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let t=this.readSPS(r.data);for(let i in e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={}),t.params)e.params[i]=t.params[i]}this.pushParameterSet(e.sps,r.data,e.vps),n||(n=o(!1));break;case 34:if(s=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];let t=this.readPPS(r.data);for(let i in t)e.params[i]=t[i]}this.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:s=!0,e.audFound=!0,null!=(d=n)&&d.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=o(!1));break;default:s=!1}n&&s&&n.units.push(r)}),r&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,i){(!i||i[0]!==this.initVPS)&&(i||e.length)||e.push(t)}startsNewAccessUnit(e,t,i,r){if(!e)return!1;if(!t.audFound&&0===r)return!0;if(!e.frame)return!1;let{type:s,data:a}=i;return s>=32&&s<=35||39===s||s>=41&&s<=44||s>=48&&s<=55||s<=31&&a.length>2&&(128&a[2])!=0}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),i=0;for(let r=0;r<e.byteLength;r++)(!(r>=2)||3!==e[r]||0!==e[r-1]||0!==e[r-2])&&(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new rB(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){let t=new rB(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let i=t.readBits(3);t.readBoolean();let r=t.readBits(2),s=t.readBoolean(),a=t.readBits(5),n=t.readUByte(),l=t.readUByte(),o=t.readUByte(),h=t.readUByte(),d=t.readUByte(),u=t.readUByte(),f=t.readUByte(),c=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),E=[],v=[];for(let e=0;e<i;e++)E.push(t.readBoolean()),v.push(t.readBoolean());if(i>0)for(let e=i;e<8;e++)t.readBits(2);for(let e=0;e<i;e++)E[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),v[e]&&t.readUByte();t.readUEG();let y=t.readUEG();3==y&&t.skipBits(1);let T=t.readUEG(),S=t.readUEG(),A=t.readBoolean(),I=0,L=0,R=0,b=0;A&&(I+=t.readUEG(),L+=t.readUEG(),R+=t.readUEG(),b+=t.readUEG());let D=t.readUEG(),k=t.readUEG(),P=t.readUEG(),_=t.readBoolean();for(let e=_?0:i;e<=i;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++)if(t.readBoolean()){let i=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<i;e++)t.readEG()}else t.readUEG();t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let C=t.readUEG(),O=0;for(let e=0;e<C;e++){let i=!1;if(0!==e&&(i=t.readBoolean()),i){e===C&&t.readUEG(),t.readBoolean(),t.readUEG();let i=0;for(let e=0;e<=O;e++){let e=t.readBoolean(),r=!1;e||(r=t.readBoolean()),(e||r)&&i++}O=i}else{let e=t.readUEG(),i=t.readUEG();O=e+i;for(let i=0;i<e;i++)t.readUEG(),t.readBoolean();for(let e=0;e<i;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let e=t.readUEG();for(let i=0;i<e;i++){for(let e=0;e<P+4;e++)t.readBits(1);t.readBits(1)}}let M=0,w=1,F=1,x=!0,N=1,$=0;t.readBoolean(),t.readBoolean();if(t.readBoolean()){if(t.readBoolean()){let e=t.readUByte();e>0&&e<16?(w=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],F=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(w=t.readBits(16),F=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(N=t.readBits(32),$=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let e=t.readBoolean(),r=t.readBoolean(),s=!1;(e||r)&&((s=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let a=0;a<=i;a++){let i=(x=t.readBoolean())||t.readBoolean(),a=!1;i?t.readEG():a=t.readBoolean();let n=a?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),s&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(r)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),s&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),M=t.readUEG())}let U=T,B=S;if(A){let e=1,t=1;1===y?e=t=2:2==y&&(e=2),U=T-e*L-e*I,B=S-t*b-t*R}let G=r?["A","B","C"][r]:"",K=n<<24|l<<16|o<<8|h,V=0;for(let e=0;e<32;e++)V=(V|(K>>e&1)<<31-e)>>>0;let H=V.toString(16);return 1===a&&"2"===H&&(H="6"),{codecString:`hvc1.${G}${a}.${H}.${s?"H":"L"}${p}.B0`,params:{general_tier_flag:s,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[n,l,o,h],general_constraint_indicator_flags:[d,u,f,c,g,m],general_level_idc:
16p,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:k,min_spatial_segmentation_idc:M,chroma_format_idc:y,frame_rate:{fixed:x,fps:$/N}},width:U,height:B,pixelRatio:[w,F]}}readPPS(e){let t=new rB(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let i=t.readBoolean(),r=t.readBoolean(),s=1;return r&&i?s=0:r?s=3:i&&(s=2),{parallelismType:s}}matchSPS(e,t){return ek(e).substring(3)===ek(t).substring(3)}}class rV{constructor(e,t,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.videoParser=null}static probe(e,t){let i=rV.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(e){let t=e.length,i=Math.min(940,t-188)+1,r=0;for(;r<i;){let s=!1,a=-1,n=0;for(let l=r;l<t;l+=188)if(71===e[l]&&(t-l==188||71===e[l+188])){if(n++,-1===a&&0!==(a=l)&&(i=Math.min(a+18612,e.length-188)+1),s||(s=0===rH(e,l)),s&&n>1&&(0===a&&n>2||l+188>i))return a}else if(n)return -1;else break;r++}return -1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:e_[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,r,s,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=rV.createTrack("video"),this._videoTrack.duration=r,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new rq(this.logger):null,this._audioTrack=rV.createTrack("audio",r),this._id3Track=rV.createTrack("id3"),this._txtTrack=rV.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,e&&this.demux(e,0,a,(null==s?void 0:s.method)==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i,r=!1,s=!1){let a;r||(this.sampleAes=null);let n=this._videoTrack,l=this.videoIntegrityChecker,o=this._audioTrack,h=this._id3Track,d=this._txtTrack,u=i.iframe,f=n.pid,c=n.pesData,g=o.pid,m=h.pid,p=this._klvPid,E=o.pesData,v=h.pesData,y=null,T=null,S=this.pmtParsed,A=this._pmtId,I=e.length;if(this.remainderData&&(I=(e=eX(this.remainderData,e)).length,this.remainderData=null),I<188&&!s)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:h,textTrack:d};let L=Math.max(0,rV.syncOffset(e));(I-=(I-L)%188)<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,I,e.buffer.byteLength-I));let R=0;for(let t=L;t<I;t+=188)if(71===e[t]){let s;let I=!!(64&e[t+1]),R=rH(e,t);if((48&e[t+3])>>4>1){if((s=t+5+e[t+4])===t+188)continue}else s=t+4;switch(R){case f:I&&(c&&!(null!=l&&l.isCorrupted)&&(a=rj(c,this.logger))&&(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(n,d,a,!1,i)),c={data:[],size:0},null==l||l.reset(f)),null==l||l.handlePacket(e.subarray(t)),c&&(c.data.push(e.subarray(s,t+188)),c.size+=t+188-s);break;case g:if(u)break;if(I){if(E&&(a=rj(E,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,a,i);break;case"mp3":this.parseMPEGPES(o,a);break;case"ac3":this.parseAC3PES(o,a)}E={data:[],size:0}}E&&(E.data.push(e.subarray(s,t+188)),E.size+=t+188-s);break;case m:if(u)break;I&&(v&&(a=rj(v,this.logger))&&this.parseID3PES(h,a),v={data:[],size:0}),v&&(v.data.push(e.subarray(s,t+188)),v.size+=t+188-s);break;case p:if(u)break;I&&(y&&(a=rj(y,this.logger))&&this.parseKlvPES(h,a),y={data:[],size:0}),y&&(y.data.push(e.subarray(s,t+188)),y.size+=t+188-s);break;case 0:var b,D;I&&(s+=e[s]+1),A=this._pmtId=(31&(b=e)[(D=s)+10])<<8|b[D+11];break;case A:{I&&(s+=e[s]+1);let a=function(e,t,i,r,s,a,n,l){let o={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},h=(15&e[t+1])<<8|e[t+2],d=t+3+h-4,u=(15&e[t+10])<<8|e[t+11];for(t+=12+u;t<d;){let h=rH(e,t),d=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!r){rW("ADTS AAC",a);break}case 15:-1===o.audioPid&&(o.audioPid=h);break;case 21:-1===o.id3Pid&&(o.id3Pid=h);break;case 219:if(!r){rW("H.264",a);break}case 27:-1===o.videoPid&&(o.videoPid=h);break;case 3:case 4:i.mpeg||i.mp3?-1===o.audioPid&&(o.audioPid=h,o.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){rW("AC-3",a);break}case 129:i.ac3?-1===o.audioPid&&(o.audioPid=h,o.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(d>0){let r=t+5,s=d;for(;s>2;){switch(e[r]){case 106:-1===o.audioPid&&(!0!==i.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(o.audioPid=h,o.segmentAudioCodec="ac3"));break;case 5:-1===o.klvPid&&n.enableEmsgKLVMetadata&&(o.klvPid=h,a.log(`KLV metadata PID found: ${h}`))}let t=e[r+1]+2;r+=t,s-=t}}break;case 194:case 135:return rY(s,Error("Unsupported EC-3 in M2TS found"),l,void 0,a),o;case 36:-1===o.videoPid&&(o.videoPid=h,o.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=d+5}return o}
16(e,s,this.typeSupported,r,this.observer,this.logger,this.config,i);(f=a.videoPid)>0&&(n.pid=f,n.segmentCodec=a.segmentVideoCodec),(g=a.audioPid)>0&&(o.pid=g,o.segmentCodec=a.segmentAudioCodec),(m=a.id3Pid)>0&&(h.pid=m),(p=a.klvPid)>0&&(this._klvPid=p),null===T||S||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${T}'. Backtracking to sync byte @${L} to parse all TS packets.`),T=null,t=L-188),S=this.pmtParsed=!0;break}case 17:case 8191:break;default:T=R}}else R++;R>0&&rY(this.observer,Error(`Found ${R} TS packet/s that do not start with 0x47`),i,void 0,this.logger),n.pesData=c,o.pesData=E,h.pesData=v;let k={audioTrack:o,videoTrack:n,id3Track:h,textTrack:d};return s&&this.extractRemainingSamples(k,i),k}flush(e,t){let i;let{remainderData:r}=this;return(this.remainderData=null,i=r?this.demux(r,0,t,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i,t),this.sampleAes)?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(e,t){let i;let{audioTrack:r,videoTrack:s,id3Track:a,textTrack:n}=e,l=s.pesData,o=r.pesData,h=a.pesData,d=this.videoIntegrityChecker;if(l&&!(null!=d&&d.isCorrupted)&&(i=rj(l,this.logger))?(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,n,i,!0,t),s.pesData=null)):s.pesData=l,o&&(i=rj(o,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,i,t);break;case"mp3":this.parseMPEGPES(r,i);break;case"ac3":this.parseAC3PES(r,i)}r.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;h&&(i=rj(h,this.logger))?(this.parseID3PES(a,i),a.pesData=null):a.pesData=h}demuxSampleAes(e,t,i,r){let s=this.demux(e,i,r,!0,!this.config.progressive),a=this.sampleAes=new r_(this.observer,this.config,t);return this.decrypt(s,a)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new rG:"hevc"===e&&(this.videoParser=new rK))}decrypt(e,t){return new Promise(i=>{let{audioTrack:r,videoTrack:s}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,()=>{i(e)}):i(e)}):s.samples&&t.decryptAvcSamples(s.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,i){let r,s,a,n,l=0,o=this.aacOverFlow,h=t.data;if(o){this.aacOverFlow=null;let t=o.missing,i=o.sample.unit.byteLength;-1===t?h=eX(o.sample.unit,h):(o.sample.unit.set(h.subarray(0,t),i-t),e.samples.push(o.sample),l=o.missing)}for(r=l,s=h.length;r<s-1&&!rg(h,r);r++);if(r!==l){let e;let t=r<s-1;if(e=t?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",rY(this.observer,Error(e),i,t,this.logger),!t)return}if(rm(e,this.observer,h,r,this.audioCodec),void 0!==t.pts)a=t.pts;else if(o){let t=9216e4/e.samplerate;a=o.sample.pts+t}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0;for(;r<s;){if(n=rp(e,h,r,a,d),r+=n.length,n.missing){this.aacOverFlow=n;break}for(d++;r<s-1&&!rg(h,r);r++);}}parseMPEGPES(e,t){let i=t.data,r=i.length,s=0,a=0,n=t.pts;if(void 0===n){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(rk(i,a)){let t=rR(e,i,a,n,s);if(t)a+=t.length,s++;else break}else a++}parseAC3PES(e,t){{let i;let r=t.data,s=t.pts;if(void 0===s){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let a=r.length,n=0,l=0;for(;l<a&&(i=rw(e,r,l,s,n++))>0;)l+=i}}parseID3PES(e,t){if(void 0===t.pts){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=K({},t,{type:this._videoTrack?rE.emsg:rE.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}parseKlvPES(e,t){var i,r;let s=null!=(i=t.pts)?i:t.dts;if(void 0===s){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}let a=t.data;if(a.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let n=0;for(;n<a.length&&!(n+16>a.length);){let i=n;if((n+=16)>=a.length)break;let l=a[n];n+=1;let o=0;if(128&l){let e=127&l;if(0===e||e>4||n+e>a.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let t=0;t<e;t++)o=o<<8|a[n+t];n+=e}else o=l;if(n+o>a.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}let h=n+o,d=a.subarray(i,h),u={data:d,len:d.byteLength,pts:s,dts:null!=(r=t.dts)?r:s,type:rE.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(u),n=h}}}function rH(e,t){return((31&e[t+1])<<8)+e[t+2]}function rY(e,t,i,r,s){s.warn(`parsing error: ${t.message}
16`),e.emit(m.ERROR,m.ERROR,{type:c.MEDIA_ERROR,details:g.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,chunkMeta:i,error:t,reason:t.message})}function rW(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function rj(e,t){let i,r,s,a,n,l=0,o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=eX(o[0],o[1]),o.splice(1,1);if(1===((i=o[0])[0]<<16)+(i[1]<<8)+i[2]){if((r=(i[4]<<8)+i[5])&&r>e.size-6)return null;let h=i[7];192&h&&(a=(14&i[9])*536870912+(255&i[10])*4194304+(254&i[11])*16384+(255&i[12])*128+(254&i[13])/2,64&h?a-(n=(14&i[14])*536870912+(255&i[15])*4194304+(254&i[16])*16384+(255&i[17])*128+(254&i[18])/2)>54e5&&(t.warn(`${Math.round((a-n)/9e4)}s delta between PTS and DTS, align them`),a=n):n=a);let d=(s=i[8])+9;if(e.size<=d)return null;e.size-=d;let u=new Uint8Array(e.size);for(let e=0,t=o.length;e<t;e++){let t=(i=o[e]).byteLength;if(d){if(d>t){d-=t;continue}i=i.subarray(d),t-=d,d=0}u.set(i,l),l+=t}return r&&(r-=s+3),{data:u,pts:a,dts:n,len:r}}return null}class rq{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return"ok"!==this.integrityState}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;let t=rH(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}let i=(48&e[3])>>4;if(0===i)return;let r=15&e[3],s=this.lastContinuityCounter;if(this.lastContinuityCounter=r,(2&i)!=0&&0!=e[4]&&(128&e[5])!=0||s<0)return;let a=(1&i)!=0?s+1&15:s;if(r!==a){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${r}, Expected-CC=${a} Last-CC=${s}`),this.integrityState="cc-failed";return}if((128&e[1])!=0){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState="tei-bit";return}}}class rX{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);else if(5===t)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(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t||3===t)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])}}}let rz={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])},rQ=new Uint8Array([0,0,0,0,0,0,0,0]),rZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),rJ=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),r0=new Uint8Array([0,0,0,0,0,0,0,0]),r1=new Uint8Array([0,0,0,0,0,0,0,1]),r2=new Uint8Array([105,115,111,109]),r4=new Uint8Array([97,118,99,49]),r3=new Uint8Array([0,0,0,1]);class r8{static box(e,...t){let i=8,r=t.length,s=r;for(;r--;)i+=t[r].byteLength;let a=new Uint8Array(i);for(ex(a,0,i),ex(a,4,e),r=0,i=8;r<s;r++)a.set(t[r],i),i+=t[r].byteLength;return a}static hdlr(e){return r8.box(eP.hdlr,rz[e])}static mdat(e){return r8.box(eP.mdat,e)}static mdhd(e,t){let i=Math.floor((t*=e)/4294967296),r=Math.floor(t%4294967296);return r8.box(eP.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return r8.box(eP.mdia,r8.mdhd(e.timescale||0,e.duration||0),r8.hdlr(e.type),r8.minf(e))}static mfhd(e){return r8.box(eP.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?r8.box(eP.minf,r8.box(eP.smhd,r0),r8.DINF,r8.stbl(e)):r8.box(eP.minf,r8.box(eP.vmhd,rJ),r8.DINF,r8.stbl(e))}static moof(e,t,i){return r8.box(eP.moof,r8.mfhd(e),r8.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=r8.trak(e[t]);return r8.box.apply(null,[eP.moov,r8.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).c
16oncat(r8.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=r8.trex(e[t]);return r8.box.apply(null,[eP.mvex,...i])}static mvhd(e,t){let i=Math.floor((t*=e)/4294967296),r=Math.floor(t%4294967296),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return r8.box(eP.mvhd,s)}static sdtp(e){let t,i;let r=e.samples||[],s=new Uint8Array(4+r.length);for(t=0;t<r.length;t++)i=r[t].flags,s[t+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return r8.box(eP.sdtp,s)}static stbl(e){return r8.box(eP.stbl,r8.stsd(e),r8.box(eP.stts,rQ),r8.box(eP.stsc,rQ),r8.box(eP.stsz,rZ),r8.box(eP.stco,rQ))}static avc1(e){let t,i,r,s=[],a=[];for(t=0;t<e.sps.length;t++)r=(i=e.sps[t]).byteLength,s.push(r>>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(i));for(t=0;t<e.pps.length;t++)r=(i=e.pps[t]).byteLength,a.push(r>>>8&255),a.push(255&r),a=a.concat(Array.prototype.slice.call(i));let n=r8.box(eP.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(a))),l=e.width,o=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return r8.box(eP.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,255&l,o>>8&255,255&o,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]),n,r8.box(eP.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),r8.box(eP.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(e){let t=e.config,i=t.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,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return r8.box(eP.mp4a,r8.audioStsd(e),r8.box(eP.esds,r8.esds(e)))}static mp3(e){return r8.box(eP[".mp3"],r8.audioStsd(e))}static ac3(e){return r8.box(eP["ac-3"],r8.audioStsd(e),r8.box(eP.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return r8.box(eP.stsd,r1,r8.mp4a(e));if("ac3"===t&&e.config)return r8.box(eP.stsd,r1,r8.ac3(e));if("mp3"===t&&"mp3"===e.codec)return r8.box(eP.stsd,r1,r8.mp3(e))}else if(e.pps&&e.sps){if("avc"===t)return r8.box(eP.stsd,r1,r8.avc1(e));if("hevc"===t&&e.vps)return r8.box(eP.stsd,r1,r8.hvc1(e))}else throw Error("video track missing pps or sps");throw Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,i=(e.duration||0)*(e.timescale||0),r=e.width||0,s=e.height||0,a=Math.floor(i/4294967296),n=Math.floor(i%4294967296);return r8.box(eP.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,n>>24,n>>16&255,n>>8&255,255&n,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,s>>8&255,255&s,0,0]))}static traf(e,t){let i=r8.sdtp(e),r=e.id,s=Math.floor(t/4294967296),a=Math.floor(t%4294967296);return r8.box(eP.traf,r8.box(eP.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),r8.box(eP.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,a>>24,a>>16&255,a>>8&255,255&a])),r8.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,r8.box(eP.trak,r8.tkhd(e),r8.mdia(e))}static trex(e){let t=e.id;return r8.box(eP.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let i,r,s,a,n,l;let o=e.samples||[],h=o.length,d=12+16*h,u=new Uint8Array(d);for(t+=8+d,u.set(["video"===e.type?1:0,0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),i=0;i<h;i++)s=(r=o[i]).duration,a=r.size,n=r.flags,l=r.cts,u.set([s>>>24&255,s>>>16&255,s>>>8&255,255&s,a>>>24&255,a>>>16&255,a>>>8&255,255&a,n.isLeading<<2|n.dependsOn,n.isDependedOn<<6|n.hasRedundancy<<4|n.paddingValue<<1|n.isNonSync,61440&n.degradPrio,15&n.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return r8.box(eP.trun,u)}static initSegment(e){let t=r8.moov(e);return eX(r8.FTYP,t)}
16static hvc1(e){let t=e.params,i=[e.vps,e.sps,e.pps],r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),i.length]),s=r.length;for(let e=0;e<i.length;e+=1){s+=3;for(let t=0;t<i[e].length;t+=1)s+=2+i[e][t].length}let a=new Uint8Array(s);a.set(r,0),s=r.length;let n=i.length-1;for(let e=0;e<i.length;e+=1){a.set(new Uint8Array([32+e|(e===n?128:0),0,i[e].length]),s),s+=3;for(let t=0;t<i[e].length;t+=1)a.set(new Uint8Array([i[e][t].length>>8,255&i[e][t].length]),s),s+=2,a.set(i[e][t],s),s+=i[e][t].length}let l=r8.box(eP.hvcC,a),o=e.width,h=e.height,d=e.pixelRatio[0],u=e.pixelRatio[1];return r8.box(eP.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,r8.box(eP.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),r8.box(eP.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,u>>24,u>>16&255,u>>8&255,255&u])))}}function r5(e,t,i=1,r=!1){let s=e*t*i;return r?Math.round(s):s}function r6(e,t=!1){return r5(e,1e3,11111111111111112e-21,t)}function r9(e){let{baseTime:t,timescale:i,trackId:r}=e;return`${t/i} (${t}/${i}) trackId: ${r}`}function r7(e,t,i,r){return{duration:t,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1,paddingValue:0}}}r8.FTYP=r8.box(eP.ftyp,r2,r3,r2,r4),r8.DINF=r8.box(eP.dinf,r8.box(eP.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));class se extends er{constructor(e,t,i,r){super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t?r9(t):t} > ${e?r9(e):e}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,i=e[0].pts,r=e.reduce((e,r)=>{let s=r.pts,a=s-e;return(a<-4294967296&&(t=!0,a=(s=st(s,i))-e),a>0)?e:s},i);return t&&this.debug("PTS rollover detected"),r}remux(e,t,i,r,s,a,n,l,o){let h,d,u,f,c,g;let m=s,p=s,E=!o.iframe&&e.pid>-1,v=t.pid>-1,y=t.samples.length,T=e.samples.length>0,S=n&&y>0||y>1;if((!E||T)&&(!v||S)||this.ISGenerated||n){let i;if(this.ISGenerated){var A,I,L,R;let e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(A=t.pixelRatio)?void 0:A[0])!==(null==(I=e.pixelRatio)?void 0:I[0])||
16(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(R=e.pixelRatio)?void 0:R[1]))||!e&&S||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,s,a));let r=this.isVideoContiguous,n=-1;if(S&&(n=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return -1}(t.samples),!r&&this.config.forceKeyFrameOnDiscontinuity)){if(g=!0,n>0){this.warn(`Dropped ${n} out of ${y} video samples due to a missing keyframe`);let e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(n),t.dropped+=n,p+=(t.samples[0].pts-e)/t.inputTimeScale,i=p}else -1===n&&(this.warn(`No keyframe found out of ${y} video samples`),g=!1)}if(this.ISGenerated){if(T&&S&&s){let i=this.getVideoStartPts(t.samples),r=(st(e.samples[0].pts,i)-i)/t.inputTimeScale;m+=Math.max(0,r),p+=Math.max(0,-r)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,s,a)),d=this.remuxAudio(e,m,this.isAudioContiguous,a,v||S||l===w.AUDIO?p:void 0,o),S){let i=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,s,a)),h=this.remuxVideo(t,p,r,i,o)}}else S&&(h=this.remuxVideo(t,p,r,0,o));h&&(h.firstKeyFrame=n,h.independent=-1!==n,h.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=si(i,s,this._initPTS,this._initDTS)),r.samples.length&&(f=sr(r,s,this._initPTS))),{audio:d,video:h,initSegment:u,independent:g,text:f,id3:c}}computeInitPts(e,t,i,r){let s=Math.round(i*t),a=st(e,s);if(a<s)for(this.log(`Adjusting PTS for rollover in timeline near ${(s-a)/t} ${r}`);a<s;)a+=8589934592;return a-s}generateIS(e,t,i,r){let s,a,n;let l=e.samples,o=t.samples,h=this.typeSupported,u={},f=this._initPTS,c=!f||r,g="audio/mp4",m=-1;if(c&&(s=a=1/0),e.config&&l.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":h.mpeg?(g="audio/mpeg",e.codec=""):h.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}if(u.audio={id:"audio",container:g,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&h.mpeg?new Uint8Array(0):r8.initSegment([e]),metadata:{channelCount:e.channelCount}},c){m=e.id,n=e.inputTimeScale;let t=this.computeInitPts(l[0].pts,n,i,"audio");(!f||n!==f.timescale||0===i&&t<f.baseTime)&&(s=a=t)}}if(t.sps&&t.pps&&o.length){if(t.timescale=t.inputTimeScale,u.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:r8.initSegment([t]),metadata:{width:t.width,height:t.height}},c){m=t.id,n=t.inputTimeScale;let e=this.getVideoStartPts(o),r=st(o[0].dts,e),l=this.computeInitPts(r,n,i,"video"),h=this.computeInitPts(e,n,i,"video");(!f||n!==f.timescale||d(s)||0===i&&h<f.baseTime)&&(a=Math.min(a,l),s=Math.min(s,l))}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(u).length)return this.ISGenerated=!0,c&&d(s)?(f&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${i} ${s/n} != initPTS: ${f.baseTime/f.timescale} (${f.baseTime}/${f.timescale}) trackId: ${f.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${s/n} (${s}/${n}) trackId: ${m}`),this._initPTS={baseTime:s,timescale:n,trackId:m},this._initDTS={baseTime:a,timescale:n,trackId:m}):s=n=void 0,{tracks:u,initPTS:s,timescale:n,trackId:m}}remuxVideo(e,t,i,r,s){let a,l,o;let h=e.inputTimeScale,d=e.samples,u=[],f=d.length,p=this._initPTS,E=p.baseTime*h/p.timescale,v=this.nextVideoTs,y=8,T=this.videoSampleDuration,S=Number.POSITIVE_INFINITY,A=Number.NEGATIVE_INFINITY,I=!1;if(!i||null===v){let e=E+t*h,r=d[0].pts-st(d[0].dts,d[0].pts);e3()&&null!==v&&15e3>Math.abs(e-r-(v+E))?i=!0:v=e-r-E}let L=v+E;for(let e=0;e<f;e++){let t=d[e];t.pts=st(t.pts,L),t.dts=st(t.dts,L),t.dts<d[e>0?e-1:e].dts&&(I=!0)}I&&d.sort(function(e,t){let i=e.dts-t.dts,r=e.pts-t.pts;return i||r}),a=d[0].dts;let R=(l=d[d.length-1].dts)-a,b=R?Math.round(R/(f-1)):T||e.inputTimeScale/30;if(i){let i=a-L,r=i>b,s=i<-1;if((r||s)&&(r?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${r6(i,!0)} ms (${i}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${r6(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!s||L>=d[0].pts||e3())){a=L;let e=d[0].pts-i;
16if(r)d[0].dts=a,d[0].pts=e;else{let t=!0;for(let r=0;r<d.length&&(!(d[r].dts>e)||!t);r++){let e=d[r].pts;if(d[r].dts-=i,d[r].pts-=i,r<d.length-1){let i=d[r+1].pts;t=i<=d[r].pts==i<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${r6(e,!0)}/${r6(a,!0)}, delta: ${r6(i,!0)} ms`)}}let D=0,k=0,P=a=Math.max(0,a);for(let e=0;e<f;e++){let t=d[e],i=t.units,r=i.length,s=0;for(let e=0;e<r;e++)s+=i[e].data.length;k+=s,D+=r,t.length=s,t.dts<P?(t.dts=P,P+=b/4|0||1):P=t.dts,S=Math.min(t.pts,S),A=Math.max(t.pts,A)}l=d[f-1].dts;let _=k+4*D+8;try{o=new Uint8Array(_)}catch(e){this.observer.emit(m.ERROR,m.ERROR,{type:c.MUX_ERROR,details:g.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:s,error:e,bytes:_,reason:`fail allocating video mdat ${_}`});return}ex(o,0,_),ex(o,4,eP.mdat);let C=!1,O=Number.POSITIVE_INFINITY,M=Number.POSITIVE_INFINITY,w=Number.NEGATIVE_INFINITY,F=Number.NEGATIVE_INFINITY;for(let e=0;e<f;e++){let t;let a=d[e],n=a.units,l=0;for(let e=0,t=n.length;e<t;e++){let t=n[e],i=t.data,r=t.data.byteLength;ex(o,y,r),y+=4,o.set(i,y),y+=r,l+=4+r}if(e<f-1)T=d[e+1].dts-a.dts,t=d[e+1].pts-a.pts;else{let i=this.config,s=e>0?a.dts-d[e-1].dts:b;if(t=e>0?a.pts-d[e-1].pts:b,i.stretchShortVideoTrack&&null!==this.nextAudioTs){let e=Math.floor(i.maxBufferHole*h),t=(r?S+r*h:this.nextAudioTs+E)-a.pts;t>e?((T=t-s)<0?T=s:C=!0,this.log(`It is approximately ${t/90} ms to the next segment; using duration ${T/90} ms for the last video frame.`)):T=s}else T=s}let c=Math.round(a.pts-a.dts);if(O=Math.min(O,T),w=Math.max(w,T),M=Math.min(M,t),F=Math.max(F,t),!i&&0===e&&c>T){let e=Math.round(c/b)*b;e-c==1&&(this.log(`pad first CTS ${c} -> ${e} of sn: ${s.sn}`),c=e)}u.push(r7(a.key,T,l,c))}if(u.length){let e=e3();if(e){if(e<70){let e=u[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(function(){if(void 0===n){let e=e1.match(/Safari\/(\d+)/i);n=e?parseInt(e[1]):0}return n}()&&F-M<w-O&&b/w<.025&&0===u[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=a;for(let t=0,i=u.length;t<i;t++){let r=e+u[t].duration,s=e+u[t].cts;if(t<i-1){let e=r+u[t+1].cts;u[t].duration=e-s}else u[t].duration=t?u[t-1].duration:b;u[t].cts=0,e=r}}}let x=l+(T=C||!T?b:T);this.nextVideoTs=v=x-E,this.videoSampleDuration=T,this.isVideoContiguous=!0,s.iframe&&(1===u.length?(u[0].duration=T=s.duration*h,this.nextVideoTs=v=a+T-E):this.warn(`Not adjusting IFrame duration (sample count ${u.length})`));let N={data1:r8.moof(s.sn,a,K(e,{samples:u})),data2:o,startPTS:(S-E)/h,endPTS:(A+T-E)/h,startDTS:(a-E)/h,endDTS:v/h,type:"video",hasAudio:!1,hasVideo:!0,nb:u.length,dropped:e.dropped};return e.samples=[],e.dropped=0,N}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,i,r,s,a){let n;let l=e.inputTimeScale,o=e.samplerate?e.samplerate:l,h=l/o,d=this.getSamplesPerFrame(e),u=d*h,f=this._initPTS,p="mp3"===e.segmentCodec&&this.typeSupported.mpeg,E=[],v=void 0!==s,y=e.samples,T=p?0:8,S=this.nextAudioTs||-1,A=f.baseTime*l/f.timescale,I=A+t*l;if(this.isAudioContiguous=i=i||y.length&&S>0&&(r&&9e3>Math.abs(I-(S+A))||Math.abs(st(y[0].pts,I)-(S+A))<20*u),y.forEach(function(e){e.pts=st(e.pts,I)}),!i||S<0){let e=y.length;if(e!==(y=y.filter(e=>e.pts>=0)).length&&this.warn(`Removed ${y.length-e} of ${e} samples (initPTS ${A} / ${l})`),!y.length)return;S=0===s?0:r&&!v?Math.max(0,I-A):y[0].pts-A}if("aac"===e.segmentCodec){let t=this.config.maxAudioFramesDrift;for(let i=0,r=S+A;i<y.length;i++){let s=y[i],a=s.pts,n=a-r,o=Math.abs(1e3*n/l);
16if(n<=-t*u&&v)0===i&&(this.warn(`Audio frame @ ${(a/l).toFixed(3)}s overlaps marker by ${Math.round(1e3*n/l)} ms.`),this.nextAudioTs=S=a-A,r=a);else if(n>=t*u&&o<1e4&&v){let t=Math.round(n/u);for(r=a-t*u;r<0&&t&&u;)t--,r+=u;0===i&&(this.nextAudioTs=S=r-A),this.warn(`Injecting ${t} audio frames @ ${((r-A)/l).toFixed(3)}s due to ${Math.round(1e3*n/l)} ms gap.`);for(let a=0;a<t;a++){let t=rX.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=s.unit.subarray()),y.splice(i,0,{unit:t,pts:r}),r+=u,i++}}s.pts=r,r+=u}}let L=null,R=null,b=0,D=y.length;for(;D--;)b+=y[D].unit.byteLength;for(let t=0,r=y.length;t<r;t++){let r=y[t],s=r.unit,l=r.pts;if(null!==R)E[t-1].duration=Math.round((l-R)/h);else{if(i&&"aac"===e.segmentCodec&&(l=S+A),L=l,!(b>0))return;b+=T;try{n=new Uint8Array(b)}catch(e){this.observer.emit(m.ERROR,m.ERROR,{type:c.MUX_ERROR,details:g.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:e,bytes:b,reason:`fail allocating audio mdat ${b}`});return}p||(ex(n,0,b),ex(n,4,eP.mdat))}n&&n.set(s,T);let o=s.byteLength;T+=o,E.push(r7(!0,d,o,0)),R=l}let k=E.length;if(!k)return;let P=E[E.length-1];S=R-A,this.nextAudioTs=S+h*P.duration;let _=p?new Uint8Array(0):r8.moof(e.sequenceNumber++,L/h,K({},e,{samples:E}));e.samples=[];let C=(L-A)/l,O=this.nextAudioTs/l,M={data1:_,data2:n,startPTS:C,endPTS:O,startDTS:C,endDTS:O,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,M}}function st(e,t){let i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function si(e,t,i,r){let s=e.samples.length;if(!s)return;let a=e.inputTimeScale;for(let n=0;n<s;n++){let s=e.samples[n];s.pts=st(s.pts-i.baseTime*a/i.timescale,t*a)/a,s.dts=st(s.dts-r.baseTime*a/r.timescale,t*a)/a}let n=e.samples;return e.samples=[],{samples:n}}function sr(e,t,i){let r=e.samples.length;if(!r)return;let s=e.inputTimeScale;for(let a=0;a<r;a++){let r=e.samples[a];r.pts=st(r.pts-i.baseTime*s/i.timescale,t*s)/s}e.samples.sort((e,t)=>e.pts-t.pts);let a=e.samples;return e.samples=[],{samples:a}}class ss extends er{constructor(e,t,i,r){super("passthrough-remuxer",r),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=e}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.decryptdata=r,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,i){this.videoOnlyRemux=!1;let{audioCodec:r,videoCodec:s}=this;if(!(null!=e&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:a,video:n}=this.initData=i||eG(e);if(t)!function(e,t){if(!e||!t)return;let i=t.keyId;(null==i?void 0:i.byteLength)===16&&t.isCommonEncryption&&eW(e,(e,t)=>{let r=e.subarray(8,24);r.some(e=>0!==e)||(eo.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${eR(r)} -> ${eR(i)}`),e.set(i,8))})}(e,t);else{let e=a||n;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}a&&(r=sn(a,F.AUDIO,this)),n&&(s=sn(n,F.VIDEO,this));let l={};a&&n?l.audiovideo={container:"video/mp4",codec:r+","+s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:r,encrypted:a.encrypted,initSegment:e,id:"audio"}:n?l.video={container:"video/mp4",codec:s,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(e,t,i,r,s,a,n,l,o,h,u){var f,c,g,m;let p,E;let{initPTS:v,lastEndTime:y}=this,T={audio:void 0,video:void 0,text:void 0,id3:i,initSegment:void 0};d(y)||(y=this.lastEndTime=s||0);let S=t.samples;if(!S.length)return T;let A=this.pendingInitSegment;A&&(this.pendingInitSegment=void 0,this.generateInitSegment(A,this.decryptdata,h));let I={initPTS:void 0,timescale:void 0,trackId:void 0},L=this.initData;if(null!=(f=L)&&f.length||(this.generateInitSegment(S),L=this.initData),!(null!=(c=L)&&c.length))return this.warn("Failed to generate initSegment."),T;if(o.iframe&&L.audio&&L.video){let e=null==(g=this.initTracks)||null==(g=g.audiovideo)?void 0:g.initSegment,t=e?function(e){let t=eB(e,["moov"]);if(1!==t.length||eB(e,["moof"]).length)return null;let i=e.byteOffset,r=[],s=[],a=!1,n=eB(t[0],["trak"]);for(let e=0;e<n.length;e++){let t=n[e],l=eB(t,["mdia","hdlr"])[0];if("vide"===(l?ek(l.subarray(8,12)):"")){a=!0;continue}let o=eB(t,["tkhd"])[0];if(!o)return null;let h=o[0];s.push(eO(o,0===h?12:20)),r.push(e$(t,i))}if(!a||!r.length)return null;let l=eB(t[0],["mvex"])[0],o=0;if(l){let e=eB(l,["trex"]);for(let t=0;t<e.length;t++){let a=e[t];-1!==s.indexOf(eO(a,4))&&(r.push(e$(a,i)),o+=a.byteLength+8)}}let{result:h,dropped:d,droppedBefore:u}=eU(e,r);if(ex(h,t[0].byteOffset-i-8,t[0].byteLength+8-d),l&&o){let e=l.byteOffset-i-8;ex(h,e-u(e),l.byteLength+8-o)}return h}(e):null;t&&(this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(t,this.decryptdata),null!=(m=this.initData)&&m.length&&(L=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0))}this.emitInitSegment&&(I.tracks=this.initTracks,T.initSegment=I,this.emitInitSegment=!1);let R=o.iframe,b=u&&(!R||u.includeSampleDetails)?u.tracks:function(e,t,i,r,s=!0){return eq(e,t,r,s)}(S,L,0,this,R),D=L.audio?b[L.audio.id]:null,k=L.video?b[L.video.id]:null,P=!!L.audio,_=!!L.video,C="";P&&(C+="audio"),_&&(C+="video");let O=sa(k,1/0),M=sa(D,1/0),w=sa(k,0,!0),F=sa(D,0,!0),x=s,N=0;k&&D&&L.audio&&(M>w||O>F)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${O}-${w} a: ${M}-${F}}`,k,D);let $=!!D&&(!k||!v&&M<O||!!v&&v.trackId===L.audio.id),U=$?D:k;if(!U)return this.log(`No media samples found in ${l} ${o.level} ${-1===o.part?"":`part: ${o.part} of`} sn: ${o.sn} at playlist time: ${s}`),T;let B=S;
16if(k&&k.sampleCount>=1&&L.video&&o.iframe){let{trun:e,start:t}=k,i=1===e.length,r=e.length?i?e[0].samples:e[0].samples.concat(...e.slice(1).map(e=>e.samples)):[];if(r.length){let s=e[0],a=s;for(let t=e.length;t--;)if(e[t].samples.length){a=e[t];break}let n=a.lastSampleDurationOffset,{defaultSampleDurationOffset:l}=s,h=Math.abs(o.duration-(w-O))>.05,d=r.length<k.sampleCount;if(h||d||this.videoOnlyRemux||!i){let e=d?a.sampleOffset+a.samples.reduce((e,t)=>e+t.size,0):void 0,i=h?o.duration:w-O,s=function(e,t,i,r){if(void 0!==i){let r=e[e.length-1],s=t;for(let t=0;t<e.length-1;t++)s-=e[t].duration;return s<=0&&(s=r.duration),r.duration=s,{durationOffset:i,value:s}}if(void 0===r)return;let s=Math.round(t/e.length);for(let t=0;t<e.length;t++)e[t].duration=s;return{durationOffset:r,value:s}}(r,i*L.video.timescale,n,l),u=function(e,t,i,r,s){if(i<1)return null;let a=eB(e,["moof"]);if(1!==a.length)return null;let n=a[0],l=e.byteOffset,o=[],h=[],d=eB(n,["traf"]),u=!0;for(let e=0;e<d.length;e++){let i=d[e],r=eB(i,["tfhd"])[0];if(!r)return null;eO(r,4)===t?(o.push(i),131072&eO(r,0)||(u=!1)):h.push(e$(i,l))}if(!o.length||h.length&&!u)return null;if(void 0!==r){let t=i;for(let i=0;i<o.length;i++){let r=o[i],s=0,a=eB(r,["trun"]);for(let i=0;i<a.length;i++){let r=a[i],n=Math.min(t,eO(r,4));if(n){ex(e,r.byteOffset-l+4,n);let t=16777215&eO(r,0),i=(256&t?4:0)+(512&t?4:0)+(1024&t?4:0)+(2048&t?4:0);eN(e,r,8+(1&t?4:0)+(4&t?4:0)+n*i)}else ex(e,r.byteOffset-l-4,eP.free);t-=n,s+=n}let n=eB(r,["senc"])[0];n&&ex(e,n.byteOffset-l+4,s);let h=eB(r,["saiz"])[0];if(h){let t=h[1]<<16|h[2]<<8|h[3],i=4;1&t&&(i+=8);let r=h[i];i+=1,ex(e,h.byteOffset-l+i,s),eN(e,h,i+4+(0===r?s:0))}}let s=eB(e,["mdat"]);if(1===s.length){let t=s[0].byteOffset-l-8;ex(e,t,r-t)}}let f=e,c=0,g=()=>0;if(h.length){({result:f,dropped:c,droppedBefore:g}=eU(e,h)),ex(f,n.byteOffset-l-8,n.byteLength+8-c);for(let e=0;e<o.length;e++){let t=o[e],i=g(t.byteOffset-l),r=eB(t,["trun"]);for(let e=0;e<r.length;e++){let t=r[e];1&eO(t,0)&&ex(f,t.byteOffset-l-i+8,eO(t,8)-c)}if(i){let e=eB(t,["saio"]);for(let t=0;t<e.length;t++){let r=e[t],s=0===r[0]?4:8,a=1&eO(r,0)?12:4,n=eO(r,a);for(a+=4;n--;a+=s){let e=a+s-4;ex(f,r.byteOffset-l-i+e,eO(r,e)-i)}}}}}if(s){let{durationOffset:e,value:t}=s;ex(f,e-g(e),t)}return void 0!==r?f.subarray(0,r-c):f}(S,L.video.id,r.length,e,s);u?(B=u,E=function(e,t){let i=e,r=e;for(let e=0;e<t.length;e++){let{cts:s,duration:a}=t[e];r=Math.max(r,i+(s||0)+a),i+=a}return r}(t,r)):this.warn(`IFrame remux skipped (sn ${o.sn}); using native sample duration`),N=u&&s?i:w-O}else N=w-O}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${e.length})`),N=w-O}else N=$?F-M:w-O;if(this.videoOnlyRemux&&B===S)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${o.sn})`),T;let G=U.timescale,K=U.start-s*G,V=$?L.audio.id:L.video.id;if(x=U.start/G,(a||!v)&&(function(e,t,i,r){if(null===e)return!0;let s=Math.max(r,1);return Math.abs(t-e.baseTime/e.timescale-i)>=s}(v,x,s,N)||G!==v.timescale)){let e=!1,t=$?"audio":"video";if(v){let i=0!==s?x/s:1+x/1;e=x>=0&&.001>Math.abs(1-i),this.log(`${t} timestamps in track ${V} at playlist time: ${a?"":"~"}${s} maps to ${x} with initPTS: ${v.baseTime/v.timescale} (${K/G-v.baseTime/v.timescale}s diff) (${C}) drift estimate: ${i} ${e?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}e||(this.log(`Found initPTS in ${t} track ${V} at playlist time: ${s} offset: ${x-s} (${K}/${G})`),v=null,I.initPTS=K,I.timescale=G,I.trackId=V)}v?(I.initPTS=v.baseTime,I.timescale=v.timescale,I.trackId=v.trackId):(I.timescale&&void 0!==I.trackId&&void 0!==I.initPTS||(this.warn("Could not set initPTS"),I.initPTS=x,I.timescale=1,I.trackId=-1),this.initPTS=v={baseTime:I.initPTS,timescale:I.timescale,trackId:I.trackId});let H=x-v.baseTime/v.timescale,Y=H+N,W=_&&(null==U?void 0:U.ptsMin)!==void 0?U.ptsMin/U.timescale-v.baseTime/v.timescale:H,j=void 0!==E&&k?E/k.timescale-v.baseTime/v.timescale:_&&null!=U&&U.ptsMax?U.ptsMax/U.timescale-v.baseTime/v.timescale:Y;N>0?this.lastEndTime=Y:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let q={data1:B,data2:p,startPTS:W,startDTS:H,endPTS:j,endDTS:Y,type:C,hasAudio:P,hasVideo:_,nb:1,dropped:0,encrypted:!!L.audio&&L.audio.encrypted||!!L.video&&L.video.encrypted};T.audio=P&&!_?q:void 0,T.video=_?q:void 0;let X=this.isVideoContiguous,z=null==k?void 0:k.sampleCount;if(z){let e=k.keyFrameIndex,t=-1!==e;q.nb=z,q.dropped=0===e||X?0:t?e:z,q.independent=t,q.firstKeyFrame=e,t&&k.keyFrameStart&&(q.firstKeyFramePTS=(k.keyFrameStart-v.baseTime)/v.timescale),X||(T.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),q.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${z} dropped: ${q.dropped} start: ${q.firstKeyFramePTS||"NA"}`)}return T.initSegment=I,T.id3=si(i,s,v,v),r.samples.length&&(T.text=sr(r,s,v)),T}}function sa(e,t,i=!1){return(null==e?void 0:e.start)!==void 0?(e.start+(i?e.duration:0))/e.timescale:t}function sn(e,t,i){let r=e.codec;return r&&r.length>4?r:t===F.AUDIO?"ec-3"===r||"ac-3"===r||"alac"===r?r:"fLaC"===r||"Opus"===r?ta(r,!1):(i.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"):"mjpg"===r?r:(i.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1")}try{l=self.performance.now.bind(self.performance)}catch(e){l=Date.now}let sl=[{demux:rN,remux:ss},{demux:rV,remux:se},{demux:rC,remux:se},{demux:rF,remux:se}];sl.splice(2,0,{demux:rM,remux:se});class so{constructor(e,t,i,r,s,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupp
16orted=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=i,this.id=s,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,r){let s;if(!this.observer)return sh(i);let a=i.transmuxing;a.executeStart=l();let n=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:h}=this;r&&(this.currentTransmuxState=r);let{contiguous:d,discontinuity:u,trackSwitch:f,accurateTimeOffset:p,timeOffset:E,initSegmentChange:v}=r||o,{audioCodec:y,videoCodec:T,defaultInitPts:S,duration:A,initSegmentData:I}=h,L=(s=null,n.byteLength>0&&(null==t?void 0:t.key)!=null&&null!==t.iv&&null!=t.method&&(s=t),s);if(L&&ip(L.method)){let e=this.getDecrypter(),t=iE(L.method);return this.asyncResult=!0,this.decryptionPromise=e.decrypt(n,L.key.buffer,L.iv.buffer,t,i.decryptRange).then(e=>{let t=this.push(e,null,i);return this.decryptionPromise=null,t}),this.decryptionPromise}let R=this.needsProbing(u,f);if(R){let e=i.iframe&&I&&rV.probe(I,this.logger)?I:n,t=this.configureTransmuxer(e);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:c.MEDIA_ERROR,details:g.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),a.executeEnd=l(),sh(i)}(u||f||v||R)&&this.resetInitSegment(I,y,T,A,t,i),(u||v||R)&&this.resetInitialTimestamp(S),d||this.resetContiguity();let b=this.transmux(n,L,E,p,i);this.asyncResult=sd(b);let D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,a.executeEnd=l(),b}flush(e){let t=e.transmuxing;t.executeStart=l();let{decrypter:i,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(e));let a=[],{timeOffset:n}=r;if(i){let t=i.flush();t&&a.push(this.push(t.buffer,null,e))}let{demuxer:o,remuxer:h}=this;if(!o||!h){t.executeEnd=l();let i=[sh(e)];return this.asyncResult?Promise.resolve(i):i}let d=o.flush(n,e);return sd(d)?(this.asyncResult=!0,d.then(t=>(this.flushRemux(a,t,e),a))):(this.flushRemux(a,d,e),this.asyncResult)?Promise.resolve(a):a}flushRemux(e,t,i){if(!this.remuxer)return;let{audioTrack:r,videoTrack:s,id3Track:a,textTrack:n}=t,{accurateTimeOffset:o,timeOffset:h}=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 d=this.remuxer.remux(r,s,a,n,h,o,!0,this.id,i,t.initData,t.sampleData);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=l()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,s,a){let{demuxer:n,remuxer:l}=this;n&&l&&(n.resetInitSegment(e,t,i,r,s,a),l.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,t,i,r,s){return(null==t?void 0:t.method)==="SAMPLE-AES"?this.transmuxSampleAes(e,t,i,r,s):this.transmuxUnencrypted(e,i,r,s)}transmuxUnencrypted(e,t,i,r){let{demuxer:s,remuxer:a}=this;if(!s||!a)return sh(r);let n=s.demux(e,t,r,!1,!this.config.progressive),{audioTrack:l,videoTrack:o,id3Track:h,textTrack:d}=n;return{remuxResult:a.remux(l,o,h,d,t,i,!1,this.id,r,n.initData,n.sampleData),chunkMeta:r}}transmuxSampleAes(e,t,i,r,s){return this.demuxer?this.demuxer.demuxSampleAes(e,t,i,s).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,this.id,s,e.initData,e.sampleData),chunkMeta:s})):Promise.reject(Error("no demuxer"))}configureTransmuxer(e){let t;
16let{config:i,observer:r,typeSupported:s}=this;if(!r)return;try{for(let i=0,r=sl.length;i<r;i++){var a;if(null!=(a=sl[i].demux)&&a.probe(e,this.logger)){t=sl[i];break}}}catch(e){return e}if(!t)return Error("Failed to find demuxer by probing fragment data");let n=this.demuxer,l=this.remuxer,o=t.demux,h=t.remux;n&&n instanceof o||(this.logger.log(`Using ${o.name}`),this.demuxer=new o(r,i,s,this.logger),this.probe=o.probe),l&&l instanceof h||(this.logger.log(`Using ${h.name}`),this.remuxer=new h(r,i,s,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new t4(this.config)),e}}let sh=e=>({remuxResult:{},chunkMeta:e});function sd(e){return"then"in e&&e.then instanceof Function}class su{constructor(e,t,i,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null}}class sf{constructor(e,t,i,r,s,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=a}}let sc=0;class sg{constructor(e,t,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=sc++,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=e=>{let t=e.data,i=this.hls;if(i&&null!=t&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case"init":{var r;let e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,i.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;let t=Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:c.OTHER_ERROR,details:g.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};let s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;let a=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===m.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new ro,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);let n=to(s.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){let i=this.hls.logger;if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(i.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){let t=rd[e];if(t)return t.clientCount++,t;let i=new self.URL(e,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return rd[e]=r,r}(s.workerPath)):(i.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){let e=rd[rh];if(e)return e.clientCount++,e;let t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(t),r={worker:new self.Worker(i),objectURL:i,clientCount:1};return rd[rh]=r,r}());let{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:n,id:t,config:tR(s)})}catch(r){i.warn(`Error setting up "${t}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new so(this.observer,n,s,"",t,e.logger)}return}}this.transmuxer=new so(this.observer,n,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=sc++;let t=this.hls.config,i=to(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupp
16orted:i,id:this.id,config:tR(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){let t=rd[e||rh];if(t&&1==t.clientCount--){let{worker:i,objectURL:r}=t;delete rd[e||rh],r&&self.URL.revokeObjectURL(r),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,r,s,a,n,l,o,h){var d,u;o.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:c}=this,g=a?a.start:s.start,m=s.decryptdata,p=this.frag,E=!p||s.cc!==p.cc,v=!p||o.level!==p.level,y=p?o.sn-p.sn:-1,T=this.part?o.part-this.part.index:-1,S=0===y&&o.id>1&&o.id===(null==p?void 0:p.stats.chunkCount),A=!v&&(1===y||0===y&&(1===T||S&&T<=0)),I=self.performance.now();(v||y||0===s.stats.parsing.start)&&(s.stats.parsing.start=I),a&&(T||!A)&&(a.stats.parsing.start=I);let L=!(p&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=p.initSegment)?void 0:u.url)),R=new sf(E,A,l,v,g,L);if(!A||E||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${o.sn}${o.part>-1?" part: "+o.part:""} ${this.id} playlist: ${o.level} id: ${o.id} 17 discontinuity: ${E} 18 trackSwitch: ${v} 19 contiguous: ${A} 20 accurateTimeOffset: ${l} 21 timeOffset: ${g} 22 initSegmentChange: ${L}`);let e=new su(i,r,t,n,h);this.configureTransmuxer(e)}if(this.frag=s,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:m,chunkMeta:o,state:R},e instanceof ArrayBuffer?[e]:[]);else if(c){let t=c.push(e,m,o,R);sd(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,o,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let t=i.flush(e);sd(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class sm extends rr{constructor(e,t,i){super(e,t,i,"audio-stream-controller",w.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){let{frag:i,id:r,initPTS:s,timescale:a,trackId:n,timestampOffsets:l}=t;if(r===w.MAIN){let e=i.cc,t=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${e}
22 found from main: ${s/a} (${s}/${a}) trackId: ${n}`),this.mainAnchor=i,this.state===ri.WAITING_INIT_PTS){let t=this.waitingData;(t||this.loadingParts)&&(!t||t.frag.cc===e)||this.syncWithAnchor(i,null==t?void 0:t.frag)}else!this.hls.hasEnoughToStart&&t&&t.cc!==e?(t.abortRequests(),this.syncWithAnchor(i,t)):this.state===ri.IDLE&&this.tick()}}getLoadPosition(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&(null==(e=this.switchingTrack)?void 0:e.flushImmediate)!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;let r=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(t&&(null==r?void 0:r.cc)===t.cc)return;let s=(r||e).cc,a=tB(this.getLevelDetails(),s,this.getLoadPosition());a&&(this.log(`Syncing with main frag at ${a.start} cc ${a.cc}`),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===ri.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=ri.STOPPED;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===e&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=ri.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case ri.IDLE:this.doTickIdle();break;case ri.WAITING_TRACK:{let{levels:e,trackId:t}=this,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=ri.WAITING_INIT_PTS}break}case ri.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case ri.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:r,complete:s}=e,a=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=ri.FRAG_LOADING;let e={frag:t,part:i,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=ri.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())}doTickIdle(){var e;let{hls:t,levels:i,media:r,trackId:s}=this,a=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(null!=i&&i[s]))return;let n=i[s],l=n.details;if(!l||this.waitForLive(n)||this.waitForCdnTuneIn(l)){this.state=ri.WAITING_TRACK,this.startFragRequested=!1;return}let o=this.getBufferOutput();this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,F.AUDIO));let h=this.getFwdBufferInfo();if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,l)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=ri.ENDED;return}let d=h.len,u=t.maxBufferLength,f=l.fragments,c=f[0].start,g=this.getLoadPosition(),p=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?g:h.end;if(this.switchingTrack&&r&&l.PTSKnown&&g<c&&g>=this.timelineOffset&&(h.end>c||h.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${g} -> ${c} + 0.05`),r.currentTime=c+.05),d>=u&&!this.switchingTrack&&p<f[f.length-1].start)return;let E=this.getNextFragment(p,l);if(E&&this.isLoopLoading(E,p)&&(E=this.getNextFragmentLoopLoading(E,l,h,w.MAIN,u)),!E){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(h,u,E))return;let v=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&N(E)&&!E.endList&&(!l.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(v)===tq.OK&&(this.mainFragLoading=v=null),v&&N(v))){if(E.start>v.end){let e=this.fragmentTracker.getFragAtPos(p,w.MAIN);e&&e.end>v.end&&(v=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(E.start>v.end)return}this.loadFragment(E,n,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new tA(e))}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==ri.STOPPED&&(this.setInterval(100),this.state=ri.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i,r;let{levels:s}=this,{details:a,id:n,groupId:l,track:o}=t;if(!s){this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${l}"`);return}let h=this.mainDetails;if(!h||a.endCC>h.endCC||h.expired){this.cachedTrackLoadedData=t,this.state!==ri.STOPPED&&(this.state=ri.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${l}" loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`);let d=s[n],u=0;if(a.live||null!=(i=d.details)&&i.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d.details&&(u=this.alignPlaylists(a,d.details,null==(r=this.levelLastLoaded)?void 0:r.details)),a.alignedSliding||(i9(h,a,this),u=a.fragmentStart)}d.details=a,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(h,u),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:a,id:n,groupId:t.groupId}),this.state!==ri.WAITING_TRACK||this.waitForCdnTuneIn(a)||(this.state=ri.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:s}=e,{config:a,trackId:n,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let o=l[n];if(!o){this.warn("Audio track is undefined on fragment load progress");return}let h=o.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let d=a.defaultAudioCodec||o.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new sg(this.hls,w.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[i.cc],c=null==(t=i.initSegment)?void 0:t.data;if(void 0!==f){let e=r?r.index:-1,t=new ie(i.level,i.sn,i.stats.chunkCount,s.byteLength,e,-1!==e,i.duration);u.push(s,c,d,"",i,r,h.totalduration,!1,t,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${n}`);let{cache:e}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new rn,complete:!1};e.push(new Uint8Array(s)),this.state!==ri.STOPPED&&(this.state=ri.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===w.MAIN&&N(t.frag)&&(this.mainFragLoading=t,this.state===ri.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i.type!==w.AUDIO){this.audioOnly||i.type!==w.MAIN||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(N(i)){let e=this.switchingTrack;e&&(this.bufferedTrack=e)}this.fragBufferedComplete(i,r),this.media&&this.tick()}getFwdBufferInfo(){let e=this.getBufferOutput();return super.getFwdBufferInfo(e,w.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let t=this.fragPlaying,i=null==e?void 0:e.level;return(!t||t.level!==i)&&(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(e,t){var i;if(t.fatal){this.state=ri.ERROR;return}switch(t.details){case g.FRAG_GAP:case g.FRAG_PARSING_ERROR:case g.FRAG_DECRYPT_ERROR:case g.FRAG_LOAD_ERROR:case g.FRAG_LOAD_TIMEOUT:case g.KEY_LOAD_ERROR:case g.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(w.AUDIO,t);break;case g.AUDIO_TRACK_LOAD_ERROR:case g.AUDIO_TRACK_LOAD_TIMEOUT:case g.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==ri.WAITING_TRACK||(null==(i=t.context)?void 0:i.type)!==M.AUDIO_TRACK||(this.state=ri.IDLE);break;case g.BUFFER_APPEND_NO_PROGRESS:if("audio"!==t.parent)return;t.frag&&(t.appendsWithoutProgress||0)>
22=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of track ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case g.BUFFER_ADD_CODEC_ERROR:case g.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case g.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case g.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==F.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==F.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===ri.ENDED&&(this.state=ri.IDLE);let e=this.getBufferOutput();e&&(this.afterBufferFlushed(e,t),this.tick())}}_handleTransmuxComplete(e){var t;let i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:a}=e,n=this.getCurrentContext(a);if(!n){this.resetWhenMissingContext(a);return}let{frag:l,part:o,level:h}=n,{details:d}=h,{audio:u,text:f,id3:c,initSegment:g}=s;if(this.fragContextChanged(l)||!d){this.fragmentTracker.removeFragment(l),null!=g&&g.tracks&&this.resetTransmuxer();return}if(this.state=ri.PARSING,u&&this.switchingTrack&&!this.switchingTrack.flushImmediate){let{config:e}=this,t=e.nextAudioTrackBufferFlushForwardOffset,i=Math.max(this.getLoadPosition()+t,l.start);super.flushMainBuffer(i,Number.POSITIVE_INFINITY,w.AUDIO)}if(null!=g&&g.tracks){let e=l.initSegment||l;if(this.unhandledEncryptionError(g,l))return;this._bufferInitSegment(h,g.tracks,e,a),r.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:g.tracks})}if(u){let{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=u;o&&(o.elementaryStreams[F.AUDIO]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),l.setElementaryStreamInfo(F.AUDIO,e,t,i,r),this.bufferFragmentData(u,l,o,a)}if(null!=c&&null!=(t=c.samples)&&t.length){let e=K({id:i,frag:l,details:d},c);r.trigger(m.FRAG_PARSING_METADATA,e)}if(f){let e=K({id:i,frag:l,details:d},f);r.trigger(m.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,i,r){if(this.state!==ri.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let s=t.audio;s.id=w.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${a}/${s.codec}]`),(null==a?void 0:a.split(",").length)===1&&(s.levelCodec=a),this.hls.trigger(m.BUFFER_CODECS,t);let n=s.initSegment;if(null!=n&&n.byteLength){let e={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:n};this.hls.trigger(m.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===tq.NOT_LOADED||r===tq.PARTIAL){var s;if(null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=ri.WAITING_INIT_PTS;let i=this.mainDetails;i&&i.fragmentStart!==t.details.fragmentStart&&i9(i,t.details,this)}else super.loadFragment(e,t,i)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){let{name:t,lang:i,assocLang:r,characteristics:s,audioCodec:a,channels:n}=this.bufferedTrack;t_({name:t,lang:i,assocLang:r,characteristics:s,audioCodec:a,channels:n},e,tC)||(tM(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(m.AUDIO_TRACK_SWITCHED,H({},e))}get nextAudioTrack(){return this.nextTrackId}}class sp extends er{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){let r=null==t?void 0:t.renditionReports;if(r){let s=-1;for(let i=0;i<r.length;i++){let a;let n=r[i];try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){s=i;break}a===e.substring(0,a.length)&&(s=i)}if(-1!==s){let e=r[s],a=parseInt(e["LAST-MSN"])||t.lastPartSn,n=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let e=Math.min(t.age-t.partTarget,t.targetduration);n>=0&&e>t.partTarget&&(n+=1)}return new tS(a,n>=0?n:void 0,i&&tT(i))}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,i){let{details:r,stats:s}=t,a=r.fragments,n=self.performance.now(),l=s.loading.first?Math.max(0,Math.floor(n-s.loading.first)):0;r.advancedDateTime=Date.now()-l;let o=this.hls.config.timelineOffset;
22if(o!==r.appliedTimelineOffset){let e=Math.max(o||0,0);r.appliedTimelineOffset=e,a.forEach(t=>{null==t||t.setStart(t.playlistOffset+e)})}if(r.live||null!=i&&i.live){var h;let o,u,f;let p="levelInfo"in t?t.levelInfo:t.track;r.reloaded(i);let E=null==(h=a[a.length-1])?void 0:h.type;if(r.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){let e=Error(`${E} playlist ${p.id} hit max allowed unchanged reloads.`);this.warn(e);let{networkDetails:i,context:a}=t;this.hls.trigger(m.ERROR,{type:c.NETWORK_ERROR,details:g.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level,parent:E,context:a,networkDetails:i,stats:s});return}if(i){!function(e,t,i){let r;if(e===t)return;let s=null,a=e.fragments;for(let e=a.length-1;e>=0;e--){let t=a[e].initSegment;if(t){s=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){var r,s,a;let n=t.skippedSegments,l=Math.max(e.startSN,t.startSN)-t.startSN,o=(e.fragmentHint?1:0)+(n?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,h=t.startSN-e.startSN,d=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=null!=(r=e.fragmentHint)&&r.duration?e.fragments.concat(e.fragmentHint):e.fragments;for(let r=l;r<=o;r++){let l=u[h+r],o=d[r];if(n&&!o&&l&&(o=t.fragments[r]=l),l&&o){i(l,o,r,d);let n=l.relurl,h=o.relurl;if(n&&(s=n)!==(a=h)&&a&&i3(s)!==i3(a)){t.playlistParsingError=iQ(`media sequence mismatch ${o.sn}:`,e,t,l,o);return}if(l.cc!==o.cc){t.playlistParsingError=iQ(`discontinuity sequence mismatch (${l.cc}!=${o.cc})`,e,t,l,o);return}}}}(e,t,(e,i,a,n)=>{if((!t.startCC||t.skippedSegments)&&i.cc!==e.cc){let r=e.cc-i.cc;for(let e=a;e<n.length;e++)n[e].cc+=r;t.endCC=n[n.length-1].cc}d(e.startPTS)&&d(e.endPTS)&&(i.setStart(i.startPTS=e.startPTS),i.startDTS=e.startDTS,i.maxStartPTS=e.maxStartPTS,i.endPTS=e.endPTS,i.endDTS=e.endDTS,i.minEndPTS=e.minEndPTS,i.setDuration(e.endPTS-e.startPTS),i.duration&&(r=i),t.PTSKnown=t.alignedSliding=!0),e.hasStream
22s&&(i.elementaryStreams=e.elementaryStreams),i.loader=e.loader,e.hasStats&&(i.stats=e.stats),e.initSegment&&(i.initSegment=e.initSegment,s=e.initSegment)});let n=t.fragments,l=t.fragmentHint?n.concat(t.fragmentHint):n;if(s&&l.forEach(e=>{var t;e&&(!e.initSegment||e.initSegment.relurl===(null==(t=s)?void 0:t.relurl))&&(e.initSegment=s)}),t.skippedSegments){if(t.deltaUpdateFailed=n.some(e=>!e),t.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)n.shift();t.startSN=n[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){let{dateRanges:r,recentlyRemovedDateranges:s}=t,a=K({},e);s&&s.forEach(e=>{delete a[e]});let n=Object.keys(a).length;return n?(Object.keys(r).forEach(e=>{let t=a[e],s=new iu(r[e].attr,t);s.isValid?(a[e]=s,t||(s.tagOrder+=n)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${tR(r[e].attr)}"`)}),a):r}(e.dateRanges,t,i));let r=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<l.length;e++)null===l[e].programDateTime&&iY(l[e],l[e-1],r);iB(r,t)}t.endCC=n[n.length-1].cc}if(!t.startCC){var o;let i=i0(e,t.startSN-1);t.startCC=null!=(o=null==i?void 0:i.cc)?o:n[0].cc}if(function(e,t,i){if(e&&t){let r=0;for(let s=0,a=e.length;s<a;s++){let a=e[s],n=t[s+r];a&&n&&a.index===n.index&&a.fragment.sn===n.fragment.sn?i(a,n):r--}}}(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats,t.gap=e.gap||t.gap}),r){let e=t.iframesOnly&&r.type===w.MAIN;iz(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,e,i)}else iZ(e,t);n.length&&(t.totalduration=t.edge-n[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let h=t.advancedDateTime;if(t.advanced&&h){let e=t.edge;t.driftStart||(t.driftStartTime=h,t.driftStart=e),t.driftEndTime=h,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}(i,r,this);let e=r.playlistParsingError;if(e){this.warn(e);let i=this.hls;if(!i.config.ignorePlaylistParsingErrors){let{networkDetails:a}=t;i.trigger(m.ERROR,{type:c.NETWORK_ERROR,details:g.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level,parent:E,networkDetails:a,stats:s});return}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=s.loading.start);let v=this.hls.mainForwardBufferInfo,y=v?v.end-v.len:0,T=(r.edge-y)*1e3,S=iJ(r,T);r.requestScheduled+S<n?r.requestScheduled=n:r.requestScheduled<=n&&(r.requestScheduled+=S);let A=t.deliveryDirectives;if(this.log(`live playlist ${e} ${r.advanced?`REFRESHED ${r.lastPartSn} - ${r.lastPartIndex}`:r.updated?"UPDATED":`MISSED (received ${r.lastPartSn} - ${r.lastPartIndex}${A?` | requested ${A.msn} - ${A.part}`:""})`}`),!this.canLoad||!r.live)return;if(r.canBlockReload&&r.endSN&&r.advanced){let e=this.hls.config.lowLatencyMode,s=r.lastPartSn,a=r.endSN,l=r.lastPartIndex,h=s===a;-1!==l?h?(u=a+1,f=e?0:l):(u=s,f=e?l+1:r.maxPartIndex):u=a+1;let d=r.age,c=d+r.ageHeader,g=Math.min(c-r.partTarget,1.5*r.targetduration);if(g>0){if(c>3*r.targetduration)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),u=void 0,f=void 0;else if(null!=i&&i.tuneInGoal&&c-r.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${g} with playlist age: ${r.age}`),g=0;else{let e=Math.floor(g/r.targetduration);u+=e,void 0!==f&&(f+=Math.round(g%r.targetduration/r.partTarget)),this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${g} skip sn ${e} to part ${f}`)}r.tuneInGoal=g}if(o=this.getDeliveryDirectives(r,t.deliveryDirectives,u,f),e||!h){r.requestScheduled=n,this.loadingPlaylist(p,o);return}}else(r.canBlockReload||r.canSkipUntil)&&(o=this.getDeliveryDirectives(r,t.deliveryDirectives,u,f));o&&void 0!==u&&r.canBlockReload&&(r.requestScheduled=s.loading.first+Math.max(S-2*l,S/2)),this.scheduleLoading(p,o,r)}else this.clearTimer()}scheduleLoading(e,t,i){let r=i||e.details;if(!r){this.loadingPlaylist(e,t);return}let s=self.performance.now(),a=r.requestScheduled;if(s>=a){this.loadingPlaylist(e,t);return}let n=a-s;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(n)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),n)}getDeliveryDirectives(e,t,i,r){let s=tT(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=ty.No),new tS(i,r,s)}checkRetry(e){let t=e.details,i=W(e),r=e.errorAction,{action:s,retryCount:a=0,retryConfig:n}=r||{},l=!!r&&!!n&&(s===tK.RetryRequest||!r.resolved&&s===tK.SendAlternateToPenaltyBox);if(l){var o,h;if(a>=n.maxNumRetry)return!1;if(i&&null!=(o=e.context)&&o.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${n.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let i=J(null==(h=e.response)?void 0:h.code);
22if(this.clearTimer(),i)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{let e=z(n,a);this.warn(`Retrying playlist loading ${a+1}/${n.maxNumRetry} after "${t}" in ${e}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),e)}}e.levelRetry=!0,r.resolved=!0}return l}checkOfflineStatus(){this.clearTimer(),J(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function sE(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!sv(e[i].attrs,t[i].attrs))return!1;return!0}function sv(e,t,i){let r=e["STABLE-RENDITION-ID"];return r&&!i?r===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>e[i]!==t[i])}class sy extends sp{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:i,groupId:r,details:s}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Audio track with id:${i} and group:${r} not found in active group ${null==a?void 0:a.groupId}`);return}let n=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,n)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some(e=>(null==r?void 0:r.indexOf(e))===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>tw(e.groupId,i));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.audioPreference;if(!s&&t){let i=tP(t,e,tC);if(i>-1)s=e[i];else{let e=tP(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null)),this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,{audioTracks:e});let n=this.trackId;if(-1!==r&&-1===n)this.setAudioTrack(r);else if(e.length&&-1===n){var a;let t=Error(`No audio track selected for current audio group-ID(s): ${null==(a=this.groupIds)?void 0:a.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&t.context.type===M.AUDIO_TRACK&&t.context.id===this.trackId&&tw(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let i=this.allAudioTracks;
22if(this.selectDefaultTrack=!1,i.length){let r=this.currentTrack;if(r&&t_(e,r,tC))return r;let s=tP(e,this.tracksInGroup,tC);if(s>-1){let t=this.tracksInGroup[s];return this.setAudioTrack(s,"flushImmediate"in e&&e.flushImmediate),t}if(r){let r=t.loadLevel;-1===r&&(r=t.firstAutoLevel);let s=function(e,t,i,r,s){let a=t[r],n=t.reduce((e,t,i)=>{let r=t.uri;return(e[r]||(e[r]=[])).push(i),e},{})[a.uri];n.length>1&&(r=Math.max.apply(Math,n));let l=a.videoRange,o=a.frameRate,h=a.codecSet.substring(0,4),d=tO(t,r,t=>{if(t.videoRange!==l||t.frameRate!==o||t.codecSet.substring(0,4)!==h)return!1;let r=t.audioGroups;return tP(e,i.filter(e=>tw(e.groupId,r)),s)>-1});return d>-1?d:tO(t,r,t=>{let r=t.audioGroups;return tP(e,i.filter(e=>tw(e.groupId,r)),s)>-1})}(e,t.levels,i,r,tC);if(-1===s)return null;t.nextLoadLevel=s}if(e.channels||e.audioCodec){let t=tP(e,i);if(t>-1)return i[t]}}}return null}setAudioTrack(e,t=!0){let i=this.tracksInGroup;if(e<0||e>=i.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let r=this.currentTrack,s=i[e],a=s.details&&!s.details.live;if(e===this.trackId&&s===r&&a||(this.log(`Switching to audio-track ${e} "${s.name}" lang:${s.lang} group:${s.groupId} channels:${s.channels}`),this.trackId=e,this.currentTrack=s,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,H(H({},s),{},{flushImmediate:t})),a))return;let n=this.switchParams(s.url,null==r?void 0:r.details,s.details);this.loadPlaylist(n)}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if((!this.selectDefaultTrack||r.default)&&(!e||t_(e,r,tC)))return i}if(e){let{name:i,lang:r,assocLang:s,characteristics:a,audioCodec:n,channels:l}=e;for(let e=0;e<t.length;e++)if(t_({name:i,lang:r,assocLang:s,characteristics:a,audioCodec:n,channels:l},t[e],tC))return e;for(let i=0;i<t.length;i++){let r=t[i];if(sv(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){let r=t[i];if(sv(e.attrs,r.attrs,["LANGUAGE"]))return i}}return -1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&tM(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,s=this.getUrlWithDirectives(e.url,t),a=e.details,n=null==a?void 0:a.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${r}${(null==t?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n&&a.live?" age "+n.toFixed(1)+(a.type?" "+a.type:""):""} ${s}`),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:t||null,track:e})}}class sT{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(null===this.queues||null===this.tracks)return;let r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}appendBlocker(e){return new Promise(t=>{this.append({label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}},e)})}prependBlocker(e){return new Promise(t=>{this.queues&&this.queues[e].unshift({label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}})})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let i=null==(t=e[0])?void 0:t.label;"async-blocker"===i||"async-blocker-prepend"===i?(e[0].execute(),e.splice(0,1)):"block-audio"===i&&e.splice(0,1)})}insertNext(e,t){null!==this.queues&&this.queues[t].splice(1,0,...e)}unblockAudio(){var e;null!==this.queues&&(null==(e=this.current("audio"))?void 0:e.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return null!==this.queues&&this.queues.audio.some(e=>"block-audio"===e.label)}executeNext(e){if(null===this.queues||null===this.tracks)return;let t=this.queues[e];if(t.length){let r=t[0];try{r.execute()}catch(s){var i;if(r.onError(s),null===this.queues||null===this.tracks)return;let t=null==(i=this.tracks[e])?void 0:i.buffer;null!=t&&t.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":` 23${this.list("video")} 24${this.list("audio")} 25${this.list("audiovideo")}}`}list(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=null==(t=this.tracks)?void 0:t[e],r=null==i?void 0:i.buffer;return r?`SourceBuffer${r.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}}let sS=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,sA="HlsJsTrackRemovedError";
25class sI extends Error{constructor(e){super(e),this.name=sA}}class sL extends er{constructor(e,t){var i;super("buffer-controller",e.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=e=>{var t;this.hls&&(null==(t=this.mediaSource)?void 0:t.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{let{media:t,mediaSource:i}=this;e&&this.log("Media source opened"),t&&i&&(re(i,"sourceopen",this._onMediaSourceOpen),re(t,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTA
25CHED,{media:t,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){let e=this.media.error,{appendError:t,appendErrors:i}=this,r=!1;!t&&e&&(r=Math.max(++i.audio,++i.video,++i.audiovideo)>=this.hls.config.appendErrorMaxRetry);let s=Error(`MediaSource closed while media attached${sD(r,e)}`);this.warn(s),this.hls.trigger(m.ERROR,K({fatal:r},t,{type:c.MEDIA_ERROR,details:g.MEDIA_SOURCE_REQUIRES_RESET,error:s}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this._onMediaError=()=>{let{media:e}=this;if(e){var t,i;this.log(`Media error (code: ${null==(t=e.error)?void 0:t.code}): ${null==(i=e.error)?void 0:i.message}`)}},this.hls=e,this.fragmentTracker=t,this.appendSource=(i=eh(e.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){let{hls:e}=this;
25e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_APPENDING,this.onBufferAppending,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.BUFFER_EOS,this.onBufferEos,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.FRAG_PARSED,this.onFragParsed,this),e.on(m.FRAG_CHANGED,this.onFragChanged,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_APPENDING,this.onBufferAppending,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_EOS,this.onBufferEos,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.FRAG_PARSED,this.onFragParsed,this),e.off(m.FRAG_CHANGED,this.onFragChanged,this),e.off(m.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let i={};if(this.operationQueue){let e=this.isUpdating();e||this.operationQueue.removeBlockers();let t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}let r=this.transferData;return r&&!this.sourceBufferCount&&r.mediaSource===t?K(i,r.tracks):this.sourceBuffers.forEach(e=>{let[t]=e;t&&(i[t]=K({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var i;let r=2;(!t.audio||t.video)&&t.altAudio||(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){let i=this.media=t.media;this.transferData=this.overrides=void 0;let r=eh(this.appendSource);if(r){let e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let s=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(s),e)this._objectUrl=i.src,this.attachTransferred();else{let e=this._objectUrl=self.URL.createObjectURL(s);if(this.appendSource)try{i.removeAttribute("src");let t=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||t&&s instanceof t,sR(i),function(e,t){let i=self.document.createElement("source");i.type="video/mp4",i.src=t,e.appendChild(i)}(i,e),i.load()}catch(t){i.src=e}else i.src=e}i7(i,"emptied",this._onMediaEmptied),i7(i,"error",this._onMediaError)}}assignMediaSource(e){var t,i;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${null==(i=e.constructor)?void 0:i.name}`),i7(e,"sourceopen",this._onMediaSourceOpen),i7(e,"sourceended",this._onMediaSourceEnded),i7(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(i7(e,"startstreaming",this._onStartStreaming),i7(e,"endstreaming",this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let i=this.tracks,r=t.tracks,s=r?Object.keys(r):null,a=s?s.length:0,n=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(r&&s&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) 26required tracks: ${tR(i,(e,t)=>"initSegment"===e?void 0:t)}; 27transfer tracks: ${tR(r,(e,t)=>"initSegment"===e?void 0:t)}}`),!ed(r,i)){t.mediaSource=null,t.tracks=void 0;let s=e.currentTime,a=this.details,n=Math.max(s,(null==a?void 0:a.fragments[0].start)||0);if(n-s>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${s} -> ${n}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(i)}") start time: ${n} currentTime: ${s}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}
27),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=n;return}this.transferData=void 0,s.forEach(e=>{let t=r[e];if(t){let i=t.buffer;if(i){let r=this.fragmentTracker,s=t.id;if(r.hasFragments(s)||r.hasParts(s)){let t=ir.getBuffered(i);r.detectEvictedFragments(e,t,s,null,null,!0)}let a=sb(e),n=[e,i];this.sourceBuffers[a]=n,i.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,t)}}}),n(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),n()}get mediaSourceOpenOrEnded(){var e;let t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){let i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:s,_objectUrl:a}=this;if(s){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let e="open"===s.readyState;try{let t=s.sourceBuffers;for(let i=t.length;i--;)e&&t[i].abort(),s.removeSourceBuffer(t[i]);e&&s.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}re(s,"sourceopen",this._onMediaSourceOpen),re(s,"sourceended",this._onMediaSourceEnded),re(s,"sourceclose",this._onMediaSourceClose),this.appendSource&&(re(s,"startstreaming",this._onStartStreaming),re(s,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(re(r,"emptied",this._onMediaEmptied),re(r,"error",this._onMediaError),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&sR(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t,i;let r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[sb(e)]=[null,null];let t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new sT(this.tracks)}onBufferCodecs(e,t){var i;let r=this.tracks,s=Object.keys(t);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),n=!a&&this.sourceBufferCount&&this.media&&s.some(e=>!r[e]);if(a||n){this.warn(`Unsupported transition between "${Object.keys(r)}" and "${s}" SourceBuffers`);return}s.forEach(e=>{var i,s;let{id:a,codec:n,levelCodec:l,container:o,metadata:h,supplemental:d}=t[e],u=r[e],f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[e],c=null!=f&&f.buffer?f:u,g=(null==c?void 0:c.pendingCodec)||(null==c?void 0:c.codec),m=null==c?void 0:c.levelCodec;u||(u=r[e]={buffer:void 0,listeners:[],codec:n,supplemental:d,container:o,levelCodec:l,metadata:h,id:a});let p=tn(g,m),E=null==p?void 0:p.replace(sS,"$1"),v=tn(n,l),y=null==(s=v)?void 0:s.replace(sS,"$1");v&&p&&E!==y&&("audio"===e.slice(0,5)&&(v=ta(v,this.appendSource)),this.log(`switching codec ${g} to ${v}`),v!==(u.pendingCodec||u.codec)&&(u.pendingCodec=v),u.container=o,this.appendChangeType(e,o,v))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(!(this.bufferCodecEventsTotal>1)||this.tracks.video||t.video||(null==(i=t.audio)?void 0:i.id)!=="main"||(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let r=`${t};codecs=${i}`,s={label:`change-type=${r}`,execute:()=>{let s=this.tracks[e];if(s){let a=s.buffer;null!=a&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),a.changeType(r),s.codec=i,s.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let i=e.start,r=i+.05*e.duration;(null==(t=this.fragmentTracker.getAppendedFrag(i,w.MAIN))?void 0:t.gap)!==!0&&this.append({label:"block-audio",execute:()=>{var e,t;(this.lastVideoAppendEnd>r||ir.isBuffered(null==(e=this.tracks.video)?void 0:e.buffer,r)||(null==(t=this.fragmentTracker.getAppendedFrag(r,w.MAIN))?void 0:t.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}},"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){let{tracks:i}=this,{data:r,type:s,parent:a,frag:n,part:l,chunkMeta:o,offset:h}=t,u=o.buffering[s],f=N(n)&&!l&&!n.gap&&!o.partial&&!o.iframe,p=null,E=!1,{sn:v,cc:y}=n,T=self.performance.now();u.start=T;let S=n.stats.buffering,A=l?l.stats.buffering:null;0===S.start&&(S.start=T),(null==A?void 0:A.start)===0&&(A.start=T);let I=i.audio,L=!1;"audio"===s&&(null==I?void 0:I.container)==="audio/mpeg"&&(L=!this.lastMpegAudioChunk||1===o.id||this.lastMpegAudioChunk.sn!==o.sn,this.lastMpegAudioChunk=o);let R=i.video,b=null==R?void 0:R.buffer;if(b&&"initSegment"!==v&&void 0!==h){let e=null==I?void 0:I.buffer,t=l||n;if("audio"===s&&"main"!==a&&!(R.ending||R.ended)&&e&&ir.getBuffered(e).length){let e=t.start+.05*t.duration,i=ir.getBuffered(b),r=this.currentOp("video");i.length||r?!ir.isBuffered(b,e)&&this.lastVideoAppendEnd<e&&this.blockAudio(t):this.blockAudio(t)}else if("video"===s){let e=t.end,i=this.lastVideoAppendEnd-e;this.lastVideoAppendEnd=e,i<0||i>t.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}let D=(l||n).start,k={label:`append-${s}`,execute:()=>{var e;u.executeStart=self.performance.now();let t=null==(e=this.tracks[s])?void 0:e.buffer;t&&(f&&(E=s_(sP(p=ir.timeRangesToArray(ir.getBuffered(t)),n),n)),L?this.updateTimestampOffset(t,D,.1,s,v,y):void 0!==h&&d(h)&&this.updateTimestampOffset(t,h,1e-6,s,v,y)),this.appendExecutor(r,s)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[s]);let e=self.performance.now();u.executeEnd=u.end=e,0===S.first&&(S.first=e),(null==A?void 0:A.first)===0&&(A.first=e);let t={};
27if(this.sourceBuffers.forEach(([e,i])=>{e&&(t[e]=ir.getBuffered(i))}),f){let e=this.getFragmentAppendProgress(n),i=t[s];if(i&&p){let t=sP(ir.timeRangesToArray(i),n);e.progressed||(e.progressed=t-sP(p,n)>.001);let r=E&&s_(t,n);e.fullyBuffered[s]=void 0===e.fullyBuffered[s]?r:e.fullyBuffered[s]&&r}}this.hls.trigger(m.BUFFER_APPENDED,{type:s,frag:n,part:l,chunkMeta:o,parent:a,timeRanges:t})},onError:e=>{var t,i;this.clearBufferAppendTimeoutId(this.tracks[s]);let h=e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e;if(h&&!this._quotaEvictionPending[s]){let e=this.getBackBufferEvictionTarget(s,r.byteLength,n.type);if(e>0){this._quotaEvictionPending[s]=!0,this.log(`QuotaExceededError on "${s}" append sn: ${v} - evicting back buffer to ${e.toFixed(3)}s and retrying`);let t=this.getFlushOp(s,0,e),i=this.getClearEvictionPendingOp(s);this.insertNext([t,k,i],s);return}this.warn(`QuotaExceededError on "${s}" sn: ${v} - no back buffer available to evict`)}f&&(this.getFragmentAppendProgress(n).errored=!0);let d={type:c.MEDIA_ERROR,parent:a,details:g.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:n,part:l,chunkMeta:o,error:e,err:e,fatal:!1},u=null==(t=this.media)?void 0:t.error;if(e.name!==sA||0!==this.sourceBufferCount||this.media&&0!==this.pendingTrackCount){h&&(d.details=g.BUFFER_FULL_ERROR);let t=++this.appendErrors[s],r=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${t}/${r+1} times to append segment in "${s}" sourceBuffer with error: ${e.message}`),t>=r&&(d.fatal=!h);let a=null==(i=this.mediaSource)?void 0:i.readyState;("ended"===a||"closed"===a||u)&&(this.warn(`MediaSource readyState "${a}" during SourceBuffer${sD(d.fatal,u)}`),d.details=g.MEDIA_SOURCE_REQUIRES_RESET)}else d.errorAction=tj(!0);this.appendError=d,this.hls.trigger(m.ERROR,d),h&&this.hls&&this.trimBuffers(n.start,1)}};this.log(`queuing "${s}" append sn: ${v}${l?" p: "+l.index:""} of ${a} playlist ${n.level} cc: ${y} offset: ${h} bytes: ${r.byteLength}`),this.append(k,s,this.isPending(this.tracks[s]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{var r;let s=null==(r=this.tracks[e])?void 0:r.buffer;this.log(`Remove request ${t}-${i} from ${e} Source Buffer complete > buffer: ${s?rt(ir.getBuffered(s)):"(detached)"}`),this.hls.trigger(m.BUFFER_FLUSHED,{type:e,start:t,end:i})},onError:r=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,r),this.hls.trigger(m.BUFFER_FLUSHED,{type:e,start:0,end:0,error:r})}}}onBufferFlushing(e,t){let{type:i,startOffset:r,endOffset:s}=t;i&&"audio"!==i||this.unblockAudio(),i?this.append(this.getFlushOp(i,r,s),i):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,r,s),e)})}onFragParsed(e,t){let{frag:i,part:r,chunkMeta:s}=t,a=[],n=r?r.elementaryStreams:i.elementaryStreams;n[F.AUDIOVIDEO]?a.push("audiovideo"):(n[F.AUDIO]&&a.push("audio"),n[F.VIDEO]&&a.push("video")),0===a.length&&this.log(`Fragments must have at least one ElementaryStreamType set. ${i.type} ${i.level} ${r?`part: ${r.index} of `:""}sn: ${i.sn}`),this.blockBuffers(()=>{let e=self.performance.now();i.stats.buffering.end=e,r&&(r.stats.buffering.end=e);let t=r?r.stats:i.stats;this.checkAppendProgress(i,r,s,a),this.hls&&(this.hls.trigger(m.FRAG_BUFFERED,{frag:i,part:r,stats:t,id:i.type,chunkMeta:s}),!r&&i.gap&&t.retry&&this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${t.retry}`))},a).catch(e=>{this.warn(`Fragment buffered callback ${e.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var i,r;let s=null==(i=this.hls)?void 0:i.config;if(!s)return;let{backBufferLength:a,frontBufferFlushThreshold:n}=s;this.trimBuffers(n,a,t.frag,t.previousFrag);let l=t.frag.elementaryStreams,{appendErrors:o}=this,h=null==(r=this.appendError)?void 0:r.sourceBufferName;Object.keys(l).forEach(e=>
27{l[e]&&(o[e]=0,e===h&&(this.appendError=void 0),"audio"===e||"video"===e?(o.audiovideo=0,"audiovideo"===h&&(this.appendError=void 0)):(o.audio=0,o.video=0,"audiovideo"!==h&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([e])=>{if(e){let i=this.tracks[e];t.type&&t.type!==e||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${e} buffer reached EOS`)))}});let r=(null==(i=this.overrides)?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?(this.unblockAudio(),r?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:e}=this;if((null==e?void 0:e.readyState)!=="open"){e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(m.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(m.BUFFERED_TO_END,void 0))):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===g.BUFFER_APPEND_ERROR&&t.frag){var i;let e=null==(i=t.errorAction)?void 0:i.nextAutoLevel;d(e)&&e!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,i){let{media:r}=this;return r?this.fragmentTracker.getBackBufferEvictionEnd(r.currentTime,i,t):0}getFragmentAppendProgress(e){var t;let i=sk(e),r=this.fragmentAppendProgress[i];return(null==(t=r)?void 0:t.stats)!==e.stats&&(r={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[i]=r),r}checkAppendProgress(e,t,i,r){if(t||!N(e)||e.gap||i.iframe||i.partial)return;let s=sk(e),a=this.fragmentAppendProgress[s];delete this.fragmentAppendProgress[s];let n=(null==a?void 0:a.stats)===e.stats?a:void 0;if(null!=n&&n.errored)return;let l=r.length>0&&r.every(e=>(null==n?void 0:n.fullyBuffered[e])===!0);if(null!=n&&n.progressed||l){delete this.appendsWithoutProgress[s];return}if(!n&&0===r.length)return;let o=(this.appendsWithoutProgress[s]||0)+1,h=this.hls;o>=h.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[s]:this.appendsWithoutProgress[s]=o,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${o} time${o>1?"s":""} without buffered range growth`),h.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:i,parent:e.type,appendsWithoutProgress:o,error:Error(`Fragment append did not increase buffered coverage (${o})`)})}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(e,t,i,r){let{hls:s,details:a,media:n}=this;if(!n||null===a||!this.sourceBufferCount)return;let l=s.config,o=n.currentTime,h=a.levelTargetDuration;t=a.live&&null!==l.liveBackBufferLength?l.liveBackBufferLength:t;let u=-1/0;if(d(t)&&t>=0){let e=Math.max(t,h);u=Math.floor(o/h)*h-e}if(i){let e=this.getLoopBackBufferFlushEnd(i,null!=r?r:null);e>0&&(u=Math.max(u,e))}if(u>0&&this.flushBackBuffer(o,h,u),d(e)&&e>0){let t=Math.max(Math.max(l.maxBufferLength,e),h);this.flushFrontBuffer(o,h,Math.floor(o/h)*h+t)}}getLoopBackBufferFlushEnd(e,t){var i;let{media:r}=this;if((null==(i=this.hls)?void 0:i.config.loopBackBufferFlush)===!1||!(null!=r&&r.loop)||!t||e.level<=t.level)return 0;let{video:s,audiovideo:a}=e.elementaryStreams;if(null!=s&&s.partial||null!=a&&a.partial)return 0;let n=this.getEarliestElementaryStreamStart(e)-.25;return n<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${n.toFixed(3)}]`),n)}getEarliestElementaryStreamStart(e){let{audio:t,video:i,audiovideo:r}=e.elementaryStreams,s=e.start;return r?s=Math.min(s,r.startDTS):(t&&(s=Math.min(s,t.startDTS)),i&&(s=Math.min(s,i.startDTS))),s}
27flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([e,t])=>{if(t){let n=ir.getBuffered(t);if(n.length>0&&i>n.start(0)){var r,s,a;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:i});let t=this.tracks[e];if(null!=(r=this.details)&&r.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=t&&t.ended&&!(null!=(s=this.media)&&s.loop&&(null==(a=this.hls)?void 0:a.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:e})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([t,r])=>{if(r){let s=ir.getBuffered(r),a=s.length;if(a<2)return;let n=s.start(a-1),l=s.end(a-1);i>n||e>=n&&e<=l||this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:n,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||(null==i?void 0:i.readyState)!=="open")return null;let r=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){let e=Math.max(0,t.fragmentStart),i=Math.max(e,r);return{duration:1/0,start:e,end:i}}return{duration:1/0}}let s=null==(e=this.overrides)?void 0:e.duration;if(s)return d(s)?{duration:s}:null;let a=this.media.duration;return r>(d(i.duration)?i.duration:0)&&r>a||!d(a)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:i}){let r=this.mediaSource;r&&this.media&&"open"===r.readyState&&(r.duration!==e&&(d(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),void 0!==t&&void 0!==i&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${i}.`),r.setLiveSeekableRange(t,i)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${tR(i)}`),this.tracksReady){var r;let e=null==(r=this.transferData)?void 0:r.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let r=this.tracks[t];e[t]={buffer:i,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(m.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{let e=Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(let s in e){let a=e[s];if(this.isPending(a)){let e=this.getTrackCodec(a,s),n=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${n})${this.currentOp(s)?" Queued":""} ${tR(a)}`);try{let e=i.addSourceBuffer(n),r=sb(s),l=[s,e];t[r]=l,a.buffer=e}catch(e){var r;this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(s),null==(r=this.operationQueue)||r.removeBlockers(),delete this.tracks[s],this.hls.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:s,mimeType:n,parent:a.id});return}this.trackSourceBuffer(s,a)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}getTrackCodec(e,t){let i=e.supplemental,r=e.codec;i&&("video"===t||"audiovideo"===t)&&e9(i,"video")&&(r=function(e,t){let i=[];if(e){let t=e.split(",");for(let e=0;e<t.length;e++)e6(t[e],"video")||i.push(t[e])}return t&&i.push(t),i.join(",")}(r,i));let s=tn(r,e.levelCodec);return s?"audio"===t.slice(0,5)?ta(s,this.appendSource):s:""}trackSourceBuffer(e,t){let i=t.buffer;if(!i)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(e,t)=>{let i=t.removedRanges;null!=i&&i.length&&(this.log(`${e} buffer removed ${rt(i)}`),this.hls.trigger(m.BUFFER_FLUSHED,{type:e,start:i.start(0),end:i.end(i.length-1)}))})}get mediaSrc(){var e,t;let i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,i;if((null==(t=this.mediaSource)?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let r=this.currentOp(e);if(r){if(r.onComplete(),null==(i=this.tracks[e])||null==(i=i.buffer)?void 0:i.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}}onSBUpdateError(e,t){var i;let r=null==(i=this.mediaSource)?void 0:i.readyState,s=Error(`${e} SourceBuffer error. MediaSource readyState: ${r}`);this.error(`${s.message}`,t),this.hls.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});let a=this.currentOp(e);a&&a.onError(s)}updateTimestampOffset(e,t,i,r,s,a){Math.abs(t-e.timestampOffset)>=i&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${s} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){let{media:r,mediaSource:s}=this,a=this.tracks[e],n=null==a?void 0:a.buffer;if(!r||!s||!n)throw Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);let l=d(r.duration)?r.duration:1/0,o=d(s.duration)?s.duration:1/0,h=Math.max(0,t);if(h>=o){var u;null==(u=this.currentOp(e))||u.onComplete(),this.shiftAndExecuteNext(e);return}let f=Math.min(i,l,o);if(f>h&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${h},${f}] from the ${e} SourceBuffer`),n.remove(h,f);else throw Error(`Cannot remove ${f<=h?`invalid range (${h} >= ${f}) `:""}from the ${e} SourceBuffer${a.ending?" while track ending":""}`)}appendExecutor(e,t){let i=this.tracks[t],r=null==i?void 0:i.buffer;if(!r)throw new sI(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){let e=this.calculateAppendTimeoutTime(r);i.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,r,e),e)}r.appendBuffer(e)}appendTimeoutHandler(e,t,i){this.log(`Received timeout after ${i}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch(t){this.log(`Failed to abort append on ${e} source buffer after timeout.`)}let r=this.currentOp(e);r&&r.onError(Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=10;this.details&&(t=this.details.levelTargetDuration);let i=2*t*1e3;if(null===this.media)return i;let r=ir.bufferInfo(e,this.media.currentTime,0);return r.len?(i=Math.max(1e3*r.len,i),Math.max(this.hls.config.appendTimeout,i)):i}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}
27`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return(null==(e=this.currentOp("audio"))?void 0:e.label)==="block-audio"}isAudioBlocking(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:i}=this;return Promise.all(2===t.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(e=>this.appendBlocker(e))).then(t=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;let i=null==(t=this.tracks[e])?void 0:t.buffer;!i||i.updating||"audio"===e&&this.isAudioBlocked()||this.shiftAndExecuteNext(e)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}insertNext(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){let r=this.tracks[e];if(!r)return;let s=r.buffer;if(!s)return;let a=i.bind(this,e);r.listeners.push({event:t,listener:a}),i7(s,t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;i&&(t.listeners.forEach(e=>{re(i,e.event,e.listener)}),t.listeners.length=0)}}function sR(e){let t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function sb(e){return"audio"===e?1:0}function sD(e,t){return`${e?"":" - triggering recovery"}${t?" with HTMLMediaElement Error: "+t.message:""}`}function sk(e){return`${e.type}_${e.sn}_${e.level}`}function sP(e,t){let{start:i,end:r}=t,s=0;for(let t=0;t<e.length;t++){let a=e[t];if(a.start>=r)break;let n=Math.max(i,a.start),l=Math.min(r,a.end);l>n&&(s+=l-n)}return s}function s_(e,t){return t.duration-e<=.001}class sC{constructor(e){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=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){let{hls:e}=this;e&&(e.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(m.MEDIA_ATTA
27CHING,this.onMediaAttaching,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){let{hls:e}=this;e&&(e.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){let i=t.media;this.clientRect=null,this.hls&&(i instanceof HTMLVideoElement?(this.media=i,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(e,t){this.restrictedLevels=[],t.video&&this.startCapping()}onLevelsUpdated(e,{levels:t}){(this.timer||this.observer)&&d(this.autoLevelCapping)?this.detectPlayerSize():void 0===this.observer&&void 0===this.timer&&t.length>1&&t.some(e=>!!e.videoCodec)&&this.startCapping()}onBufferCodecs(e,t){t.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 e=this.hls.levels;if(e.length>1){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else 1===e.length&&this.stopCapping()}}getMaxLevel(e){if(!this.hls)return -1;let t=this.hls.levels;if(!t.length)return -1;let i=t.filter((t,i)=>this.isLevelAllowed(t)&&i<=e);return this.observer||(this.clientRect=null),sC.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){let e=self.ResizeObserver;e&&(this.observer=new e(e=>{var t;let i=null==(t=e[0])?void 0:t.contentRect;i&&(this.clientRect=i,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var e;this.timer||this.observer||null==(e=this.hls)||!e.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;let{ignoreDevicePixelRatio:t,maxDevicePixelRatio:i}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,i)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,i){if(!(null!=e&&e.length))return -1;let r=(e,t)=>!t||e.width!==t.width||e.height!==t.height,s=e.length-1,a=Math.max(t,i);for(let t=0;t<e.length;t+=1){let i=e[t];if((i.width>=a||i.height>=a)&&r(i,e[t+1])){s=t;break}}return s}}var sO=class e{constructor(t,i){Array.isArray(t)&&(t=t.map(t=>t instanceof e?t:new e(t))),this.value=t,this.params=i}};let sM="Bare Item",sw=/[\x00-\x1f\x7f]+/;var sF=class{constructor(e){this.description=e}};function sx(e,t,i){return Error(`failed to serialize "${Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":"object"==typeof e?JSON.stringify(e):String(e)}" as ${t}`,{cause:i})}function sN(e){if(e<-999999999999999||999999999999999<e)throw sx(e,"Integer");return e.toString()}function s$(e){let t=e.description||e.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw sx(t,"Token");return t}function sU(e){switch(typeof e){case"number":if(!d(e))throw sx(e,sM);if(Number.isInteger(e))return sN(e);return function(e){let t=function e(t,i){if(t<0)return-e(-t,i);let r=Math.pow(10,i);if(!(Math.abs(t*r%1-.5)<Number.EPSILON))return Math.round(t*r)/r;{let e=Math.floor(t*r);return(e%2==0?e:e+1)/r}}(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw sx(e,"Decimal");let i=t.toString();return i.includes(".")?i:`${i}.0`}(e);case"string":return function(e){if(sw.test(e))throw sx(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(e);case"symbol":return s$(e);case"boolean":return function(e){if("boolean"!=typeof e)throw sx(e,"Boolean");return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return`@${sN(e.getTime()/1e3)}`;if(e instanceof Uint8Array)return function(e){if(!1===ArrayBuffer.isView(e))throw sx(e,"Byte Sequence");return`:${btoa(String.fromCharCode(...e))}:`}(e);if(e instanceof sF)return s$(e);default:throw sx(e,sM)}}function sB(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw sx(e,"Key");return e}function sG(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${sB(e)}`:`;${sB(e)}=${sU(t)}`).join("")}function sK(e){return e instanceof sO?`${sU(e.value)}${sG(e.params)}`:sU(e)}function sV(e,t){return function(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw sx(e,"Dict");let i=e instanceof Map?e.entries():Object.entries(e),r=null!=t&&t.whitespace?" ":"";return Array.from(i).map(([e,t])=>{t instanceof sO==!1&&(t=new sO(t));let i=sB(e);if(!0===t.value)i+=sG(t.params);else if(i+="=",Array.isArray(t.value)){var r;i+=(r=t,`(${r.value.map(sK).join(" ")})${sG(r.params)}`)}else i+=sK(t);return i}).join(`,${r}`)}(e,t)}let sH=["url"],sY=["version","eventTargets","sid","transmissionMode"],sW=["customData","headers"],sj=e=>e instanceof sO?new sO(Math.round(e.value),e.params):Math.round(e),sq=e=>Array.isArray(e)?e.map(sj):sj(e),sX=(e,t)=>Array.isArray(e)?e.map(e=>sX(e,t)):e instanceof sO&&"string"==typeof e.value?new sO(sX(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){let i;try{i=new URL(e)}catch(t){return e}let r=new URL(t);if(i.origin!==r.origin)return e;let s=i.pathname.split("/").slice(1),a=r.pathname.split("/").slice(1,-1),n=Math.min(s.length,a.length);for(let e=0;e<n&&s[e]===a[e];e++)s.shift(),a.shift();for(;a.length;)a.shift(),s.unshift("..");return s.join("/")+i.search+i.hash}(e,function(e){let t="string"==typeof e?new URL(e):e;return t.origin+t.pathname.substring(0,t.pathname.lastIndexOf("/")+1)}(t.baseUrl))),1===t.version?encodeURIComponent(e):e),sz=e=>e instanceof sO?new sO(100*Math.round(e.value/100),e.params):100*Math.round(e/100),sQ=e=>Array.isArray(e)?e.map(sz):sz(e),sZ={br:sq,d:sq,bl:sQ,dl:sQ,mtp:sQ,nor:(e,t)=>
27{let i=e;return t.version>=2&&(e instanceof sO&&"string"==typeof e.value?i=new sO([e]):"string"==typeof e&&(i=[e])),sX(i,t)},rtp:sQ,tb:sq},sJ={BITRATE_CHANGE:"bc",ERROR:"e",RESPONSE_RECEIVED:"rr",CUSTOM_EVENT:"ce"},s0=new Map([["ps","sta"],["pr","pr"],["c","cid"],["b","bg"],["bc","br"]]),s1="event",s2="request",s4=["cen","e","h","ts"],s3=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],s8=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function s5(e){return s8.test(e)}let s6=new Set(s3);function s9(e){return s6.has(e)||s5(e)}let s7=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],ae=new Set(s7),at=new Set(s4),ai=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),ar=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],as=new Set(ar);function aa(e){return as.has(e)||s5(e)}let an=new Set(["ot","sf","st","e","sta"]),al={[s1]:function(e){return s9(e)||ae.has(e)||at.has(e)},[s2]:s9};function ao(e,t={}){let i={};if(null==e||"object"!=typeof e)return i;let r=t.version||e.v||2,s=t.reportingMode||s2,a=1===r?function(e){let t={};for(let[r,s]of Object.entries(e)){if(null==s){t[r]=s;continue}if("nor"===r){let e=(Array.isArray(s)?s:[s])[0];if(e instanceof sO){var i;t.nor=e.value,null!=(i=e.params)&&i.r&&(t.nrr=e.params.r)}else t.nor=e}else ai.has(r)?t[r]=function e(t,i){if(Array.isArray(t)){let r;return i&&(r=t.find(e=>{var t;return(null==(t=e.params)?void 0:t.ot)===i})),r||(r=t[0]),e(r)}return t instanceof sO?t.value:t}(s,e.ot):t[r]=s}return t}(e):e,n=1===r?aa:al[s],l=Object.keys(a).filter(n);a.e&&"rr"!==a.e&&(l=l.filter(e=>!ae.has(e)));let o=t.filter;"function"==typeof o&&(l=l.filter(o));let h=s===s1;if(h){let e=a.e;l.includes("e")||null==e||l.push("e"),l.includes("ts")||l.push("ts"),l.includes("cen")||null==a.cen||"ce"!==e||l.push("cen");let t=e?s0.get(e):void 0;t&&null!=a[t]&&!l.includes(t)&&l.push(t)}if(0===l.length)return i;r>1&&!l.includes("v")&&l.push("v");let u={version:r,reportingMode:s,baseUrl:t.baseUrl};for(let e of(l.sort(),l)){var f,c,g;let s=a[e],n=null!=(f=null==(c=t.formatters)?void 0:c[e])?f:sZ[e];if("function"==typeof n&&(s=n(s,u)),"v"===e){if(1===r)continue;s=r}if("pr"===e&&1===s&&!(h&&"pr"===a.e))continue;h&&"ts"===e&&!d(s)&&(s=Date.now());let l=h&&!1===s&&"bg"===e&&"b"===a.e;(("number"==typeof(g=s)?d(g):null!=g&&""!==g&&!1!==g)||l)&&(an.has(e)&&"string"==typeof s&&(s=new sF(s)),i[e]=s)}return i}let ah="CMCD-Object",ad="CMCD-Request",au="CMCD-Session",af="CMCD-Status",ac={REQUEST:ad},ag={ab:ah,br:ah,d:ah,lab:ah,lb:ah,ot:ah,tab:ah,tb:ah,tpb:ah,bl:ad,cs:ad,dfa:ad,dl:ad,ltc:ad,mtp:ad,nor:ad,nrr:ad,pb:ad,sn:ad,sta:ad,su:ad,tbl:ad,cid:au,msd:au,sf:au,sid:au,st:au,v:au,bg:af,bs:af,bsa:af,bsd:af,bsda:af,cdn:af,ec:af,nr:af,pr:af,pt:af,rtp:af},am="CMCD";function ap(e){return sV(e,{whitespace:!1})}let aE=[...ar,...s3,...s7,...s4].filter((e,t,i)=>i.indexOf(e)===t),av={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",TIMED_TEXT:"tt"},ay={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},aT="query",aS="headers";function aA(e,t,i){var r;let s=new Set(null!=(r=t.enabledKeys)?r:[]);return{version:t.version||2,reportingMode:e,filter:e=>s.has(e),baseUrl:i}}let aI=Object.is,aL=e=>e,aR=Array.from(s0,([e,t])=>"br"===t?{event:e,field:t,equal:(e,t)=>void 0===e||void 0===t?e===t:function(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++){let r=e[i],s=t[i];if(r===s)continue;if("number"==typeof r||"number"==typeof s||r.value!==s.value)return!1;let a=r.params,n=s.params,l=a&&Object.keys(a)[0],o=n&&Object.keys(n)[0];if(l!==o||void 0!==l&&void 0!==o&&a&&n&&a[l]!==n[o])return!1}return!0}(e,t),snapshot:e=>e.slice()}:{event:e,field:t,equal:aI,snapshot:aL}),ab=new Map(aR.map(e=>[e.event,e]));function aD(e){let{url:t}=e;return fetch(t,Y(e,sH))}var ak=class{constructor(e,t=aD){var i;for(let r of(this.timeOrigin=performance.timeOrigin||(null==(i=performance.timing)?void 0:i.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=function(e){let{version:t=2,eventTargets:i=[],sid:r=em(),transmissionMode:s=aT}=e;return H(H({},Y(e,sY)),{},{version:t,transmissionMode:s,sid:r,eventTargets:i.reduce((e,t)=>
27{var i,r,s;return null!=t&&t.url&&null!=(i=t.events)&&i.length&&e.push({version:t.version||2,enabledKeys:(null==(r=t.enabledKeys)?void 0:r.slice())||[],url:t.url,events:t.events.slice(),interval:null!=(s=t.interval)?s:30,batchSize:t.batchSize||1}),e},[])})}(e),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=t,this.config.eventTargets))this.eventTargets.set(r,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((e,t)=>{if(this.disarmInterval(e),0===t.interval||!t.events.includes("t"))return;let i=()=>{this.recordTargetEvent(e,t,"t"),this.processEventTargets()};e.intervalId=setInterval(i,1e3*t.interval),i()})}stop(e=!1){e&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(e){for(let t of(e.sid&&e.sid!==this.data.sid&&this.resetSession(),e.msd&&!isNaN(e.msd)&&(this.msd=e.msd),this.data=H(H(H({},this.data),e),{},{msd:void 0}),aR))t.field in e&&!t.equal(this.data[t.field],this.lastEmitted[t.field])&&this.recordEvent(t.event)}recordEvent(e,t={}){let i=ab.get(e);if(i){let e=i.field,r=t[e];void 0!==r&&K(this.data,{[e]:r});let s=this.data[e];if(void 0===s||i.equal(s,this.lastEmitted[e]))return;K(this.lastEmitted,{[e]:i.snapshot(s)})}this.eventTargets.forEach((i,r)=>{this.recordTargetEvent(i,r,e,t)}),this.processEventTargets()}recordTargetEvent(e,t,i,r={}){var s;if(!t.events.includes(i))return;let a=H(H(H({},this.data),r),{},{e:i,ts:null!=(s=r.ts)?s:Date.now(),sn:e.sn++});isNaN(this.msd)||e.msdSent||(a.msd=this.msd,e.msdSent=!0),e.queue.push(a)}recordResponseReceived(e,t={}){var i,r,s;let{request:a}=e,n=null!=(i=t.url)?i:null==a?void 0:a.url;if(!n)return;let l=new URL(n);l.searchParams.delete(am);let o={url:l.toString(),rc:e.status},h=e.resourceTiming;h&&(null!=h.startTime&&(o.ts=Math.round(this.timeOrigin+h.startTime),null!=h.responseStart&&(o.ttfb=Math.round(h.responseStart-h.startTime))),null!=h.duration&&(o.ttlb=Math.round(h.duration)));let d=null!=(r=null==(s=a.customData)?void 0:s.cmcd)?r:{};this.recordEvent("rr",H(H(H({},d),o),t))}applyRequestReport(e){var t;return null!=(t=this.createRequestReport(e))?t:e}isRequestReportingEnabled(){var e;return!!(null!=(e=this.config.enabledKeys)&&e.length)}createRequestReport(e,t){var i;let{customData:r={},headers:s={}}=e,a=H(H({},Y(e,sW)),{},{headers:H({},s),customData:H(H({},r),{},{cmcd:{}})});if(!(null!=(i=this.config.enabledKeys)&&i.length)||!a.url)return a;let n=new URL(a.url),l=H(H(H({},this.data),t),{},{sn:this.requestTarget.sn++}),o=aA(s2,this.config,a.url);isNaN(this.msd)||this.requestTarget.msdSent||(l.msd=this.msd,this.requestTarget.msdSent=!0);let h=a.customData.cmcd=ao(l,o);switch(this.config.transmissionMode){case aT:let d=ap(h);d&&(n.searchParams.set(am,d),a.url=n.toString());break;case aS:K(a.headers,function(e,t){let i={};for(let[r,s]of Object.entries(function(e,t){var i;let r={};if(!e)return r;let s=Object.keys(e),a=t?Object.keys(t).reduce((e,i)=>{var r;return null==(r=t[i])||r.forEach(t=>e[t]=i),e},{}):{};for(let t of s){let s=ag[t]||a[t]||ac.REQUEST;(null!=(i=r[s])?i:r[s]={})[t]=e[t]}return r}(e,t))){let e=sV(s,{whitespace:!1});e&&(i[r]=e)}return i}(h,o.customHeaderMap))}return a}processEventTargets(e=!1){let t=!1;this.eventTargets.forEach((i,r)=>{let{queue:s}=i;if(!s.length||s.length<r.batchSize&&!e)return;let a=e?s.length:r.batchSize,n=s.splice(0,a);this.sendEventReport(r,n).catch(()=>{i.queue.unshift(...n)}),t||(t=s.length>0)}),t&&this.processEventTargets()}async sendEventReport(e,t){let i=aA(s1,e),{status:r}=await this.requester({url:e.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:t.map(e=>(function(e,t={}){return e?ap(ao(e,t)):""})(e,i)).join("\n")+"\n"});if(410===r)this.disposeEventTarget(e);else if(429===r||r>499&&r<600)throw Error(`Event report failed with status ${r}`)}disarmInterval(e){clearInterval(e.intervalId),e.intervalId=void 0}disposeEventTarget(e){let t=this.eventTargets.get(e);t&&(this.disarmInterval(t),this.eventTargets.delete(e))}resetSession(){this.eventTargets.forEach(e=>e.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};let aP={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"},a_=["includeKeys"];function aC(e){return Object.keys(e).every(s5)}class aO{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(ay.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(ay.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(ay.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(ay.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(ay.SEEKING)},this.onSeeked=()=>{var e;this.initialized&&null!=(e=this.media)&&e.paused&&this.setPlayerState(ay.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=e=>{try{this.apply(e,{ot:av.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{var t,i,r,s;let{frag:a,part:n}=e,l=this.hls.levels[a.level],o=this.getObjectType(a,l),h={d:1e3*(n||a).duration,ot:o};if(o===av.VIDEO||o===av.AUDIO||o===av.MUXED||null==o&&("main"===a.type||"audio"===a.type)){let e=l.bitrate/1e3;h.br=[e];let{cmcd:r}=this.config,s=null!=(t=null==r?void 0:r.rtpSafetyFactor)?t:5;if(h.rtp=100*Math.round(e*s/100),o===av.MUXED||null==o&&"main"===a.type){let e=this.getTopBandwidth()/1e3;d(e)&&(h.tb=[e]);let t=this.getLowestBandwidth()/1e3;d(t)&&(h.lb=[t])}let n=this.getBufferLength(a);if(d(n)){h.bl=[n];let e=(null==(i=this.media)?void 0:i.playbackRate)||1;h.dl=100*Math.round(n/e/100)}this.playheadLevel&&(h.pb=[this.playheadLevel.bitrate/1e3]);let u=this.hls.maxAutoLevel;if(u>=0){let e=this.hls.levels[u];e&&(h.tpb=[e.bitrate/1e3])}}let u=n?this.getNextPart(n):this.getNextFrag(a);null!=u&&u.url&&u.url!==a.url&&(u.byteRange.length>0?h.nor=[(r=u.url,s={r:`${u.byteRange[0]}-${u.byteRange[1]}`},new sO(r,s))]:h.nor=[u.url]),this.apply(e,h)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.recordFragmentResponse=(e,t,i)=>{var r;let{cmcd:s}=this.config,a=null==s||null==(r=s.eventTargets)?void 0:r.some(e=>{var t;return null==(t=e.events)?void 0:t.includes(sJ.RESPONSE_RECEIVED)});if(this.reporter&&i.loading.first>0&&a)try{this.reporter.recordResponseReceived({request:{url:e},status:t.code,resourceTiming:{startTime:i.loading.start,responseStart:i.loading.first,duration:i.loading.end-i.loading.start,encodedBodySize:i.total}})}catch(e){this.hls.logger.warn("Could not record fragment response CMCD data.",e)}},this.hls=e;let t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;let{cmcd:i}=this.config;if(null==i)return;
27let r=i.version||1;if(this.reporter=new ak({sid:i.sessionId||this.hls.sessionId,cid:i.contentId,version:r,transmissionMode:!0===i.useHeaders?aS:aT,enabledKeys:null!=(e=i.includeKeys)?e:[...r>=2?aE:ar],eventTargets:(null!=(t=i.eventTargets)?t:[]).map(e=>{let{includeKeys:t}=e;return H(H({},Y(e,a_)),{},{enabledKeys:null!=t?t:aE})})},i.loader),this.reporter.update({sf:"h",sta:this.playerState}),i.reporterCallback){let e=this.reporter;i.reporterCallback({updateCustomData:t=>{aC(t)&&e.update(t)},recordCustomEvent:(t,i={})=>{aC(i)&&e.recordEvent(sJ.CUSTOM_EVENT,H({cen:t},i))}})}this.reporter.start()}registerListeners(){let e=this.hls;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHED,this.onMediaDetached,this),e.on(m.MEDIA_ENDED,this.onMediaEnded,this),e.on(m.ERROR,this.onError,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(m.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(m.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){let e=this.hls;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MEDIA_ATTA
27CHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHED,this.onMediaDetached,this),e.off(m.MEDIA_ENDED,this.onMediaEnded,this),e.off(m.ERROR,this.onError,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(m.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(m.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(e,t){let i=this.media=t.media;this.setPlayerState(this.media.autoplay?ay.STARTING:ay.PRELOADING),i7(i,"waiting",this.onWaiting),i7(i,"play",this.onPlay),i7(i,"playing",this.onPlaying),i7(i,"pause",this.onPause),i7(i,"seeking",this.onSeeking),i7(i,"seeked",this.onSeeked),i7(i,"ratechange",this.onRateChange)}onMediaDetached(){let e=this.media;e&&(re(e,"waiting",this.onWaiting),re(e,"play",this.onPlay),re(e,"playing",this.onPlaying),re(e,"pause",this.onPause),re(e,"seeking",this.onSeeking),re(e,"seeked",this.onSeeked),re(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(ay.ENDED)}onManifestLoading(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(ay.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(ay.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(sJ.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var i;if(!this.reporter)return;let r={br:[t.bitrate/1e3]},s=null==(i=t.details)?void 0:i.fragments[0];s&&(r.ot=this.getObjectType(s,t)),this.reporter.recordEvent(sJ.BITRATE_CHANGE,r)}onLevelSwitched(e,t){let i=this.hls.levels[t.level];i&&(this.playheadLevel=i)}setPlayerState(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}getStreamType(){let e=this.hls.latestLevelDetails;return e?e.live?e.partList&&e.canBlockReload?aP.LOW_LATENCY:aP.LIVE:aP.VOD:void 0}apply(e,t={}){var i;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(i=this.media)?void 0:i.playbackRate,st:this.getStreamType()});let r=t.ot===av.INIT||t.ot===av.VIDEO||t.ot===av.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);let s=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=s.url,e.headers=s.headers}getNextFrag(e){var t;let i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){let t=e.sn-i.startSN;return i.fragments[t+1]}}getNextPart(e){var t;let{index:i,fragment:r}=e,s=null==(t=this.hls.levels[r.level])||null==(t=t.details)?void 0:t.partList;if(s){let{sn:e}=r;for(let t=s.length-1;t>=0;t--){let r=s[t];if(r.index===i&&r.fragment.sn===e)return s[t+1]}}}getObjectType(e,t){let{type:i}=e;if("subtitle"===i)return av.TIMED_TEXT;if("initSegment"===e.sn)return av.INIT;if("audio"===i)return av.AUDIO;if("main"===i){if(e.hasStreams){let t=e.elementaryStreams;if(t.audiovideo)return av.MUXED;if(t.video)return av.VIDEO;if(t.audio)return av.AUDIO}if(t){let{audioCodec:e,videoCodec:i}=t;if(!this.hls.audioTracks.length){if(e&&i)return av.MUXED;if(e)return av.AUDIO}if(i)return av.VIDEO}}}getTopBandwidth(){let e=0,t=this.hls,i=t.maxAutoLevel,r=i>-1?i+1:t.levels.length;return t.levels.slice(0,r).forEach(t=>{t.bitrate>e&&(e=t.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0,t=this.hls,i=t.maxAutoLevel,r=i>-1?i+1:t.levels.length;return t.levels.slice(0,r).forEach(t=>{t.bitrate<e&&(e=t.bitrate)}),d(e)?e:NaN}getBufferLength(e){if(!this.media)return NaN;let t="audio"===e.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?1e3*t.len:NaN}getEventBufferLength(){if(!this.media)return NaN;let e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return 1e3*Math.min(e.len,t.len);let i=e||t;return i?1e3*i.len:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;let i=this.getEventBufferLength();d(i)&&this.reporter.update({bl:[i]})}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=this.recordFragmentResponse,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,s){t(e);let{onSuccess:a}=s;this.loader.load(e,r,H(H({},s),{},{onSuccess:(t,r,s,n)=>{a(t,r,s,n),i(e.url,t,r)}}))}}}}class aM extends er{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>
27(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:i}=t;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if((null==i?void 0:i.action)===tK.SendAlternateToPenaltyBox&&i.flags&tV.MoveAllAlternatesMatchingHost){let e=this.levels,r=this._pathwayPriority,s=this.pathwayId;if(t.context){let{groupId:i,pathwayId:r,type:a}=t.context;i&&e?s=this.getPathwayForGroupId(i,a,s):r&&(s=r)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!r&&e&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s,!i.resolved&&(t.details!==g.BUFFER_APPEND_ERROR||t.fatal)&&this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${s} levels: ${e?e.length:e} priorities: ${tR(r)} penalized: ${tR(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;let i=this.penalizedPathways,r=performance.now();
27Object.keys(i).forEach(e=>{r-i[e]>3e5&&delete i[e]});for(let r=0;r<e.length;r++){let s=e[r];if(s in i)continue;if(s===this.pathwayId)return;let a=this.hls.nextLoadLevel,n=this.hls.levels[a];if((t=this.getLevelsForPathway(s)).length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,i4(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});let e=this.hls.levels[a];n&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==n.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==n.bitrate&&this.log(`Unstable Pathways change from bitrate ${n.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<r.length;i++)if(t===M.AUDIO_TRACK&&r[i].hasAudioGroup(e)||t===M.SUBTITLE_TRACK&&r[i].hasSubtitleGroup(e))return r[i].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach(e=>{let{ID:s,"BASE-ID":a,"URI-REPLACEMENT":n}=e;if(t.some(e=>e.pathwayId===s))return;let l=this.getLevelsForPathway(a).map(e=>{let t=new id(e.attrs);t["PATHWAY-ID"]=s;let a=t.AUDIO&&`${t.AUDIO}_clone_${s}`,l=t.SUBTITLES&&`${t.SUBTITLES}_clone_${s}`;a&&(i[t.AUDIO]=a,t.AUDIO=a),l&&(r[t.SUBTITLES]=l,t.SUBTITLES=l);let o=aF(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",n),h=new tA({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:o,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)h.addGroupId("audio",`${e.audioGroups[t]}_clone_${s}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)h.addGroupId("text",`${e.subtitleGroups[t]}_clone_${s}`);return h});t.push(...l),aw(this.audioTracks,i,n,s),aw(this.subtitleTracks,r,n,s)})}loadSteeringManifest(e){let t;let i=this.hls.config,r=i.loader;this.loader&&this.loader.destroy(),this.loader=new r(i);try{t=new self.URL(e)}catch(t){this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if("data:"!==t.protocol){let e=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);tp(t,"_HLS_pathway",this.pathwayId),tp(t,"_HLS_throughput",""+e)}let s={type:M.STEERING_MANIFEST,responseType:"json",url:t.href},a=i.steeringManifestLoadPolicy.default,n=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0};this.log(`Requesting steering manifest: ${t}`),this.loader.load(s,l,{onSuccess:(e,i,r,s)=>{this.log(`Loaded steering manifest: "${t}"`);let a=e.data;if((null==a?void 0:a.VERSION)!==1){this.log(`Steering VERSION ${a.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=a.TTL;let{"RELOAD-URI":n,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":o}=a;if(n)try{this.uri=new self.URL(n,t).href}catch(e){this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${n}`);return}this.scheduleRefresh(this.uri||r.url),l&&this.clonePathways(l);let h={steeringManifest:a,url:t.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,h),o&&this.updatePathwayPriority(o)},onError:(e,t,i,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code){this.enabled=!1,this.log(`Steering manifest ${t.url} no longer available`);return}let s=1e3*this.timeToLoad;if(429===e.code){let e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){let t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`);return}this.scheduleRefresh(this.uri||t.url,s)},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}})}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;let i=null==(t=this.hls)?void 0:t.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,1e3*this.timeToLoad)},t)}}function aw(e,t,i,r){e&&Object.keys(t).forEach(s=>{let a=e.filter(e=>e.groupId===s).map(e=>{let a=K({},e);return a.details=void 0,a.attrs=new id(a.attrs),a.url=a.attrs.URI=aF(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),a.groupId=a.attrs["GROUP-ID"]=t[s],a.attrs["PATHWAY-ID"]=r,a});e.push(...a)})}function aF(e,t,i,r){if(t){let{[i]:e}=r;if(e){let i=e[t];if(i)return i}}let{HOST:s,PARAMS:a}=r,n=new self.URL(e);
27return s&&(n.hostname=s),a&&Object.keys(a).sort().forEach(e=>{e&&tp(n,e,a[e])}),n.href}class ax extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=Error(t)),this.data=e,e.err=e.error}}class aN extends er{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=aN.CDMCleanupPromise?[aN.CDMCleanupPromise]:[],this.onMediaEncrypted=e=>{let{initDataType:t,initData:i}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.log(r),null!==i){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=iD(this.config));let t=e.map(ib).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(s=>{var a,n,l;let o,h;let d=iL(s),u=this.activeLevelKeys();if(d===iA.FAIRPLAY&&"sinf"===t)try{let e=ek(new Uint8Array(i)),t=eD(JSON.parse(e).sinf),r=ej(t);if(!r)throw Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(r.subarray(8,24))}catch(e){this.warn(`${r} Failed to parse sinf: ${e}`);return}else if(d===iA.PLAYREADY)o=iP(new Uint8Array(i));else if(d===iA.WIDEVINE){let e=e0(i).filter(e=>e.systemId===iR.WIDEVINE);if(e.length){let t=e[0];o=null!=(a=t.kids)&&a.length?t.kids[0]:null}}if(o){let e=eR(o);for(let r=0;r<u.length;r++){let s=u[r];if(s.keyId&&(ig(o,s.keyId)||-1!==s.uri.replace(/-/g,"").indexOf(e))){s.pssh||(s.scheme=t,s.pssh=new Uint8Array(i),s.keyId=o,iC.setKeyIdForUri(s.uri,o)),h=this.getSessionForKey(s,"encrypted-event-key-match");break}}}if(!h){if(u.length)return(n=u[0]).scheme||(n.scheme=t),(l=u[0]).pssh||(l.pssh=new Uint8Array(i)),this.getSessionForKey(u[0],"encrypted-event-no-match");if(o)throw Error(`Key ID ${eR(o)} not encountered in playlist`);this.log(`Ignoring "${e.type}" event - could not determine keyId`)}return h}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){let{hls:e}=this;
27e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHED,this.onMediaDetached,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHED,this.onMediaDetached,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(Error("destroyed"));let t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,r=t.map(e=>e.audioCodec).filter(i),s=t.map(e=>e.videoCodec).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise((t,i)=>{let a=e=>{let n=e.shift();this.getMediaKeysPromise(n,r,s).then(e=>t({keySystem:n,mediaKeys:e})).catch(t=>{e.length?a(e):t instanceof ax?i(t):i(new ax({type:c.KEY_SYSTEM_ERROR,details:g.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};a(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===ik&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){var r;let s=function(e,t,i,r){let s;switch(e){case iA.FAIRPLAY:s=["cenc","sinf"];break;case iA.WIDEVINE:case iA.PLAYREADY:s=["cenc"];break;case iA.CLEARKEY:s=["cenc","keyids"];break;default:throw Error(`Unknown key-system: ${e}`)}return[{initDataTypes:s,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:i.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],n=null==(r=a)?void 0:r.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${tR(s)}`),n=this.requestMediaKeySystemAccess(e,s);let t=a=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),n.then(i=>{this.throwIfDestroyed(),this.log(`Access for key-system "${i.keySystem}" obtained`);let r=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let s=t.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,r.then(t=>t?this.setMediaKeysServerCertificate(i,e,t):i)));return s.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),s})}return n.then(()=>a.mediaKeys)}getMediaKeySessionContext(e,t,i,r){let{mediaKeySessions:s}=this,a=` key-session "${e}" keyId: ${eR(i.keyId||[])} keyUri: ${i.uri} for "${r}"`;for(let e=0;e<s.length;e++){let t=s[e];if(!t.initialized&&t.createdFor.levelKey.uri===i.uri)return this.log(`Reusing${a}`),t}this.log(`Creating${a}`);let n=t.createSession(),l={keySystem:e,mediaKeys:t,mediaKeysSession:n,keyRequests:{},keyStatuses:{},createdFor:{levelKey:i,reason:r},initialized:!1};return s.push(l),l}resetMediaKeys(){var e;let t=null==(e=this.mediaKeySessions[0])?void 0:e.keySystem,i=this.keySystemAccessPromises[t];i&&(this.log("reset mediaKeys"),this.mediaKeys=null,i.hasMediaKeys=!1,delete i.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,i){let r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${eR(t.keyId||[])} 28 } (data length: ${i.byteLength})`),r.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>ib(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{let t=ib(e);if(!t)throw Error(`Unable to find format for key-system "${e}"`);return t})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=iD(this.config),i=e.map(iL).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(i)}loadClear(e,t,i){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,s=t.length;r<s;r++){let a=t[r];if(e.cc<=a.cc&&(!N(e)||!N(a)||e.sn<a.sn)||!i&&r==s-1)return this.selectKeySystemFormat(a).then(e=>{if(!this.hls)return;a.setKeyFormat(e);let t=iL(e);if(t)return this.getKeySystemAccess([t])})}if(this.config.requireKeySystemAccessOnStart){let e=iD(this.config);if(e.length)return this.getKeySystemAccess(e)}}return null}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let i=0;i<t.length;i++){let r=a$(e,t[i]);if(r)return r}}loadKey(e){let t=e.decryptdata,i=this.getKeyStatus(t);if("internal-error"===i){let r=aU(i,t);return r.data.frag=e,this.error(`${r.message} (${eR(t.keyId||[])})`),Promise.reject(r)}let r=e.type,s=this.activeKeys,a=s[r];a&&!t.matches(a.decryptdata)&&(s.previous||(s.previous=[]),s.previous.push(a),delete s[r]),s[r]||(s[r]=e);for(let e=this.mediaKeySessions.length;e--;){let i=this.mediaKeySessions[e];if(t.keyId&&"expired"===i.keyStatuses[eR(t.keyId)])return this.renewKeySession(t,i)}return this.updateUsablePromise(t,"playlist-key",e)}renewKeySession(e,t){return this.resetMediaKeys(),this.removeSession(t).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,t,i){let r=this.getSessionForKey(e,t);return r.catch(e=>this.handleError(e,i)),r.then(t=>e)}getSessionForKey(e,t){let i;let r=this.findContextForKey(e);if(void 0!==r)return Promise.resolve(r);let s=e.uri,a=this.sessionSetupByUri[s];i=void 0===a?this.resolveSessionForKey(e,t):a.catch(()=>void 0).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[s]=i;let n=()=>{this.sessionSetupByUri[s]===i&&delete this.sessionSetupByUri[s]};return i.then(n,n),i}findContextForKey(e){let{mediaKeySessions:t}=this;for(let i=t.length;i--;){let r=t[i];if(a$(e,r))return r}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:i,mediaKeys:r})=>{this.throwIfDestroyed();for(let i=this.mediaKeySessions.length;i--;){let r=this.mediaKeySessions[i];if(a$(e,r))return r;let s=this.getUsableKeyPromise(r,e,t);if(s)return s}return this.attemptSetMediaKeys(i,r).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(i,r,e,t))).then(i=>{this.throwIfDestroyed();let r=e.scheme||"cenc",s=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(i,e,r,s,t)})})}getUsableKeyPromise(e,t,i){let r=e.keyRequests[t.uri];if(r)return this.log(`Waiting for usable key (${i} keyId: ${function(e){if(e.keyFormat===iI.FAIRPLAY)return e.uri;if(null===e.keyId)throw Error("keyId is null");return eR(e.keyId)}(t)} format: "${t.keyFormat}" URI: ${t.uri})`),aB(r).then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw Error("invalid state")}handleError(e,t){if(this.hls){if(e instanceof ax){t&&(e.data.frag=t);let i=e.data.decryptdata;this.error(`${e.message}${i?` (${eR(i.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:c.KEY_SYSTEM_ERROR,details:g.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}}getKeySystemForKeyPromise(e){let t=iL(e.keyFormat),i=t?[t]:iD(this.config);return this.attemptKeySystemAccess(i)}getKeySystemSelectionPromise(e){if(e.length||(e=iD(this.config)),0===e.length)throw new ax({type:c.KEY_SYSTEM_ERROR,details:g.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${tR({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){let e=this.activeKeys,t=(e.previous||[]).map(e=>e.decryptdata);return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,i)=>{this.mediaResolved=()=>
28{if(this.mediaResolved=void 0,!this.media)return i(Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(i)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>-1===i.indexOf(e))})}filterInitData(e,t,i,r,s){var a,n;let l=null==(a=this.config.drmSystems)||null==(a=a[e.keySystem])?void 0:a.generateRequest;if(l)try{let a=l.call(this.hls,i,r,K({},e,{decryptdata:t,reason:s}),s);if(!a)throw Error("Invalid response from configured generateRequest filter");t.scheme=a.initDataType?a.initDataType:"cenc";let n=a.initData?a.initData:null;return t.pssh=n?new Uint8Array(n):null,a}catch(e){if(this.warn(e.message),null!=(n=this.hls)&&n.config.debug)throw e}return{initDataType:i,initData:r}}generateRequestWithPreferredKeySession(e,t,i,r,s){let a=this.getUsableKeyPromise(e,t,s);if(a)return a;let n=this.filterInitData(e,t,i,r,s);if(n&&(r=n.initData?n.initData:null,i=n.initDataType),null===r)return s.startsWith("encrypted-event")?Promise.reject(Error(`missing initialization data for "${s}"`)):(this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(e));let l=t.uri,o=new ro;o.status="initialized",o.requestErrors=[],e.keyRequests[l]=o;let h=i=>{let r=e.mediaKeysSession;if(!r){let e=Error("invalid state");o.errored=e,o.emit("error",e);return}let{messageType:s,message:a}=i;o.status=s,this.log(`"${s}" message event for session "${r.sessionId}" message size: ${a.byteLength}`),"license-request"===s||"license-renewal"===s?this.renewLicense(e,t,a).catch(t=>
28{o.errored=t,o.eventNames().length?o.emit("error",t):this.handleError(t),this.removeSession(e)}):"license-release"===s?e.keySystem===iA.FAIRPLAY&&this.updateKeySession(e,t,iv("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${s}"`)};return o.onmessage=h,i7(e.mediaKeysSession,"message",h),this.generateRequest(e,t,i,r,s,!1)}generateRequest(e,t,i,r,s,a){if(a){let a=this.filterInitData(e,t,i,r,s);a&&(r=a.initData?a.initData:r,i=a.initDataType)}let n=t.uri,l=e.keyRequests[n],o=eR(t.keyId||[]),h=e=>{let i;e.startsWith("usable")?(l.resolved=!0,l.emit("resolved")):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?i=aU(e,t):"expired"===e?i=Error(`key expired (keyId: ${o})`):"released"===e?i=Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${o})`),i&&(l.errored=i,l.eventNames().length?l.emit("error",i):this.handleError(i))},d=i=>{var r,s;if(!e.mediaKeysSession){let e=Error("invalid state");l.errored=e,l.emit("error",e);return}let a=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(a).some(e=>"status-pending"!==a[e]))return;let n=this.activeLevelKeys();for(let i=0;i<n.length;i++)if("expired"===a[eR(n[i].keyId||[])]){this.log(`Expired key ${tR(a)} in key-session "${null==(r=e.mediaKeysSession)?void 0:r.sessionId}"`),this.renewKeySession(t,e).catch(e=>this.handleError(e));break}let d=a[o];d?h(d):(e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(s=e.keyStatusTimeouts)[o]||(s[o]=self.setTimeout(()=>{var i,r;if(!e.mediaKeysSession)return;let s=this.getKeyStatus(t);if(s&&"status-pending"!==s)return this.log(`No status for keyId ${o} in key-session "${null==(r=e.mediaKeysSession)?void 0:r.sessionId}". Using session key-status ${s} from other session.`),h(s);this.log(`key status for ${o} in key-session "${null==(i=e.mediaKeysSession)?void 0:i.sessionId}" timed out after 1000ms`),h(d="internal-error")},1e3)),this.log(`No status for keyId ${o} (${tR(a)}).`))};l.onkeystatuseschange=d,i7(e.mediaKeysSession,"keystatuseschange",d);let u=aB(l);return this.log(`Generating key-session request for "${s}" keyId: ${o} URI: ${n} (init data type: ${i} length: ${r.byteLength})`),l.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(i,r).then(()=>{var t;l.status="generated",this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${o} URI: ${n}`)}).catch(e=>{throw this.log(`mediaKeysSession.generateRequest failed: ${e}`),new ax({type:c.KEY_SYSTEM_ERROR,details:g.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>u).catch(t=>{var i;this.log(`mediaKeysSession.generateRequest failed: ${t}`);let r=null==(i=t.data)?void 0:i.details;return(r===g.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||r===g.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(t=>"usable"===e.keyStatuses[t])?(this.handleError(t),e):(l.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))}).then(()=>e)}getKeyStatuses(e){let t={},i=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((r,s)=>{if("string"==typeof s&&"object"==typeof r){let e=s;s=r,r=e}let a="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);e.keySystem===iA.PLAYREADY&&16===a.length&&(t[eR(a)]=r,iy(a));let n=eR(a);this.log(`key status change "${r}" for keyStatuses keyId: ${n} key-session "${i}"`),t[n]=r}),t}fetchServerCertificate(e){let t=this.config,i=new t.loader(t),r=function(e,t){let{drmSystems:i}=t,r=null==i?void 0:i[e];if(r)return r.serverCertificateUrl}(e,t);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((s,a)=>{let n={type:M.SERVER_CERTIFICATE,responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,o={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};i.load(n,o,{onSuccess:(e,t,i,r)=>{s(e.data)},onError:(t,i,s,l)=>{a(new ax({type:c.KEY_SYSTEM_ERROR,details:g.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:H({url:n.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,s)=>{a(new ax({type:c.KEY_SYSTEM_ERROR,details:g.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:n.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,i)=>{a(Error("aborted"))}})})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,i){return new Promise((r,s)=>{e.setServerCertificate(i).then(s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),r(e)}).catch(e=>{s(new ax({type:c.KEY_SYSTEM_ERROR,details:g.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t,i){return this.requestLicense(e,t,new Uint8Array(i)).then(i=>this.updateKeySession(e,t,new Uint8Array(i)).catch(e=>{throw new ax({type:c.KEY_SYSTEM_ERROR,details:g.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:e,fatal:!1},e.message)}))}unpackPlayReadyKeyMessage(e,t){let i=ek(new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let t;for(let i=0,r=s.length;i<r;i++){var a,n;let r=null==(a=(t=s[i]).querySelector("name"))?void 0:a.textContent,l=null==(n=t.querySelector("value"))?void 0:n.textContent;r&&l&&e.setRequestHeader(r,l)}}let l=r.querySelector("Challenge"),o=null==l?void 0:l.textContent;
28if(!o)throw Error("Cannot find <Challenge> in key message");return iv(atob(o))}setupLicenseXHR(e,t,i,r,s){let a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,H(H({},i),{},{decryptdata:r}),s))).catch(n=>{if(!i.mediaKeysSession)throw n;return e.open("POST",t,!0),a.call(this.hls,e,t,H(H({},i),{},{decryptdata:r}),s)}).then(i=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||s})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:s}))}requestLicense(e,t,i){return new Promise((r,s)=>{let a=function(e,t){let{drmSystems:i,widevineLicenseUrl:r}=t,s=null==i?void 0:i[e];return s?s.licenseUrl:e===iA.WIDEVINE&&r?r:void 0}(e.keySystem,this.config);if(!a)return s(Error(`no license server URL configured for key-system "${e.keySystem}"`));let n=e.keyRequests[t.uri];if(!n)return s(Error("License emitter removed"));this.log(`Sending license request to URL: ${a}`);let l=this.config.keyLoadPolicy.default,o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(Error("invalid state"));if(4===o.readyState){if(200===o.status){n.requestErrors=[];let i=o.response;this.log(`License received ${i instanceof ArrayBuffer?i.byteLength:i}`);let s=this.config.licenseResponseCallback;if(s)try{i=s.call(this.hls,o,a,H(H({},e),{},{decryptdata:t}))}catch(e){this.error(e)}r(i)}else{let h=l.errorRetry,d=h?h.maxNumRetry:0;if(n.requestErrors.push({status:o.status,message:o.statusText}),n.requestErrors.length>d||o.status>=400&&o.status<500)s(new ax({type:c.KEY_SYSTEM_ERROR,details:g.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{let a=d-n.requestErrors.length;this.warn(`Retrying license request, ${a} attempts left`),this.requestLicense(e,t,i).then(r,s)}}}},n.licenseXhr&&n.licenseXhr.readyState!==XMLHttpRequest.DONE&&n.licenseXhr.abort(),n.licenseXhr=o,this.setupLicenseXHR(o,a,e,t,i).then(({xhr:t,licenseChallenge:i})=>{e.keySystem==iA.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}).catch(s)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,i7(i,"encrypted",this.onMediaEncrypted),i7(i,"waitingforkey",this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=i.mediaKeys}onMediaDetached(){let e=this.media;e&&(re(e,"encrypted",this.onMediaEncrypted),re(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let i=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,iC.clearKeyUriToKeyIdMap();let s=r.length;aN.CDMCleanupPromise=Promise.all(r.map(e=>this.removeSession(e)).concat((null==i||null==(e=i.setMediaKeys(null))?void 0:e.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(m.ERROR,{type:c.OTHER_ERROR,details:g.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(m.ERROR,{type:c.OTHER_ERROR,details:g.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{s&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){let e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e),this.keyFormatPromise.catch(()=>{})}}removeSession(e){let{mediaKeysSession:t}=e;if(t){var i;
28this.log(`Remove licenses and keys and close session "${t.sessionId}"`),Object.keys(e.keyRequests).forEach(i=>{let r=e.keyRequests[i];r.onmessage&&(t.removeEventListener("message",r.onmessage),r.onmessage=void 0),r.onkeystatuseschange&&(t.removeEventListener("keystatuseschange",r.onkeystatuseschange),r.onkeystatuseschange=void 0);let s=r.licenseXhr;s&&(s.readyState!==XMLHttpRequest.DONE&&s.abort(),r.licenseXhr=void 0),e.keyRequests[i]=void 0}),e.mediaKeysSession=void 0;let r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);let{keyStatusTimeouts:s}=e;s&&Object.keys(s).forEach(e=>self.clearTimeout(s[e]));let{drmSystemOptions:a}=this.config;return(a&&("persistent-license"===a.sessionType||null!=(i=a.sessionTypes)&&i.some(e=>"persistent-license"===e))?new Promise((e,i)=>{self.setTimeout(()=>i(Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(i)}):Promise.resolve()).catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(m.ERROR,{type:c.OTHER_ERROR,details:g.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).then(()=>t.closed).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(m.ERROR,{type:c.OTHER_ERROR,details:g.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close session: ${e}`)})})}return Promise.resolve()}}function a$(e,t){let i=e.keyId,r=t.mediaKeysSession;if(i&&r){let e=t.mediaKeysSession.keyStatuses;if(e.size)return e.has(i)?e.get(i):t.keyStatuses[eR(i)]}}function aU(e,t){let i="output-restricted"===e,r=i?g.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:g.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ax({type:c.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},i?"HDCP level output restricted":`key status changed to "${e}"`)}function aB(e){return new Promise((t,i)=>e.resolved?t():e.errored?i(e.errored):void(e.on("error",i),e.on("resolved",t)))}aN.CDMCleanupPromise=void 0;class aG{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}
28registerListeners(){this.hls.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let e=r-this.lastTime,s=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,n=1e3*s/e,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:s,currentDecoded:a,totalDroppedFrames:i}),n>0&&s>l.config.fpsDroppedMonitoringThreshold*a){let e=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=e)&&(e-=1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:l.currentLevel}),l.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e){if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}}var aK=function(){if(null!=iS&&iS.VTTCue)return self.VTTCue;let e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t||!Array.isArray(e))return!1;let i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e,...t){let i=1;for(;i<arguments.length;i++){let t=arguments[i];for(let i in t)e[i]=t[i]}return e}function s(s,a,n){let l={enumerable:!0};this.hasBeenReset=!1;let o="",h=!1,d=s,u=a,f=n,c=null,g="",m=!0,p="auto",E="start",v=50,y="middle",T=50,S="middle";Object.defineProperty(this,"id",r({},l,{get:function(){return o},set:function(e){o=""+e}})),Object.defineProperty(this,"pauseOnExit",r({},l,{get:function(){return h},set:function(e){h=!!e}})),Object.defineProperty(this,"startTime",r({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"endTime",r({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"text",r({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(this,"region",r({},l,{get:function(){return c},set:function(e){c=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"vertical",r({},l,{get:function(){return g},set:function(t){let r=i(e,t);if(!1===r)throw SyntaxError("An invalid or illegal string was specified.");g=r,this.hasBeenReset=!0}})),Object.defineProperty(this,"snapToLines",r({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(this,"line",r({},l,{get:function(){return p},set:function(e){if("number"!=typeof e&&"auto"!==e)throw SyntaxError("An invalid number or illegal string was specified.");p=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"lineAlign",r({},l,{get:function(){return E},set:function(e){let r=i(t,e);if(!r)throw SyntaxError("An invalid or illegal string was specified.");E=r,this.hasBeenReset=!0}})),Object.defineProperty(this,"position",r({},l,{get:function(){return v},set:function(e){if(e<0||e>100)throw Error("Position must be between 0 and 100.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"positionAlign",r({},l,{get:function(){return y},set:function(e){let r=i(t,e);if(!r)throw SyntaxError("An invalid or illegal string was specified.");y=r,this.hasBeenReset=!0}})),Object.defineProperty(this,"size",r({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"align",r({},l,{get:function(){return S},set:function(e){let r=i(t,e);if(!r)throw SyntaxError("An invalid or illegal string was specified.");S=r,this.hasBeenReset=!0}})),this.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}();class aV{decode(e,t){if(!e)return"";if("string"!=typeof e)throw Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function aH(e){function t(e,t,i,r){return(0|e)*3600+(0|t)*60+(0|i)+parseFloat(r||0)}let i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class aY{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function aW(e,t,i,r){let s=r?e.split(r):[e];for(let e in s){if("string"!=typeof s[e])continue;let r=s[e].split(i);2===r.length&&t(r[0],r[1])}}let aj=new aK(0,0,""),aq="middle"===aj.align?"middle":"center";function aX(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class az{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new aV,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;function i(){let e=t.buffer,i=0;for(e=aX(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;let r=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),r}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;let r=(e=i()).match(/^()?WEBVTT([ \t].*)?$/);if(!(null!=r&&r[0]))throw Error("Malformed WebVTT signature.");t.state="HEADER"}let s=!1;for(;t.buffer&&/\r\n|\n/.test(t.buffer);)switch(s?s=!1:e=i(),t.state){case"HEADER":if(/:/.test(e)){var r;r=e,aW(r,function(e,t){},/:/)}else e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new aK(0,0,""),t.state="CUE",-1===e.indexOf("-->")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{!function(e,t,i){let r=e;function s(){let t=aH(e);if(null===t)throw Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=s(),a(),"-->"!==e.slice(0,3))throw Error("Malformed time stamp (time stamps must be separated by '-->'): "+r);e=e.slice(3),a(),t.endTime=s(),a(),function(e,t){let r=new aY;aW(e,function(e,t){let s;switch(e){case"region":for(let s=i.length-1;s>=0;s--)if(i[s].id===t){r.set(e,i[s].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",aq,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",aq,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",aq,"end","left","right"])}},/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===aj.line&&(s=-1),t.line=s,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",aq);let a=r.get("position","auto");"auto"===a&&50===aj.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let i=-1!==e.indexOf("-->");if(!e||i&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){try{if((this.cue||"HEADER"===this.state)&&(this.buffer+="\n\n",this.parse()),"INITIAL"===this.state||"BADWEBVTT"===this.state)throw Error("Malformed WebVTT signature.")}catch(e){this.onparsingerror&&this.onparsingerror(e)}return this.onflush&&this.onflush(),this}}function aQ(e){let t=5381,i=e.length;for(;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}let aZ=/\r\n|\n\r|\n|\r/g,aJ="Missing initPTS for VTT ",a0=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!d(t)||!d(i)||!d(r)||!d(s))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+(1e3*i+6e4*r+36e5*s)};function a1(e,t,i){return aQ(e.toString())+aQ(t.toString())+aQ(i)}let a2="stpp.ttml.im1t",a4=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,a3=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,a8={left:"start",center:"center",right:"end",start:"start",end:"end"};function a5(e,t,i,r){let s=eB(new Uint8Array(e),["mdat"]);if(0===s.length){r(Error("Could not parse IMSC1 mdat"));return}let a=s.map(e=>eS(e)),n=function(e,t,i=1,r=!1){return r5(e,1,1/i,r)}(t.baseTime,0,t.timescale);
28try{a.forEach(e=>i(function(e,t){let i=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw Error("Invalid ttml");let r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(r).reduce((e,t)=>(e[t]=i.getAttribute(`ttp:${t}`)||r[t],e),{}),a="preserve"!==i.getAttribute("xml:space"),n=a9(a6(i,"styling","style")),l=a9(a6(i,"layout","region")),o=a6(i,"body","[begin]");return[].map.call(o,e=>{let i=function e(t,i){return[].slice.call(t.childNodes).reduce((t,r,s)=>{var a;return"br"===r.nodeName&&s?t+"\n":null!=(a=r.childNodes)&&a.length?e(r,i):i?t+r.textContent.trim().replace(/\s+/g," "):t+r.textContent},"")}(e,a);if(!i||!e.hasAttribute("begin"))return null;let r=nt(e.getAttribute("begin"),s),o=nt(e.getAttribute("dur"),s),h=nt(e.getAttribute("end"),s);if(null===r)throw ne(e);if(null===h){if(null===o)throw ne(e);h=r+o}let d=new aK(r-t,h-t,i);d.id=a1(d.startTime,d.endTime,d.text);let u=l[e.getAttribute("region")],f=function(e,t,i){let r="http://www.w3.org/ns/ttml#styling",s=null,a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return a&&i.hasOwnProperty(a)&&(s=i[a]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((i,a)=>{let n=a7(t,r,a)||a7(e,r,a)||a7(s,r,a);return n&&(i[a]=n),i},{})}(u,n[e.getAttribute("style")],n),{textAlign:c}=f;if(c){let e=a8[c];e&&(d.lineAlign=e),d.align=c}return K(d,f),d}).filter(e=>null!==e)}(e,n)))}catch(e){r(e)}}function a6(e,t,i){let r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function a9(e){return e.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function a7(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function ne(e){return Error(`Could not parse ttml timestamp ${e}`)}function nt(e,t){if(!e)return null;let i=aH(e);return null===i&&(a4.test(e)?i=function(e,t){let i=a4.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return(0|i[1])*3600+(0|i[2])*60+(0|i[3])+r/t.frameRate}(e,t):a3.test(e)&&(i=function(e,t){let i=a3.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}function ni(e,t,i,r="",s="disabled"){let a=e.ownerDocument.createElement("track");return a.kind=t,a.label=i,r&&(a.srclang=r),a.src="data:,WEBVTT",a.track.mode=s,e.appendChild(a),a}function nr(e,t){let i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw Error(`addCue is failed for: ${t}`)}catch(i){eo.debug(`[texttrack-utils]: ${i}`);try{let i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){eo.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function ns(e,t,i,r){let s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){let s=function(e,t,i){let r=[],s=function(e,t){let i;if(t<=e[0].startTime)return 0;let r=e.length-1;if(t>e[r].endTime)return -1;let s=0,a=r;for(;s<=a;)if(t<e[i=Math.floor((a+s)/2)].startTime)a=i-1;else{if(!(t>e[i].startTime)||!(s<r))return i;s=i+1}return e[s].startTime-t<t-e[a].startTime?s:a}(e,t);if(s>-1)for(let a=s,n=e.length;a<n;a++){let s=e[a];if(s.startTime>=t&&s.endTime<=i)r.push(s);else if(s.startTime>i)break}return r}(e.cues,t,i);for(let t=0;t<s.length;t++)(!r||r(s[t]))&&e.removeCue(s[t])}"disabled"===s&&(e.mode=s)}class na extends sp{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{var e,t,i;if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let r=-1,s=!1;if(this.currentTrack){let t=null==(e=this.currentTrack.trackNode)?void 0:e.track.mode;"showing"===t?(r=this.trackId,s=!0):"hidden"===t&&(r=this.trackId)}if(!s)for(let e=0;e<this.tracksInGroup.length;e++){let i=null==(t=this.tracksInGroup[e].trackNode)?void 0:t.track.mode;if("showing"===i){r=e;break}r<0&&"hidden"===i&&(r=e)}r>-1&&(this._subtitleDisplay=(null==(i=this.tracksInGroup[r].trackNode)?void 0:i.track.mode)==="showing"),this.setSubtitleTrack(r,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;
28e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(e=>{!e.trackNode&&(e.trackNode=ni(this.media,e.forced&&(e2.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(e1))?"forced":e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles",e.name,e.lang))});let t=null==(e=this.currentTrack)||null==(e=e.trackNode)?void 0:e.track;(null==t?void 0:t.mode)==="disabled"&&(t.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,t){let i=t.media;this.media=i;let r=this.trackId;this.queuedDefaultTrack>-1&&(r=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(r),this.createTracksInGroup(),this.useTextTrackPolling=!(i.textTracks&&"onchange"in i.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):i.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let i=this.media;if(!i)return;let r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!r&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(e=>{let t=e.trackNode;t&&(t.track.mode="hidden",t.remove(),e.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:i,groupId:r,details:s}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${null==a?void 0:a.groupId}`);return}let n=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,n)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||(null==r?void 0:r.length)!==(null==i?void 0:i.length)||null!=i&&i.some(e=>(null==r?void 0:r.indexOf(e))===-1)){this.groupIds=i;let e=[];
28if(this.tracks.forEach(t=>{(t.textCodec===a2?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!i||i.indexOf(t.groupId)>-1?(t.id=e.length,e.push(t)):t.trackNode&&(t.trackNode.remove(),t.trackNode=void 0))}),e.length===this.tracksInGroup.length){let t=!1;for(let i=0;i<e.length;i++)if(e[i]!==this.tracksInGroup[i]){t=!0;break}if(!t)return}e.length&&this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=e,this.trackId=-1,this.currentTrack=null;let t=this.hls.config.subtitlePreference;if(!s&&t){this.selectDefaultTrack=!1;let i=tP(t,e);if(i>-1)s=e[i];else{let e=tP(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null)),this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,{subtitleTracks:e}),this.setSubtitleTrack(r),this.createTracksInGroup()}}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let s=t[r];if((!i||s.default)&&(i||e)&&(!e||t_(s,e)))return r}if(e){for(let i=0;i<t.length;i++){let r=t[i];if(sv(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){let r=t[i];if(sv(e.attrs,r.attrs,["LANGUAGE"]))return i}}return -1}onError(e,t){!t.fatal&&t.context&&t.context.type===M.SUBTITLE_TRACK&&t.context.id===this.trackId&&tw(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1,!0),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let i=this.currentTrack;if(i&&t_(e,i))return i;let r=tP(e,this.tracksInGroup);if(r>-1){let e=this.tracksInGroup[r];return this.setSubtitleTrack(r,!0),e}if(i);else{let i=tP(e,t);if(i>-1)return t[i]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,s=this.getUrlWithDirectives(e.url,t),a=e.details,n=null==a?void 0:a.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${r}${(null==t?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${n&&a.live?" age "+n.toFixed(1)+(a.type?" "+a.type:""):""} ${s}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;let e=this.currentTrack;this.tracksInGroup.forEach(t=>{if(t.trackNode){let i=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",r=t.trackNode.track;r.mode!==i&&(r.mode=i)}})}setSubtitleTrack(e,t=!1){let i=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=i.length||!d(e)){this.warn(`Invalid subtitle track id: ${e}`);return}let r=this.currentTrack,s=i[e]||null;if(this.trackId=e,this.currentTrack=s,t&&this.toggleTrackModes(),!s){r&&this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}let a=!!s.details&&!s.details.live;if(s===r&&a)return;this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:""));let{id:n,groupId:l="",name:o,type:h,url:u}=s;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:n,groupId:l,name:o,type:h,url:u});let f=this.switchParams(s.url,null==r?void 0:r.details,s.details);this.loadPlaylist(f)}}class nn extends t7{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.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 e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>
28{if(this.hls){var e;this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;let i=this.media=t.media;i7(i,"playing",this.onMediaPlaying),i7(i,"waiting",this.onMediaWaiting),i7(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(re(i,"playing",this.onMediaPlaying),re(i,"waiting",this.onMediaWaiting),re(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;let t=(null==(e=this.hls)?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}tick(){var e;if(!(null!=(e=this.media)&&e.readyState)||!this.hasBuffered)return;let t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}poll(e,t){var i,r,s;let a=null==(i=this.hls)?void 0:i.config;if(!a)return;let n=this.media;if(!n)return;let{seeking:l}=n,o=this.seeking&&!l,h=!this.seeking&&l,d=n.paused&&!l||n.ended||0===n.playbackRate;if(this.seeking=l,e!==t){t&&(this.ended=0),this.moved=!0,!l&&(this.skipRetry=this.nudgeRetry=0,a.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),0===this.waiting&&this.stallResolved(e);return}if(h||o){o&&this.stallResolved(e);return}if(d){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!ir.getBuffered(n).length){this.skipRetry=this.nudgeRetry=0;return}let u=ir.bufferInfo(n,e,0),f=this.fragmentTracker;f&&this.hls&&nd(u,e,f,this.hls);let c=u.nextStart||0;if(l&&f&&this.hls){let t=nl(this.hls.inFlightFragments,e),i=u.len>2,r=!c||t||c-e>2&&!f.getPartialFragment(e);if(i||r)return;this.moved=!1}let g=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&f){if(!(u.len>0)&&!c)return;let t=Math.max(c,u.start||0)-e,i=null!=g&&g.live?2*g.targetduration:2,r=nh(e,f);if(t>0&&(t<=i||r)){n.paused||this._trySkipBufferHole(r);return}}let p=a.detectStallWithCurrentTimeMs,E=self.performance.now(),v=this.waiting,y=this.stalled;if(null===y){if(v>0&&E-v<p)y=this.stalled=v;else{this.stalled=E;return}}let T=E-y;if(!l&&(T>=p||v&&this.moved)&&this.hls){if((null==(s=this.mediaSource)?void 0:s.readyState)==="ended"&&!(null!=g&&g.live)&&1>Math.abs(e-((null==g?void 0:g.edge)||0))){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return;if(n.currentTime!==e){let t=e;e=n.currentTime,this.moved=!0,this.log(`currentTime changed ${t} > ${e}`);return}}let S=ir.bufferInfo(n,e,a.maxBufferHole);this._tryFixBufferStall(S,T,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&e>r.end(0)){let i=ir.bufferedInfo(ir.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){let i=ir.timeRangesToArray(r),s=ir.bufferedInfo(i,t,0).bufferedIndex;if(s>-1&&s<i.length-1){let t=ir.bufferedInfo(i,e,0).bufferedIndex,r=i[s].end,a=i[s+1].start;if((-1===t||t>s)&&a-r<1&&e-r<2){let i=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${r} -> ${a} buffered index: ${t}`);this.warn(i.message),this.media.currentTime+=1e-6;let s=nh(e,this.fragmentTracker);s&&"fragment"in s?s=s.fragment:s||(s=void 0);let n=ir.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:s,buffer:n.len,bufferInfo:n})}}}}}_tryFixBufferStall(e,t,i){var r,s;let{fragmentTracker:a,media:n}=this,l=null==(r=this.hls)?void 0:r.config;if(!n||!a||!l)return;let o=null==(s=this.hls)?void 0:s.latestLevelDetails,h=nh(i,a);if((h||null!=o&&o.live&&i<o.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;let d=e.buffered,u=this.adjacentTraversal(e,i);(d&&d.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||u))&&(t>1e3*l.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let i=this.fragmentTracker,r=e.nextStart;if(i&&r){let e=i.getFragAtPos(t,w.MAIN),s=i.getFragAtPos(r,w.MAIN);if(e&&s)return s.sn-e.sn<2}return!1}_reportStall(e){let{hls:t,media:i,stallReported:r,stalled:s}=this;if(!r&&null!==s&&i&&t){this.stallReported=!0;let r=Error(`Playback stalling at @${i.currentTime} due to low buffer (${tR(e)})`);this.warn(r.message),t.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:s}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:i,hls:r}=this,s=null==r?void 0:r.config;if(!i||!t||!s)return 0;let a=i.currentTime,n=ir.bufferInfo(i,a,0);nd(n,a,t,r);let l=a<n.start?n.start:n.nextStart;if(l){let h=n.len<=s.maxBufferHole,d=n.len>0&&n.len<1&&i.readyState<3,u=l-a;if(u>
280&&(h||d)){if(u>s.maxBufferHole){let i=!1;if(0===a){let e=t.getAppendedFrag(0,w.MAIN);e&&l<e.end&&(i=!0)}if(!i&&e){var o;if(!(null!=(o=r.loadLevelObj)&&o.details)||nl(r.inFlightFragments,l))return 0;let i=!1,s=e.end;for(;s<l;){let e=nh(s,t),r=e?e.duration:0;if(r>0)s+=r;else{i=!0;break}}if(i)return 0}}let{nudgeMaxRetry:h,skipBufferHolePadding:d}=s,f=++this.skipRetry>h,p=Math.max(l,a)+d;if(f||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${p}`),this.moved=!0,i.currentTime=p),!(null!=e&&e.gap)||f){let t=Error(f?`Playhead still not moving after seeking over buffer hole from ${a} to ${p} after ${s.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${p}`),i={type:c.MEDIA_ERROR,details:g.BUFFER_SEEK_OVER_HOLE,fatal:f,error:t,reason:t.message,buffer:n.len,bufferInfo:n};e&&("fragment"in e?i.part=e:i.frag=e),r.trigger(m.ERROR,i)}return p}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:r}=this,s=null==t?void 0:t.config;if(!i||!s)return 0;let a=i.currentTime;if(this.nudgeRetry++,r<s.nudgeMaxRetry){let n=a+(r+1)*s.nudgeOffset,l=Error(`Nudging 'currentTime' from ${a} to ${n}`);this.warn(l.message),i.currentTime=n,t.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{let i=Error(`Playhead still not moving while enough data buffered @${a} after ${s.nudgeMaxRetry} nudges`);this.error(i.message),t.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:e.len,bufferInfo:e})}}}function nl(e,t){let i=no(e.main);if(i&&i.start<=t)return i;let r=no(e.audio);return r&&r.start<=t?r:null}function no(e){if(!e)return null;switch(e.state){case ri.IDLE:case ri.STOPPED:case ri.ENDED:case ri.ERROR:return null}return e.frag}function nh(e,t){return t.getAppendedFrag(e,w.MAIN)||t.getPartialFragment(e)}function nd(e,t,i,r){let s=r.latestLevelDetails,a=nh(t,i);if(ra(r.config)&&!e.nextStart&&s&&a&&r.interstitialsManager){let i="type"in a?a:a.fragment,n=tG(s,i.sn,!0);(null==n?void 0:n.level)===i.level&&rs(n,r.interstitialsManager.playerQueue,t)&&(e.nextStart=n.start)}}function nu(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function nf(e,t,i,r,s){let a=new e(t,i,"");try{a.value=r,s&&(a.type=s)}catch(n){a=new e(t,i,tR(s?H({type:s},r):r))}return a}let nc=(()=>{let e=nu();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class ng{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(m.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;
28e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;let t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return ni(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:r}=this.hls.config;if(!i&&!r)return;let{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=nu();if(a)for(let e=0;e<s.length;e++){let t=s[e].type;if(t===rE.emsg&&!i||!r)continue;let n=eA(s[e].data),l=s[e].pts,o=l+s[e].duration;o>nc&&(o=nc),o-l<=0&&(o=l+.25);for(let e=0;e<n.length;e++){let i=n[e];if(!eI(i)){this.updateId3CueEnds(l,t);let e=nf(a,l,o,i,t);e&&this.id3Track.track.addCue(e)}}}}updateId3CueEnds(e,t){var i;let r=null==(i=this.id3Track)?void 0:i.track.cues;if(r)for(let i=r.length;i--;){let s=r[i];s.type===t&&s.startTime<e&&s.endTime===nc&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:r}){let{id3Track:s,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:n,enableID3MetadataCues:l}}=a;if(s&&(n||l)){let e;e="audio"===r?e=>e.type===rE.audioId3&&l:"video"===r?e=>e.type===rE.emsg&&n:e=>e.type===rE.audioId3&&l||e.type===rE.emsg&&n,ns(s.track,t,i,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){var i,r;if(!this.hls||!this.media)return;let{assetPlayerId:s,timelineOffset:a,enableDateRangeMetadataCues:n,interstitialsController:l}=this.hls.config;if(!n)return;let o=nu();if(s&&a&&!l){let{fragmentStart:t,fragmentEnd:i}=e,r=this.assetCue;r?(r.startTime=t,r.endTime=i):o&&(r=this.assetCue=nf(o,t,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(r),r.addEventListener("enter",this.onEventCueEnter))}if(!e.hasProgramDateTime)return;let{id3Track:h}=this,{dateRanges:u}=e,f=Object.keys(u),c=this.dateRangeCuesAppended;if(h&&t){if(null!=(i=h.track.cues)&&i.length){let e=Object.keys(c).filter(e=>-1===f.indexOf(e));for(let t=e.length;t--;){let i=e[t],s=null==(r=c[i])?void 0:r.cues;delete c[i],s&&Object.keys(s).forEach(e=>{let t=s[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{h.track.removeCue(t)}catch(e){}}})}}else c=this.dateRangeCuesAppended={}}let g=e.fragments[e.fragments.length-1];if(0!==f.length&&d(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<f.length;e++){let t=f[e],i=u[t],r=i.startTime,s=c[t],a=(null==s?void 0:s.cues)||{},n=(null==s?void 0:s.durationKnown)||!1,h=nc,{duration:d,endDate:g}=i;if(g&&null!==d)h=r+d,n=!0;else if(i.endOnNext&&!n){let e=f.reduce((e,t)=>{if(t!==i.id){let r=u[t];if(r.class===i.class&&r.startDate>i.startDate&&(!e||i.startDate<e.startDate))return r}return e},null);e&&(h=e.startTime,n=!0)}let m=Object.keys(i.attr);for(let e=0;e<m.length;e++){let d=m[e];if(!("ID"!==d&&"CLASS"!==d&&"CUE"!==d&&"START-DATE"!==d&&"DURATION"!==d&&"END-DATE"!==d&&"END-ON-NEXT"!==d))continue;let u=a[d];if(u)n&&!(null!=s&&s.durationKnown)?u.endTime=h:Math.abs(u.startTime-r)>.01&&(u.startTime=r,u.endTime=h);else if(o){let e=i.attr[d];("SCTE35-OUT"===d||"SCTE35-IN"===d||"SCTE35-CMD"===d)&&(e=eb(e));let s=nf(o,r,h,{key:d,data:e},rE.dateRange);s&&(s.id=t,this.id3Track.track.addCue(s),a[d]=s,l&&("X-ASSET-LIST"===d||"X-ASSET-URL"===d)&&s.addEventListener("enter",this.onEventCueEnter))}}c[t]={cues:a,dateRange:i,durationKnown:n}}}}}function nm(){return self.SourceBuffer||self.WebKitSourceBuffer}function np(){if(!eh())return!1;let e=nm();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}var nE={DISABLED:0,SWITCHING:1,SWITCHED:2};class nv extends rr{constructor(e,t,i){super(e,t,i,"stream-controller",w.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=nE.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let e=this.media,t=e?e.currentTime:null;if(null===t||!d(t)||(this.log(`Media seeked to ${t}`),!this.getBufferedFrag(t)))return;let i=this.getFwdBufferInfoAtPos(e,t,w.MAIN,0);if(!i||0===i.len){this.log(`Main buffer empty at ${t} on "seeked" event: ${i?i.len:i}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}
28startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=r.startLevel;-1===e&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i}`),e=i),this.state=ri.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=ri.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case ri.WAITING_LEVEL:{let{levels:e,level:t}=this,i=null==e?void 0:e[t],r=null==i?void 0:i.details;if(!r||r.live&&(this.levelLastLoaded!==i||this.waitForLive(i)))this.hls.nextLoadLevel!==this.level&&(this.state=ri.IDLE);else{if(this.waitForCdnTuneIn(r))break;this.state=ri.IDLE}break}case ri.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===ri.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(null===t||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let s=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(null!=i&&i[s]))return;let a=i[s],n=this.getMainFwdBufferInfo();if(null===n)return;let l=this.getLevelDetails();if(l&&this._streamEnded(n,l)){let e={type:this.targetBufferType()};this.hls.trigger(m.BUFFER_EOS,e),this.state=ri.ENDED;return}if(!this.buffering)return;e.loadLevel!==s&&-1===e.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;let o=a.details;if(!o||this.state===ri.WAITING_LEVEL||this.waitForLive(a)){this.level=s,this.state=ri.WAITING_LEVEL,this.startFragRequested=!1;return}let h=n.len,d=this.getMaxBufferLength(a.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>n.end&&(this.backtrackFragment=void 0);let u=this.backtrackFragment?this.backtrackFragment.start:n.end,f=this.getNextFragment(u,o);if(this.couldBacktrack&&!this.fragPrevious&&f&&N(f)&&this.fragmentTracker.getState(f)!==tq.OK){var c;let e=(null!=(c=this.backtrackFragment)?c:f).sn-o.startSN,t=o.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&n.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,u)){if(!f.gap){let e=this.audioOnly&&!this.altAudio?F.AUDIO:F.VIDEO,t=(e===F.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e)}f=this.getNextFragmentLoopLoading(f,o,n,w.MAIN,d)}!f||this.exceedsMaxBuffer(n,d,f)||this.loadFragment(f,a,u)}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);r===tq.NOT_LOADED||r===tq.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==nE.DISABLED){var e;((null==(e=this.getLevelDetails())?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===nE.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let t=this.fragPlaying;if(t){let i=t.level;this.hls.trigger(m.FRAG_CHANGED,{frag:t,previousFrag:e}),(null==e?void 0:e.level)!==i&&this.hls.trigger(m.LEVEL_SWITCHED,{level:i})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio!==nE.SWITCHED||this.audioOnly?null:"video"}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;i7(i,"playing",this.onMediaPlaying),i7(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:i}=this;i&&(re(i,"playing",this.onMediaPlaying),re(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,t),t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=nE.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,r=!1;for(let e=0;e<t.levels.length;e++){let s=t.levels[e].audioCodec;s&&(i=i||-1!==s.indexOf("mp4a.40.2"),r=r||-1!==s.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&r&&!function(){var e;let t=nm();return"function"==typeof(null==t||null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==ri.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=ri.WAITING_LEVEL)}onLevelLoaded(e,t){var i,r;let{levels:s,startFragRequested:a}=this,n=t.level,l=t.details,o=l.totalduration;if(!s){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""}, cc [${l.startCC}, ${l.endCC}] duration:${o}`);let h=t.levelInfo,d=this.fragCurrent;d&&(this.state===ri.FRAG_LOADING||this.state===ri.FRAG_LOADING_WAITING_RETRY)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let u=0;if(l.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(l),l.deltaUpdateFailed)return;u=this.alignPlaylists(l,h.details,null==(r=this.levelLastLoaded)?void 0:r.details)}if(h.details=l,this.levelLastLoaded=h,a||this.setStartPosition(l,u),this.hls.trigger(m.LEVEL_UPDATED,{details:l,level:n}),this.state===ri.WAITING_LEVEL){if(this.waitForCdnTuneIn(l))return;this.state=ri.IDLE}a&&l.live&&this.synchronizeToLiveEdge(l),this.initPTS.some((e,t)=>{if(t>=l.startCC)return!0;delete this.initPTS[t]}),this.tick()}
28synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let r=this.hls.liveSyncPosition,s=this.playhead,a=e.fragmentStart,n=e.edge,l=s>=a-t.maxFragLookUpTolerance&&s<=n;if(null!==r&&i.duration>r&&(s<r||!l)){let a=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||s<n-a)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState)){if(this.warn(`Playback: ${s} is located too far from the end of live sliding playlist: ${n}, reset currentTime to : ${r}`),"buffered"===this.config.liveSyncMode){var o;let e=ir.bufferInfo(i,r,0);if(!(null!=(o=e.buffered)&&o.length)||e.start<=s){i.currentTime=r;return}let{nextStart:t}=ir.bufferedInfo(e.buffered,s,0);t&&(i.currentTime=t)}else i.currentTime=r}}}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:s}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let n=a[i.level];if(!n){this.warn(`Level ${i.level} not found on progress`);return}let l=n.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=n.videoCodec,h=l.PTSKnown||!l.live,d=null==(t=i.initSegment)?void 0:t.data,u=this._getAudioCodec(n),f=this.transmuxer=this.transmuxer||new sg(this.hls,w.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),c=r?r.index:-1,{decryptRange:g,byteRange:m}=t5(i,r,this.iframesOnly),p=new ie(i.level,i.sn,i.stats.chunkCount,m?m.end-m.start:s.byteLength,c,-1!==c,i.duration,this.iframesOnly,g),E=this.initPTS[i.cc];f.push(s,d,u,o,i,r,l.totalduration,h,p,E)}onAudioTrackSwitching(e,t){let i=this.hls,r=this.altAudio!==nE.DISABLED;if(tM(t.url,i))this.altAudio=nE.SWITCHING;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r){this.altAudio=nE.DISABLED,this.fragmentTracker.removeAllFragments(),i.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),i.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=tM(t.url,this.hls);if(i){let e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=i?nE.SWITCHED:nE.DISABLED,this.tick()}onBufferCreated(e,t){let i,r;let s=t.tracks,a=!1;for(let e in s){let t=s[e];if("main"===t.id){if(r=e,i=t,"video"===e){let t=s[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:r}=t,s=i.type===w.MAIN;if(s){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===ri.PARSED&&(this.state=ri.IDLE);return}let e=!1;if(N(i)&&(e=!!i.gap&&!i.tagList.some(e=>"GAP"===e[0])),this.fragBufferedComplete(i,r),e){var a;i.stats.retry++;let e=null==(a=this.levels)?void 0:a[i.level];e&&e.fragmentError++}}let n=this.media;n&&(!this._hasEnoughToStart&&ir.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=ri.ERROR;return}switch(t.details){case g.FRAG_GAP:case g.FRAG_PARSING_ERROR:case g.FRAG_DECRYPT_ERROR:case g.FRAG_LOAD_ERROR:case g.FRAG_LOAD_TIMEOUT:case g.KEY_LOAD_ERROR:case g.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(w.MAIN,t);break;case g.LEVEL_LOAD_ERROR:case g.LEVEL_LOAD_TIMEOUT:case g.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==ri.WAITING_LEVEL||(null==(i=t.context)?void 0:i.type)!==M.LEVEL||(this.state=ri.IDLE);break;case g.BUFFER_APPEND_NO_PROGRESS:if("main"!==t.parent)return;t.frag&&(t.appendsWithoutProgress||0)>
28=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case g.BUFFER_ADD_CODEC_ERROR:case g.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case g.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case g.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=ri.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==F.AUDIO||!this.altAudio){let e=(t===F.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&i&&(i+=r);let s=this.getLevelDetails(),a=ir.getBuffered(e),n=a.length?a.start(0):0,l=n-i,o=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<o||this.loadingParts&&l<2*((null==s?void 0:s.partTarget)||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${n}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{let{hls:i}=this,r=null==e?void 0:e.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=ri.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let s=r.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,e),r.bitrateTest=!1}).catch(t=>{this.state!==ri.STOPPED&&this.state!==ri.ERROR&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:s}=e,a=this.getCurrentContext(s);if(!a){this.resetWhenMissingContext(s);return}let{frag:n,part:l,level:o}=a,{video:h,text:u,id3:f,initSegment:c}=r,{details:g}=o,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(n)){this.fragmentTracker.removeFragment(n);return}if(this.state=ri.PARSING,c){let e=c.tracks;if(e){let r=n.initSegment||n;if(this.unhandledEncryptionError(c,n))return;this._bufferInitSegment(o,e,r,s),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:t,tracks:e})}let r=c.initPTS,a=c.timescale,l=this.initPTS[n.cc];if(d(r)&&(!l||l.baseTime!==r||l.timescale!==a)){let e=c.trackId;this.initPTS[n.cc]={baseTime:r,timescale:a,trackId:e};let s=this.initPTS.slice(0);i.trigger(m.INIT_PTS_FOUND,{timestampOffsets:s,frag:n,id:t,initPTS:r,timescale:a,trackId:e})}}if(h&&g){p&&"audiovideo"===h.type&&this.logMuxedErr(n);let e=g.fragments[n.sn-1-g.startSN],t=n.sn===g.startSN,i=!e||n.cc>e.cc;if(!1!==r.independent){let{startPTS:e,endPTS:r,startDTS:a,endDTS:o}=h;if(l)l.elementaryStreams[h.type]={startPTS:e,endPTS:r,startDTS:a,endDTS:o};else if(h.firstKeyFrame&&h.independent&&1===s.id&&!i&&(this.couldBacktrack=!0),h.dropped&&h.independent){let s=this.getMainFwdBufferInfo(),a=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=h.firstKeyFramePTS?h.firstKeyFramePTS:e;if(t||!(a<l-this.config.maxBufferHole)||i)i&&(n.gap=!0);else{this.backtrack(n);return}n.setElementaryStreamInfo(h.type,n.start,r,n.start,o,!0)}
28else t&&e-(g.appliedTimelineOffset||0)>2&&(n.gap=!0);n.setElementaryStreamInfo(h.type,e,r,a,o),this.backtrackFragment&&(this.backtrackFragment=n),this.bufferFragmentData(h,n,l,s,t||i)}else if(t||i)n.gap=!0;else{this.backtrack(n);return}}if(p){let{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=p;l&&(l.elementaryStreams[F.AUDIO]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),n.setElementaryStreamInfo(F.AUDIO,e,t,i,r),this.bufferFragmentData(p,n,l,s)}if(g&&null!=f&&f.samples.length){let e={id:t,frag:n,details:g,samples:f.samples};i.trigger(m.FRAG_PARSING_METADATA,e)}if(g&&u){let e={id:t,frag:n,details:g,samples:u.samples};i.trigger(m.FRAG_PARSING_USERDATA,e)}}logMuxedErr(e){this.warn(`${N(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,r){if(this.state!==ri.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:s,video:n,audiovideo:l}=t;if(s){let i=e.audioCodec,r=tn(s.codec,i);if("mp4a"===r&&(r="mp4a.40.5"),this.audioCodecSwitch){r&&(r=-1!==r.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");let e=s.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&!function(){if(void 0===a){let e=e1.match(/Firefox\/(\d+)/i);a=e?parseInt(e[1]):0}return a}()&&(r="mp4a.40.5")}r&&-1!==r.indexOf("mp4a.40.5")&&/Android/.test(e1)&&"audio/mpeg"!==s.container&&(r="mp4a.40.2",this.log(`Android: force audio codec to ${r}`)),i&&i!==r&&this.log(`Swapping manifest audio codec "${i}" for "${r}"`),s.levelCodec=r,s.id=w.MAIN,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${r||""}/${i||""}/${s.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=w.MAIN;let i=n.codec;if((null==i?void 0:i.length)===4)switch(i){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i}]${n.codec!==i?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}l&&(this.iframesOnly&&this.logMuxedErr(i),this.log(`Init audiovideo buffer, container:${l.container}, codecs[level/parsed]=[${e.codecs}/${l.codec}]`),delete t.video,delete t.audio);let o=Object.keys(t);if(o.length){if(this.hls.trigger(m.BUFFER_CODECS,t),!this.hls)return;o.forEach(e=>{let s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:e,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.getBufferOutput();return this.getFwdBufferInfo(e,w.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,i=null==e?void 0:e[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=ri.IDLE}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return d(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(d(t)){let e=this.getLevelDetails(),i=this.currentFrag||(e?t$(null,e.fragments,t):null);if(i){let e=i.programDateTime;if(null!==e)return new Date(e+(t-i.start)*1e3)}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class ny extends nv{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{let e=this.media;null!=e&&e.seeking&&(e.currentTime=e.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;let{seekOnAppend:i}=t,r=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=r,this.startPosition=e,this.state){case ri.STOPPED:case ri.ENDED:case ri.ERROR:this.state=ri.IDLE}this.state===ri.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[r,t]):this.nextOp=[r,t],this.hls.off(m.BUFFERED_TO_END,this.onBufferedToEnd);let s=this.media;i&&s&&this.seekTo(r)&&(this.currentOp=[r,t],this.nextOp=void 0,this.flushPipeline(r,!0))}seekTo(e){let t=this.media;if(t){var i;let r=null==(i=this.getLevelDetails())?void 0:i.edge,s=void 0!==r?r:t.duration;if(e>=s&&(e=s-.01),ir.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,w.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;let i=this.cached;i.push(e),this.cachedSize+=t.buffer.byteLength;let r=this.hls.config.iframeCacheLimit;for(;this.cachedSize>r&&i.length>1;){let e=i.shift();if(e.data)this.cachedSize-=e.data.byteLength,e.data=void 0;else{this.cached=i.filter(e=>!!e.data),this.cachedSize=i.reduce((e,{data:t})=>t?t.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){let t=e.frag,{part:i,payload:r}=e;this.cacheFragmentData&&!i&&null!=r&&r.byteLength&&!t.data&&N(t)&&this.cacheSet(t,new Uint8Array(r.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if((r===tq.NOT_LOADED||r===tq.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,i)}canReplayCached(e){var t;if(!this.cacheFragmentData||!(null!=(t=e.data)&&t.byteLength))return!1;let i=e.decryptdata;return(null==i?void 0:i.keyFormat)!=="identity"||!!i.key}replayCachedFragment(e){let t=e.data.slice().buffer;
vendor: 1,253 bytes, line 28
28this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;let i=e.stats=new O;i.loading.start=i.loading.first=i.loading.end=self.performance.now(),i.loaded=i.total=t.byteLength,i.chunkCount=1,this.state=ri.FRAG_LOADING;let r={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(r),this.hls.trigger(m.FRAG_LOADED,r),this._handleFragmentLoadComplete(r)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);let{currentOp:i,nextOp:r}=this;this.currentOp=this.nextOp=void 0,this.state=ri.STOPPED,null!=i&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!r),this.seekTo(i[0])||this.log(`Could not seek to ${i[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?rt(ir.getBuffered(this.media)):"none"}`)),r&&this.loadMediaAt.apply(this,r)}flushPipeline(e,t){if(t){let t=this.media;if(t){let i=ir.bufferInfo(t,e,0),r=i.len?i.nextStart:0;r&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,w.MAIN),this.flushMainBuffer(r,1/0))}this.hls.once(m.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(m.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){let e=this.hls;
28e.nextLoadLevel=-1===e.startLevel?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,i){let r=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,i||r||void 0)}getMainFwdBufferInfo(){let e=this.playhead,t=this.getBufferedAt(e);if(t){let i=t.duration;return{len:i,start:e,end:e+i,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){let e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,w.MAIN);return!!(null!=t&&t.endList)}}class nT extends ny{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var t;let i=null==(t=this._img)?void 0:t.src;i&&self.URL.revokeObjectURL(i),this._img=e}loadMediaAt(e){if(!this.hls)return;let t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case ri.STOPPED:case ri.ENDED:case ri.ERROR:this.state=ri.IDLE}if(this.state===ri.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===ri.IDLE){let t=this.getBufferedAt(e);t&&(this.fragCurrent=t,this.updateImage(t,null))}}else{let i=this.fragCurrent;(!i||e>=i.start&&e<i.end)&&(this.queued=[t])}}updateImage(e,t,i){let r=e.data;r||this.fragmentTracker.removeFragment(e);let s=this._img;if(s&&r){let a=self.performance.now();(t?t.stats:e.stats).buffering.start=e.stats.buffering.start=a,s.onload=()=>{if(!this.hls)return;let r=this.hls.levels[e.level];null!=r&&r.fragmentError&&(r.fragmentError=0,e.stats.retry=0);let s=self.performance.now(),a=t?t.stats:e.stats;a.buffering.end=e.stats.buffering.end=s,this.hls.trigger(m.FRAG_BUFFERED,{frag:e,part:t,stats:a,id:e.type,chunkMeta:i})},s.onerror=()=>{this.handleError("Image decode error",e,t,i)};let n=s.src;n&&self.URL.revokeObjectURL(n);let l=new Blob([r],{type:"image/jpeg"});s.src=self.URL.createObjectURL(l)}else this.state=ri.STOPPED,this.processQueued()}processQueued(){let e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,i,r){if(!this.hls)return;let s=Error(e);this.hls.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.FRAG_PARSING_ERROR,chunkMeta:r,frag:t,part:i,fatal:!1,error:s,err:s})}_bufferInitSegment(){}bufferFragmentData(e,t,i,r){super.bufferFragmentData(e,t,i,r,!0);let s=eB(new Uint8Array(e.data1),["mdat"]);if(0===s.length){this.handleError("Could not find I-Frame mdat",t,i,r);return}this.cacheSet(t,s[0]),this.updateImage(t,i,r)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){var e;let t=null==(e=this.fragPrevious)?void 0:e.start;if(void 0!==t){let e=this.getAppendedFrag(t);if(e&&!$(e,this.fragPlaying))return this.fragPlaying=e,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}let nS={seekOnAppend:!0};class nA extends er{constructor(e,t){var i,r;super("iframes",e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,o||(i=t,o=class extends i{constructor(e,t,i,r){e.streamController||(e.streamController=ny),super(e),this._url=t,this.streamController.setInitPts(i),this.streamController.initDetails=r}loadSource(){}loadMediaAt(e,t=nS){if(e<0)return;let i=H(H({},nS),t);this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e,i)}}),h||(r=o,h=class extends r{constructor(e,t,i,r){e.cmcdController=void 0,e.emeController=void 0,e.streamController||(e.streamController=nT),e.capLevelController=void 0,e.bufferController=void 0,super(e,t,i,r)}attachImage(e){this.streamController.image=e}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw Error("Image I-Frame player does not accept HTMLMediaElements")}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(e){if(e<0)return null;this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e)}}),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(m.MANIFEST_LOADING,this.clearAsset,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(m.MANIFEST_LOADING,this.clearAsset,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEac
28h(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){var i;let r=null==(i=this.hls)?void 0:i.pathwayPriority;t.length&&r&&this.iframeInstances.forEach(e=>{e.pathwayPriority=r})}onInitPtsFound(e,{id:t,timestampOffsets:i}){t===w.MAIN&&(this.initPTS=i)}onFragBuffered(e,t){var i;let r=this.hls;r&&r.hasEnoughToStart&&((null==(i=r.mainForwardBufferInfo)?void 0:i.len)||0)>10&&this.iframeInstances.forEach(e=>{if(!e.loadingEnabled){var t;e.startLoad((null==(t=this.hls)||null==(t=t.media)?void 0:t.currentTime)||0)}})}createIFramePlayer(e){var t;return this.createInstance(o,null==(t=this.hls)?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;let i=null==(t=this.hls)?void 0:t.iframeVariants.filter(e=>e.imageCodec);return this.createInstance(h,i,e,"image-")}createInstance(e,t,i,r){let{hls:s}=this;if(!s)return null;let{url:a,userConfig:n,latestLevelDetails:l,loadLevelObj:o,loadLevel:h,bandwidthEstimate:d,sessionId:u}=s,{stats:f,variableList:c}=this;if(!(null!=t&&t.length)||!f||!a)return null;let g=`${r||""}iframe-player-${this.instanceCounter++}`,p=s.levels,E=o||p[h],v=tF(E,n.videoPreference),y=(null==E?void 0:E.pathwayId)||".",T=new e(H(H({},n),{},{loggerId:g,primarySessionId:u,videoPreference:v,abrEwmaDefaultEstimate:d,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},i),a,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(e=>!e.url),this.iframeInstances.push(T),T.trigger(m.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:y},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:c}),T}}let nI=((L={})[L.Point=0]="Point",L[L.Range=1]="Range",L);class nL{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let i=this.playoutLimit;return!(e<=0||isNaN(i))&&(0===i||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>i)}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return nR(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,i=nR(t,e);return t-i<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=d(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return nR(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&.025>Math.abs(this.resumeOffset-this.duration)))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){let e;let t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?nI.Range:nI.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${this.identifier}" ${this.cue.pre?"<pre>":this.cue.post?"<post>":""}${this.timelineStart.toFixed(2)}-${this.resumeTime.toFixed(2)}]`}}function nR(e,t){return e-t.start<t.duration/2&&!(.025>Math.abs(e-(t.start+t.duration)))?t.start:t.start+t.duration}function nb(e,t,i){let r=new self.URL(e,i);return"data:"!==r.protocol&&tp(r,"_HLS_primary_id",t),r}function nD(e,t){for(;null!=(i=e.assetList[++t])&&i.error;)var i;return t}function nk(e){let t=e.timelineStart,i=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+i).toFixed(2)}]`}class nP{constructor(e,t,i,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetail
28s=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(m.PLAYOUT_LIMIT_REACHED,{})};let s=this.hls=new e(t);this.interstitial=i,this.assetItem=r;let a=()=>{this.hasDetails=!0};s.once(m.LEVEL_LOADED,a),s.once(m.AUDIO_TRACK_LOADED,a),s.once(m.SUBTITLE_TRACK_LOADED,a),s.on(m.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&s.on(m.BUFFER_APPENDED,()=>{let e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,s.trigger(m.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e){if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=nb(t,e.config.primarySessionId||"").href}catch(e){}e.loadSource(t)}}}bufferedInPlaceToEnd(e,t){var i;if(!this.appendInPlace)return!1;if(null!=(i=this.hls)&&i.bufferedToEnd)return!0;if(!e)return!1;let r=Math.min(this._bufferedEosTime||1/0,this.duration),s=this.timelineOffset+(t||0),a=ir.bufferInfo(e,s,.02);return this.getAssetTime(a.end)>=r-.02}reachedPlayout(e){let t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=ir.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t&&Math.abs(e-t)>1/9e4&&this.hls){if(this.hasDetails)throw Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}getAssetTime(e){return Math.min(Math.max(0,e-this.timelineOffset),this.duration)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var r;null==(r=this.hls)||r.on(e,t)}once(e,t,i){var r;null==(r=this.hls)||r.once(e,t)}off(e,t,i){var r;null==(r=this.hls)||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${nk(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class n_ extends er{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={}
28,this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(s=r[i])&&s.event;){var s;i--}return i}findItemIndexAtTime(e,t){let i=this.items;if(i)for(let r=0;r<i.length;r++){let s=i[r];t&&"primary"!==t&&(s=s[t]);let a=s.start,n=i[r].event,l=null!=n&&n.cue.pre?n.duration:s.end;if(e===a||e>a&&e<l)return r}return -1}findJumpRestrictedIndex(e,t){let i=this.items;if(i)for(let r=e;r<=t&&i[r];r++){let e=i[r].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return r}return -1}findEventIndex(e){let t=this.items;if(t)for(let r=t.length;r--;){var i;if((null==(i=t[r].event)?void 0:i.identifier)===e)return r}return -1}findAssetIndex(e,t){let i=e.assetList,r=i.length;if(r>1)for(let e=0;e<r;e++){let s=i[e];if(!s.error){let i=s.timelineStart;if(t===i||t>i&&(t<i+(s.duration||0)||e===r-1))return e}}return 0}get assetIdAtEnd(){var e;let t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){let e=t.assetList,i=e[e.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t,i=0){let r=e.main.details,{dateRanges:s}=r,a=this.events,n=this.parseDateRanges(s,{url:r.url},t),l=Object.keys(s),o=a?a.filter(e=>-1===l.indexOf(e.identifier)):[];n.length&&n.sort((e,t)=>{let i=e.cue.pre,r=e.cue.post,s=t.cue.pre,a=t.cue.post;if(i&&!s)return -1;if(s&&!i||r&&!a)return 1;if(a&&!r)return -1;if(!i&&!s&&!r&&!a){let i=e.startTime,r=t.startTime;if(i!==r)return i-r}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=n,o.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,o,i)}updateSchedule(e,t=[],i=0,r=!1){let s=this.events||[];
28if(s.length||t.length||this.length<2){let a=this.items,n=this.parseSchedule(s,e,i);(r||t.length||(null==a?void 0:a.length)!==n.length||n.some((e,t)=>Math.abs(e.playout.start-a[t].playout.start)>.005||Math.abs(e.playout.end-a[t].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,i){let r=[],s=Object.keys(e);for(let a=0;a<s.length;a++){let n=s[a],l=e[n];if(l.isInterstitial){let e=this.eventMap[n];e?e.setDateRange(l):(e=new nL(l,t),this.eventMap[n]=e,!1===i&&(e.appendInPlace=i)),r.push(e)}}return r}parseSchedule(e,t,i=0){let r=[],s=t.main.details,a=s.live?1/0:s.edge,n=0;if((e=e.filter(e=>!e.error&&!(e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let o=0,h=0;if(e.forEach((t,l)=>{let d=t.cue.pre,u=t.cue.post,f=e[l-1]||null,c=t.appendInPlace,g=u?a:t.startOffset,m=t.duration,p=t.timelineOccupancy===nI.Range?m:0,E=d&&s.live?i+(t.resumeOffset||0):0,v=E||t.resumptionOffset,y=(null==f?void 0:f.startTime)===g,T=g+t.cumulativeDuration,S=c?T+m:g+v;if(d||!u&&g<=0){let e=h;h+=p,t.timelineStart=T;let i=n;n+=m,r.push({event:t,start:T,end:S,playout:{start:i,end:n},integrated:{start:e,end:h}})}else{if(!(g<=a))return;if(!y){let i=g-o;if(i>.033){let s=o,a=h;h+=i;let d=n;n+=i;let u={previousEvent:e[l-1]||null,nextEvent:t,start:s,end:s+i,playout:{start:d,end:n},integrated:{start:a,end:h}};r.push(u)}else i>0&&f&&(f.cumulativeDuration+=i,r[r.length-1].end=g)}u&&(S=T),t.timelineStart=T;let i=h;h+=p;let s=n;n+=m,r.push({event:t,start:T,end:S,playout:{start:s,end:n},integrated:{start:i,end:h}})}let A=E||t.resumeTime;o=u||A>a?a:!d&&S&&t.appendInPlaceStarted&&A-S>.033?S:A}),o<a){var l;let e=o,t=h,i=a-o;h+=i;let s=n;n+=i,r.push({previousEvent:(null==(l=r[r.length-1])?void 0:l.event)||null,nextEvent:null,start:o,end:e+i,playout:{start:s,end:n},integrated:{start:t,end:h}})}this.setDurations(a,n,h)}else r.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return r}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){let i=t.main.details,r=i.live?1/0:i.edge,s=0,a=-1;e.forEach((n,l)=>{let o=n.cue.pre,h=n.cue.post,u=o?0:h?r:n.startTime;this.updateAssetDurations(n),a===u?n.cumulativeDuration=s:(s=0,a=u),!h&&n.snapOptions.in&&(n.resumeAnchor=t$(null,i.fragments,n.startOffset+n.resumptionOffset,0,0)||void 0),!n.appendInPlace||n.appendInPlaceStarted||this.primaryCanResumeInPlaceAt(n,t)||(n.appendInPlace=!1),!n.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<.033&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${n}`));let f=d(n.resumeOffset)?n.resumeOffset:n.duration;s+=f})}primaryCanResumeInPlaceAt(e,t){let i=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(i-r)>.025?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(r=>{let s=t[r].details,a=s.edge;if(i>=a)return this.log(`"${e.identifier}" resumption ${i} past ${r} playlist end ${a}`),!1;let n=t$(null,s.fragments,i);if(!n)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${r} playlist (${s.fragStart}-${s.fragmentEnd})`),!0;let l="audio"===r?.175:0;return!(Math.abs(n.start-i)<.025+l||Math.abs(n.end-i)<.025+l)&&(this.log(`"${e.identifier}" resumption ${i} not aligned with ${r} fragment bounds (${n.start}-${n.end} sn: ${n.sn} cc: ${n.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,i=0,r=!1,s=!1;for(let a=0;a<e.assetList.length;a++){let n=e.assetList[a],l=t+i;n.startOffset=i,n.timelineStart=l,r||(r=null===n.duration),s||(s=!!n.error),i+=n.error?0:n.duration||0}r&&!s?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function nC(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class nO{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let i;let r=e.assetListUrl;try{i=nb(r,this.hls.sessionId,e.baseUrl)}catch(i){let t=this.assignAssetListError(e,g.ASSET_LIST_LOAD_ERROR,i,r);this.hls.trigger(m.ERROR,t);return}t&&"data:"!==i.protocol&&tp(i,"_HLS_start_offset",""+t);let s=this.hls.config,a=new s.loader(s),n={type:M.INTERSTITIAL_ASSET_LIST,responseType:"json",url:i.href},l=s.interstitialAssetListLoadPolicy.default,o={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return a.load(n,o,{onSuccess:(t,i,r,s)=>{let a=t.data;if(!Array.isArray(null==a?void 0:a.ASSETS)){let t=this.assignAssetListError(e,g.ASSET_LIST_PARSING_ERROR,Error("Invalid interstitial asset list"),r.url,i,s);this.hls.trigger(m.ERROR,t);return}e.assetListResponse=a,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:s})},onError:(t,i,r,s)=>{let a=this.assignAssetListError(e,g.ASSET_LIST_LOAD_ERROR,Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${i.url})`),i.url,s,r);this.hls.trigger(m.ERROR,a)},onTimeout:(t,i,r)=>{let s=this.assignAssetListError(e,g.ASSET_LIST_LOAD_TIMEOUT,Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,t,r);this.hls.trigger(m.ERROR,s)}}),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,i,r,s,a){return e.error=i,{type:c.NETWORK_E
28RROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:a,stats:s}}}function nM(e){var t;null==e||null==(t=e.play())||t.catch(()=>{})}function nw(e,t){return`[${e}] Advancing timeline position to ${t}`}class nF extends er{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{var e,t;let i=this.currentTime;if(void 0===i||this.playbackDisabled||!this.schedule)return;let r=i-this.timelinePos;if(Math.abs(r)<1/7056e5)return;let s=r<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=i,this.bufferedPos=i;let a=this.playingItem;if(!a){this.checkBuffer();return}if(s&&this.schedule.resetErrorsInRange(i,i-r)&&this.updateSchedule(!0),this.checkBuffer(),s&&i<a.start||i>=a.end){let t=this.findItemIndex(a),r=this.schedule.findItemIndexAtTime(i);if(-1===r&&(r=t+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${i} (resolving from ${t} to ${r})`)),!this.isInterstitial(a)&&null!=(e=this.media)&&e.paused&&(this.shouldPlay=!1),!s&&r>t){let e=this.schedule.findJumpRestrictedIndex(t+1,r);if(e>t){this.setSchedulePosition(e);return}}this.setSchedulePosition(r);return}let n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(a)){let e=a.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,e))}return}let l=n.timelineStart,o=n.duration||0;(s&&i<l||i>=l+o)&&(null!=(t=a.event)&&t.appendInPlace&&(this.clearAssetPlayers(a.event,a),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,n))},this.onTimeupdate=()=>{let e=this.currentTime;if(void 0===e||this.playbackDisabled||(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(e>this.timelinePos)))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();let t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}let i=this.playingAsset;i&&e>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(e,i)},this.onScheduleUpdate=(e,t)=>{let i=this.schedule;if(!i)return;let r=this.playingItem,s=i.events||[],a=i.items||[],n=i.durations,l=e.map(e=>e.identifier),o=!!(s.length||l.length);(o||t)&&this.log(`INTERSTITIALS_UPDATED (${s.length}): ${s} 29Schedule: ${a.map(e=>nC(e))} pos: ${this.timelinePos}`),l.length&&this.log(`Removed events ${l}`);let h=null,d=null;r&&(h=this.updateItem(r,this.timelinePos),this.itemsMatch(r,h)?this.playingItem=h:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);let u=this.bufferingItem;if(u&&(d=this.updateItem(u,this.bufferedPos),this.itemsMatch(u,d)?this.bufferingItem=d:u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){let t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(r){Math.abs(i)>.025&&this.warn(`${r} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),o||t){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:s.slice(0),schedule:a.slice(0),durations:n,removedIds:l}),this.isInterstitial(r)&&l.indexOf(r.event.identifier)>-1){this.warn(`Interstitial "${r.event.identifier}" removed while playing`),this.primaryFallback(r.event);return}r&&this.trimInPlace(h,r),u&&d!==h&&this.trimInPlace(d,u),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new nO(e),this.schedule=new n_(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;
29e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(m.MEDIA_ENDED,this.onMediaEnded,this),e.on(m.ERROR,this.onError,this),e.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(m.MEDIA_ENDED,this.onMediaEnded,this),e.off(m.ERROR,this.onError,this),e.off(m.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){re(e,"play",this.onPlay),re(e,"pause",this.onPause),re(e,"seeking",this.onSeeking),re(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let i=this.media=t.media;i7(i,"seeking",this.onSeeking),i7(i,"timeupdate",this.onTimeupdate),i7(i,"play",this.onPlay),i7(i,"pause",this.onPause)}onMediaAttached(e,t){let i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();let e=this.findItemIndex(i);this.setSchedulePosition(e)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){let e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,i=t=>t?e.getAssetPlayer(t.identifier):t,r=(t,r,s,n,l)=>{if(t){let o=t[r].start,h=t.event;if(h){if("playout"===r||h.timelineOccupancy!==nI.Point){let e=i(s);(null==e?void 0:e.interstitial)===h&&(o+=e.assetItem.startOffset+e[l])}}else o+=("bufferedPos"===n?a():e[n])-t.start;return o}return 0},s=(t,i)=>{var r,s;if(0!==t&&"primary"!==i&&null!=(r=e.schedule)&&r.length){let r=e.schedule.findItemIndexAtTime(t),a=null==(s=e.schedule.items)?void 0:s[r];if(a)return t+(a[i].start-a.start)}return t},a=()=>{let t=e.bufferedPos;return t===Number.MAX_VALUE?n("primary"):Math.max(t,0)},n=t=>{var i,r;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:(null==(r=e.schedule)?void 0:r.durations[t])||0},l=(t,s)=>{var a,n;let l=e.effectivePlayingItem;if(null!=l&&null!=(a=l.event)&&a.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${s}"`);let o=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(t,s),d=null==(n=e.schedule.items)?void 0:n[h],u=e.getBuffer
29ingPlayer(),f=null==u?void 0:u.interstitial,c=null==f?void 0:f.appendInPlace,g=o&&e.itemsMatch(o,d);if(o&&(c||g)){let a=i(e.playingAsset),n=(null==a?void 0:a.media)||e.primaryMedia;if(n){let i="primary"===s?n.currentTime:r(o,s,e.playingAsset,"timelinePos","currentTime"),l=t-i,h=(c?i:n.currentTime)+l;if(h>=0&&(!a||c||h<=a.duration)){n.currentTime=h;return}}}if(d){let i=t;if("primary"!==s){let e=t-d[s].start;i=d.start+e}let r=!e.isInterstitial(d);if((!e.isInterstitial(o)||o.event.appendInPlace)&&(r||d.event.appendInPlace)){let t=e.media||(c?null==u?void 0:u.media:null);t&&(t.currentTime=i)}else if(o){let a=e.findItemIndex(o);if(h>a){let t=e.schedule.findJumpRestrictedIndex(a+1,h);if(t>a){e.setSchedulePosition(t);return}}let n=0;if(r)e.timelinePos=i,e.checkBuffer();else{let e=d.event.assetList,i=t-(d[s]||d).start;for(let t=e.length;t--;){let r=e[t];if(r.duration&&i>=r.startOffset&&i<r.startOffset+r.duration){n=t;break}}}e.setSchedulePosition(h,n)}}},o=()=>{let i=e.effectivePlayingItem;if(e.isInterstitial(i))return i;let r=t();return e.isInterstitial(r)?r:null},h={get bufferedEnd(){let i=t(),s=e.bufferingItem;if(s&&s===i){var d;return r(s,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-s.playout.start||(null==(d=e.bufferingAsset)?void 0:d.startOffset)||0}return 0},get currentTime(){let t=o(),i=e.effectivePlayingItem;if(i&&i===t)return r(i,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start;return 0},set currentTime(time){let t=o(),i=e.effectivePlayingItem;i&&i===t&&l(time+i.playout.start,"playout")},get duration(){let e=o();if(e)return e.playout.end-e.playout.start;return 0},get assetPlayers(){var u;let t=null==(u=o())?void 0:u.event.assetList;if(t)return t.map(t=>e.getAssetPlayer(t.identifier));return[]},get playingIndex(){var f;let t=null==(f=o())?void 0:f.event;if(t&&e.effectivePlayingAsset)return t.findAssetIndex(e.effectivePlayingAsset);return -1},get scheduleItem(){return o()}};return this.manager={get events(){var c;return(null==(c=e.schedule)||null==(c=c.events)?void 0:c.slice(0))||[]},get schedule(){var g;return(null==(g=e.schedule)||null==(g=g.items)?void 0:g.slice(0))||[]},get interstitialPlayer(){if(o())return h;return null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let i=t();return e.findItemIndex(i)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return a()},get currentTime(){let t=e.timelinePos;return t>0?t:0},set currentTime(time){l(time,"primary")},get duration(){return n("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return r(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return r(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(time){l(time,"integrated")},get duration(){return n("integrated")},get seekableStart(){return s(e.seekableStart,"integrated")}},skip:()=>{let t=e.effectivePlayingItem,i=null==t?void 0:t.event;if(i&&!i.restrictions.skip){let r=e.findItemIndex(t);i.appendInPlace?l(t.playout.start+t.event.duration+.001,"playout"):e.advanceAfterAssetEnded(i,r,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!this.playbackStarted&&!!t&&!!i&&this.findItemIndex(t)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;let i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let r=this.media;!r&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(r=this.primaryMedia);let s=null==(t=r)?void 0:t.currentTime;if(void 0!==s&&d(s))return s}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!!(null!=e&&e.event)}retreiveMediaSource(e,t){let i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){let i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${tR(i)}`),this.detachedData=i}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var i,r;let s;if(e.media===t)return;let a=null,n=this.hls,l=e!==n,o=l&&e.interstitial.appendInPlace,h=null==(i=this.detachedData)?void 0:i.mediaSource;if(n.media)o&&(a=n.transferMedia(),this.detachedData=a),s="Primary";
29else{let e=this.getBufferingPlayer();e?(a=e.transferMedia(),this.detachedData=a,s=`${e}`):s=h?"detached MediaSource":"detached media"}if(!a){if(h)a=this.detachedData,this.log(`using detachedData: MediaSource ${tR(a)}`);else if(!this.detachedData||n.media===t){let e=this.playerQueue;e.length>1&&e.forEach(e=>{if(l&&e.interstitial.appendInPlace!==o){let t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let d=a&&"mediaSource"in a&&(null==(r=a.mediaSource)?void 0:r.readyState)!=="closed";if(this.log(`${d?"transfering MediaSource":"attaching media"} to ${l?e:"Primary"} from ${s} (media.currentTime: ${t.currentTime})`),!d&&!l){e.attachMedia(t);return}let u=d&&a?a:{media:t},f=this.schedule;if(f){let t=l&&e.assetId===f.assetIdAtEnd;u.overrides={duration:f.duration,endOfStream:!l||t||!1===e.appendInPlace}}if(!d&&o){let t=e.assetItem.timelineStart;if(t){let i=e.hls,r=Math.max(this.timelinePos-t,Number.EPSILON);i.startPosition!==r&&(this.log(`Set ${e} startPosition: ${r}`),i.config.startPosition=r,i.loadingEnabled&&i.startLoad(r))}}e.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=null==e?void 0:e.events,i=this.hls;if(!t||this.playbackDisabled||!this.media||!i)return;-1===this.bufferedPos&&(this.bufferedPos=0);let r=this.timelinePos,s=this.effectivePlayingItem;if(-1===r){if(!i.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}let r=i.startPosition;if(this.timelinePos=r,0===t.length)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(nw("checkStart (preroll)",r));let i=e.findEventIndex(t[0].identifier);this.setSchedulePosition(i)}else if(r>=0||!this.primaryLive){this.log(nw("checkStart",r));let t=this.timelinePos=r>0?r:0,i=e.findItemIndexAtTime(t);this.setSchedulePosition(i)}else 0===i.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(s&&!this.playingItem){this.log(nw("checkStart (playing item)",s.start));let t=e.findItemIndex(s);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){let i=e.event,r=i.findAssetIndex(t),s=nD(i,r);if(i.isAssetPastPlayoutLimit(s)){if(this.schedule){var a;let t=this.getNextItemIndex(e,!0),i=null==(a=this.schedule.items)?void 0:a[t];i&&this.bufferedToItem(i)}}else this.bufferedToEvent(e,s)}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!d(e.resumeOffset)&&this.hls){let e=this.getLiveStartPos();if(t){let t=this.getBufferingPlayer();return e+(null!=t&&t.interstitial.cue.pre?t.remaining:0)}return e}}getNextItemIndex(e,t){if(this.schedule){let i=this.livePrerollResumption(e.event,t);if(void 0!==i)return this.log(`find next item index @${i}`),this.schedule.findItemIndexAtTime(i)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,i){let r=nD(e,i);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){let i=this.schedule.items;if(i){let r=i[t],s=r.event?this.getNextItemIndex(r):t+1;if(s>=i.length){this.setSchedulePosition(-1);return}let a=e.resumeTime;this.timelinePos<a&&(this.log(nw("advanceAfterAssetEnded",a)),this.timelinePos=a,e.appendInPlace&&!i[s].event&&this.hls.startLoad(a+.01),this.checkBuffer(this.bufferedPos<a)),this.setSchedulePosition(s)}}}else{if(e.appendInPlace){let t=e.assetList[r];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,r)}}setScheduleToAssetAtTime(e,t){let i=this.schedule;if(!i)return;let r=t.parentIdentifier,s=i.getEvent(r);if(s){let t=i.findEventIndex(r),a=i.findAssetIndex(s,e);this.advanceAfterAssetEnded(s,t,a-1)}}setSchedulePosition(e,t){var i,r,s,a;let n=null==(i=this.schedule)?void 0:i.items;if(!n||this.playbackDisabled)return;let l=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${l?nC(l):l}) pos: ${this.timelinePos}`);let o=this.waitingItem||this.playingItem,h=this.playingLastItem;if(this.isInterstitial(o)){let i=o.event,d=this.playingAsset,u=null==d?void 0:d.identifier,f=u?this.getAssetPlayer(u):null;if(f&&u&&(!this.eventItemsMatch(o,l)||void 0!==t&&u!==i.assetList[t].identifier)){let t=i.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${i.assetList.length} ${nk(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:t,event:i,schedule:n.slice(0),scheduleIndex:e,player:f}),o!==this.playingItem){this.itemsMatch(o,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),t);return}this.retreiveMediaSource(u,l),f.media&&!(null!=(r=this.detachedData)&&r.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(o,l)&&(this.endedItem=o,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${nC(o)}`),i.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:i,schedule:n.slice(0),scheduleIndex:e}),i.cue.once&&this.hls)){this.updateSchedule();let e=null==(s=this.schedule)?void 0:s.items;if(l&&e){let r=this.findItemIndex(l),s=this.livePrerollResumption(i);if(void 0!==s){let t=s,l=this.getNextItemIndex(o);if(!this.isInterstitial(n[l])){let e=null==(a=this.primaryDetails)?void 0:a.fragments;if(i.snapOptions.in&&e){let i=t$(null,e,s);i&&(t=Math.min(Math.max(n[l].start,nR(t,i)),n[l].end))}}if(this.log(nw("live join (preroll)",t)),this.timelinePos=t,l!==r&&(l||0===l)){this.advanceSchedule(l,e,void 0,o,h);return}}this.advanceSchedule(r,e,t,o,h)}return}}this.advanceSchedule(e,n,t,o,h)}advanceSchedule(e,t,i,r,s){let a=this.schedule;if(!a)return;let n=t[e]||null,l=this.primaryMedia,o=this.playerQueue;if(o.length&&o.forEach(t=>{let i=t.interstitial,r=a.findEventIndex(i.identifier);(r<e||r>e+1)&&this.clearInterstitial(i,n)}),this.isInterstitial(n)){this.timelinePos=Math.min(Math.max(this.timelinePos,n.start),n.end);let s=n.event;
29if(void 0===i){i=s.cue.pre?0:a.findAssetIndex(s,this.timelinePos);let t=nD(s,i-1);if(s.isAssetPastPlayoutLimit(t)||s.appendInPlace&&this.timelinePos===n.end){this.advanceAfterAssetEnded(s,e,i);return}i=t}let o=this.waitingItem;this.assetsBuffered(n,l)||this.setBufferingItem(n);let h=this.preloadAssets(s,i);if(this.eventItemsMatch(n,o||r)||(this.waitingItem=n,this.log(`INTERSTITIAL_STARTED ${nC(n)} ${s.appendInPlace?"append in place":""}`),s.hasPlayed=!1,this.hls.trigger(m.INTERSTITIAL_STARTED,{event:s,schedule:t.slice(0),scheduleIndex:e})),!s.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${s}`);return}if(s.assetListLoader&&(s.assetListLoader.destroy(),s.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${s}`);return}this.waitingItem=this.endedItem=null,this.playingItem=n;let d=s.assetList[i];if(!d){this.advanceAfterAssetEnded(s,e,i||0);return}if(h||(h=this.getAssetPlayer(d.identifier)),null===h||h.destroyed){let e=s.assetList.length;this.warn(`asset ${i+1}/${e} player destroyed ${s}`),(h=this.createAssetPlayer(s,d,i)).loadSource()}if(!this.eventItemsMatch(n,this.bufferingItem)&&s.appendInPlace&&this.isAssetBuffered(d))return;this.startAssetPlayer(h,i,t,e,l),this.shouldPlay&&nM(h.media)}else n?(this.resumePrimary(n,e,r),this.shouldPlay&&nM(this.hls.media)):s&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!!(null!=(e=this.primaryDetails)&&e.live)}resumePrimary(e,t,i){var r,s;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${nC(e)}`);let a=this.timelinePos;if(null!=(r=this.detachedData)&&r.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(nw("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),!i)return;let n=null==(s=this.schedule)?void 0:s.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${nC(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){var e;return this.primaryLive&&(null==(e=this.primaryDetails)?void 0:e.fragmentStart)||0}getPrimaryResumption(e,t,i){let r=e.start;if(this.primaryLive){if(0===t)return this.hls.startPosition;let e=this.endedItem||this.playingItem,s=null!=e&&e.event?this.livePrerollResumption(e.event,i):void 0;if(void 0!==s)return s;let a=this.primaryDetails;if(a){let{fragmentStart:e,edge:t}=a;if(r<e||r>t&&!i){let i=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${r} [${e}-${t}]) snapping to liveSync ${i}`),i||e}}}return this.log(`primary resumption itemStart: ${r}`),r}getLiveStartPos(){var e;let t=this.hls.startPosition,i=this.hls.liveSyncPosition||0,r=3*((null==(e=this.primaryDetails)?void 0:e.targetduration)||10);return -1===t||i&&i-t<r?i||0:t}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:ir.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(nw("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){let i=this.hls,{loadingEnabled:r,bufferingEnabled:s,startPosition:a}=i,n=!t&&i.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} instructToSeek: ${n} startPosition: ${a} loadingEnabled: ${r} bufferingEnabled: ${s}`),n||!r||Math.abs(a-e)>.1){let r=this.primaryDetails;if(null!=r&&r.live&&e>=r.edge){let t=this.bufferingItem;this.log(`Resume primary loading when live reaches ${e} buffering item: ${t?nC(t):null}
29`),i.pauseBuffering(),this.bufferPastEdge=!0;return}i.startLoad(e,t)}else s||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(m.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(m.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;let i=this.hls.levels[t.level];if(!i.details)return;let r=H(H({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r;let s=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace,-1===s?0:s),this.schedule.items){if(this.effectivePlayingItem){if(this.bufferPastEdge){let e=this.primaryDetails,t=this.bufferedPos;if(null!=e&&e.live&&t<e.edge){this.bufferPastEdge=!1;let i=this.bufferingItem;if(this.log(`Live edge ${e.edge} reached buffer: ${t} buffering item: ${i?nC(i):null}`),(null==i?void 0:i.end)===1/0)this.startLoadingPrimaryAt(Math.max(t,i.start));else{let e=this.getBufferingPlayer();e&&e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)&&e.hls&&e.hls.trigger(m.BUFFERED_TO_END,void 0)}}}}else this.checkStart()}}onAudioTrackUpdated(e,t){let i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=H(H({},this.altSelection),{},{audio:i});return}let s=H(H({},r),{},{audio:i});this.mediaSelection=s}onSubtitleTrackUpdated(e,t){let i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=H(H({},this.altSelection),{},{subtitles:i});return}let s=H(H({},r),{},{subtitles:i});this.mediaSelection=s}onAudioTrackSwitching(e,t){let i=tk(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){let i=tk(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.setSubtitleOption(i)))}onBufferCodecs(e,t){let i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){let i=t[e];if(i.cue.post){let e=this.getEventItem(i.identifier);e&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var i;let r=null==(i=this.schedule)?void 0:i.items;return e&&r&&r[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,i)=>{e.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(t.identifier,null)});let i=e.end+.25,r=ir.bufferInfo(this.primaryMedia,i,0);(r.end>i||(r.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${nC(e)} (was ${nC(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;let i=null==(t=this.schedule.items)?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(i)&&i.event.identifier===e)return i}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,i;let r=this.mediaSelection;if(!r)return;let s=(null==(t=this.hls)?void 0:t.liveSyncPosition)||0;null==(i=this.schedule)||i.updateSchedule(r,[],s,e)}checkBuffer(e){var t;let i=null==(t=this.schedule)?void 0:t.items;if(!i)return;let r=ir.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,i,e)}updateBufferedPos(e,t,i){let r=this.schedule,s=this.bufferingItem;if(this.bufferedPos>e||!r)return;
29if(1===t.length&&this.itemsMatch(t[0],s)){this.bufferedPos=e;return}let a=this.playingItem,n=this.findItemIndex(a),l=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var o;let i=this.findItemIndex(s),r=Math.min(i+1,t.length-1),a=t[r];if((-1===l&&s&&e>=s.end||null!=(o=a.event)&&o.appendInPlace&&e+.01>=a.start)&&(l=r),this.isInterstitial(s)){let e=s.event;if(r-n>1&&!1===e.appendInPlace||0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,l>i&&l>n)this.bufferedToItem(a);else{let t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&a.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(a)&&this.preloadAssets(a.event,0)}}else i&&a&&!this.itemsMatch(a,s)&&(l===n?this.bufferedToItem(a):l===n+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some(e=>{let i=this.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){let{items:r,events:s}=i;if(!r||!s)return t;let a=this.isInterstitial(e),n=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=n?n.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${nC(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled){if(a){let t=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,i)=>{let r=this.getAssetPlayer(e.identifier);r&&(i===t&&r.loadSource(),r.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering())}this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;let t=this.getPrimaryResumption(e,this.findItemIndex(e),!0),i=this.bufferedPos=Math.max(t,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),r=this.detachedData;r&&r.mediaSource?this.attachPrimary(i,e,!0):this.startLoadingPrimaryAt(i)}}}bufferedToEvent(e,t){let i=e.event,r=0===i.assetList.length&&!i.assetListLoader,s=i.cue.once;if(r||!s){let e=this.preloadAssets(i,t);if(null!=e&&e.interstitial.appendInPlace){let t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){let i=e.assetUrl,r=e.assetList.length,s=0===r&&!e.assetListLoader,a=e.cue.once;if(s){let s;let a=e.timelineStart,l=this.playingItem,o=this.getBufferingPlayer();if(e.appendInPlace){var n;this.isInterstitial(l)||(null==l||null==(n=l.nextEvent)?void 0:n.identifier)!==e.identifier||this.flushFrontBuffer(a+.25)}let h=0;if((!o||o.interstitial.cue.pre)&&this.primaryLive&&(h=this.getLiveStartPos(),o&&(h+=o.remaining)),h&&!(e.cue.pre||e.cue.post)){let e=h-a;e>0&&(s=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:r} ${e}${h?` live-start: ${h} start-offset: ${s} (timeline-start: ${a})`:""}`),i)return this.createAsset(e,0,0,a,e.duration,i);let d=this.assetListLoader.loadAssetList(e,s);d&&(e.assetListLoader=d)}else if(!a&&r){for(let i=t;i<r;i++){let t=e.assetList[i],r=this.getAssetPlayerQueueIndex(t.identifier);(-1===r||this.playerQueue[r].destroyed)&&!t.error&&this.createAssetPlayer(e,t,i)}let i=e.assetList[t];if(i){let e=this.getAssetPlayer(i.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;let i=this.primaryDetails;i&&e>=i.edge||(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(t=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return -1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,r,s,a){let n={parentIdentifier:e.identifier,identifier:`${e.identifier}-${t+1}-${aQ(a)}`,duration:s,startOffset:i,timelineStart:r,uri:a};return this.createAssetPlayer(e,n,t)}createAssetPlayer(e,t,i){let r=this.hls,s=r.userConfig,a=tF(r.loadLevelObj||r.levels[r.currentLevel],s.videoPreference),n=r.audioTracks[r.audioTrack],l=r.subtitleTracks[r.subtitleTrack],o=0;if(this.primaryLive||e.appendInPlace){let e=this.timelinePos-t.timelineStart;if(e>=0){let i=t.duration;i&&e<i&&(o=e)}}let h=t.identifier,d=H(H({},s),{}
29,{maxMaxBufferLength:Math.min(15,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:o,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:n||s.audioPreference,subtitlePreference:l||s.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));let u=d.cmcd;null!=u&&u.sessionId&&u.contentId&&(d.cmcd=K({},u,{contentId:aQ(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);let f=new nP(this.HlsPlayerClass,d,e,t);this.playerQueue.push(f),e.assetList[i]=t;let p=!0,E=r=>{if(r.live){let t=Error(`Interstitials MUST be VOD assets ${e}`),r={fatal:!0,type:c.OTHER_ERROR,details:g.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},s=this.findEventIndex(e.identifier);this.handleAssetItemError(r,e,s,i,t.message);return}let s=r.edge-r.fragmentStart,a=t.duration;(p||null===a||s>a)&&(p=!1,this.log(`Interstitial asset "${h}" duration change ${a} > ${s}`),t.duration=s,this.updateSchedule())};f.on(m.LEVEL_UPDATED,(e,{details:t})=>E(t)),f.on(m.LEVEL_PTS_UPDATED,(e,{details:t})=>E(t)),f.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let v=(e,t)=>{let i=this.getAssetPlayer(h);if(i&&t.tracks){i.off(m.BUFFER_CODECS,v),i.tracks=t.tracks;let e=this.primaryMedia;this.bufferingAsset===i.assetItem&&e&&!i.media&&this.bufferAssetPlayer(i,e)}};f.on(m.BUFFER_CODECS,v),f.on(m.BUFFERED_TO_END,()=>{let t=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${t}`),!t||!this.schedule)return;let i=this.getEventItem(e.identifier);i&&this.advanceAssetBuffering(i,t.assetItem)});let y=t=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;let i=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,t)};return f.once(m.MEDIA_ENDED,y(i)),f.once(m.PLAYOUT_LIMIT_REACHED,y(1/0)),f.on(m.ERROR,(t,r)=>{if(!this.schedule)return;let s=this.getAssetPlayer(h);if(r.details===g.BUFFER_STALLED_ERROR){if(null!=s&&s.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}r.details!==g.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(r,e,this.findEventIndex(e.identifier),i,`Asset player error ${r.error} ${e}`)}),f.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;let t=Error(`Asset player destroyed unexpectedly ${h}`),r={fatal:!0,type:c.OTHER_ERROR,details:g.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(r,e,this.findEventIndex(e.identifier),i,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${nk(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log(`reset asset player "${e}" after error`);let i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){let i=this.getAssetPlayerQueueIndex(e);if(-1!==i){let e=this.playerQueue[i];this.log(`clear ${e} toSegment: ${t?nC(t):t}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(i,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,i,r,s){let{interstitial:a,assetItem:n,assetId:l}=e,o=a.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=n,(null==h?void 0:h.identifier)!==l&&(h&&(this.clearAssetPlayer(h.identifier,i[r]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${o} ${nk(n)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:n,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,s)}bufferAssetPlayer(e,t){var i;if(!this.schedule)return;let{interstitial:r,assetItem:s}=e,a=this.getEventItem(r.identifier);if(!a)return;if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=s,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(a,s);return}
29let n=this.getBufferingPlayer();if(n===e)return;let l=r.appendInPlace;if(l&&(null==n?void 0:n.interstitial.appendInPlace)===!1)return;let o=(null==n?void 0:n.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(l&&s!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(o&&!ed(o,e.tracks)){let t=Error(`Asset ${nk(s)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(o)}')`),i={fatal:!0,type:c.OTHER_ERROR,details:g.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},a=r.findAssetIndex(s);this.handleAssetItemError(i,r,this.findEventIndex(r.identifier),a,t.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,i=this.primaryMedia;if(!t||!i)return;let r=i.currentTime,s=t.findAssetIndex(e,r),a=e.assetList[s];if(a){let n=this.getAssetPlayer(a.identifier);if(n){let l=n.currentTime||r-a.timelineStart,o=n.duration-l;if(this.warn(`Stalled at ${l} of ${l+o} in ${n} ${e} (media.currentTime: ${r})`),l&&(o/i.playbackRate<.5||n.bufferedInPlaceToEnd(i,n.currentTime))&&n.hls){let i=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,s)}}}}advanceInPlace(e){let t=this.primaryMedia;if(t&&t.currentTime<e){let i=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(i),t.currentTime=e):this.log(`Cannot ${i}`)}}handleAssetItemError(e,t,i,r,s){if(e.details===g.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a?nk(a):a} ${e.error}`),!this.schedule)return;let n=(null==a?void 0:a.identifier)||"",l=this.getAssetPlayerQueueIndex(n),o=this.playerQueue[l]||null,h=this.schedule.items,d=K({},e,{fatal:!1,errorAction:tj(!0),asset:a,assetListIndex:r,event:t,schedule:h,scheduleIndex:i,player:o});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;let u=this.playingAsset,f=this.bufferingAsset,c=Error(s);if(a&&(this.clearAssetPlayer(n,null),a.error=c),t.assetList.some(e=>!e.error))for(let e=r;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);else t.error=c;this.updateSchedule(!0),t.error?this.primaryFallback(t):(null==u?void 0:u.identifier)===n?this.advanceAfterAssetEnded(t,i,r):(null==f?void 0:f.identifier)===n&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,i=this.effectivePlayingItem,r=this.playingItem,s=this.seekableStart,a=this.hls.startPosition,n=this.timelinePos;if(this.isInterstitial(i)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${n} playing: ${nC(i)} startPosition: ${a} seekableStart: ${s} error: ${e.error}`),-1===n&&(n=a),n=Math.max(n,s);let r=this.updateItem(i,n);this.itemsMatch(i,r)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===n){this.checkStart();return}if(!this.schedule||!this.isInterstitial(r))return;let l=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(l)}onAssetListLoaded(e,t){var i,r;let s=t.event,a=s.identifier,n=t.assetListResponse.ASSETS;if(!(null!=(i=this.schedule)&&i.hasEvent(a)))return;let l=s.timelineStart,o=s.duration,h=0;n.forEach((e,t)=>{let i=parseFloat(e.DURATION);this.createAsset(s,t,h,l+h,i,e.URI),h+=i}),s.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${o}) ${s}`);let d=this.waitingItem,u=(null==d?void 0:d.event.identifier)===a;this.updateSchedule();let f=null==(r=this.bufferingItem)?void 0:r.event;if(u){let e=this.findEventIndex(a),t=this.getEventItem(a);if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e){s.error=Error(`Interstitial ${n.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${s}`),this.log(s.error.message),this.updateSchedule(!0),this.primaryFallback(s);return}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if((null==f?void 0:f.identifier)===a){let e=s.assetList[0];if(e){let t=this.getAssetPlayer(e.identifier);if(f.appendInPlace){let e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case g.ASSET_LIST_PARSING_ERROR:case g.ASSET_LIST_LOAD_ERROR:case g.ASSET_LIST_LOAD_TIMEOUT:{let e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case g.BUFFER_STALLED_ERROR:{let e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace){this.handleInPlaceStall(e.event);return}let t=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${null==t?void 0:t.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0)}}}}class nx{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{let{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;let i=this.computeLatency();if(null===i)return;this._latency=i;let{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s||!t.live)return;let a=this.targetLatency;if(null===a)return;let n=i-a;if(n<Math.min(this.maxLatency,a+t.targetduration)&&n>.05&&this.forwardBufferLength>1){let t=Math.round(2/(1+Math.exp(-.75*n-this.edgeStalled))*20)/20;this.changeMediaPlaybackRate(e,Math.min(Math.min(2,Math.max(1,s)),Math.max(1,t)))}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(null===e||null===this.hls)return null;let{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:s,liveSyncDurationCount:a,lowLatencyMode:n}=this.config,l=this.hls.userConfig,o=n&&i||t;return(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===o)&&(o=void 0!==s?s:a*r),o+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,r)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;let i=this.levelDetails;if(null===i)return null;let r=i.edge,s=e-t-this.edgeStalled;return Math.min(Math.max(r-i.totalduration,s),r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration))}get drift(){let e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(null===e)return 0;let t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;
29e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===g.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,r;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(r=this.targetLatency)?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class nN extends rr{constructor(e,t,i){super(e,t,i,"subtitle-stream-controller",w.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=ri.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let i;let{frag:r,part:s,success:a}=t;if(!a)return;let n=this.tracksBuffered[this.currentTrackId];if(!n)return;let l=(s||r).start;for(let e=0;e<n.length;e++)if(l>=n[e].start&&l<=n[e].end){i=n[e];break}let o=l+(s||r).duration;if(i?i.end=o:(i={start:l,end:o},n.push(i)),!s||o>=r.end){let e=this.fragmentTracker.fragBuffered(r);s&&e&&(e.range.subs={time:[{startPTS:r.start,endPTS:o}],partial:!0}),N(r)&&!this.fragContextChanged(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,s),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){let{startOffset:i,endOffset:r}=t;if(0===i&&r!==Number.POSITIVE_INFINITY){let e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{if(t)for(let i=0;i<t.length;){if(t[i].end<=e){t.shift();continue}if(t[i].start<e)t[i].start=e;else break;i++}}),this.fragmentTracker.removeFragmentsInRange(i,e,w.SUBTITLE)}}onError(e,t){let i=t.frag;(null==i?void 0:i.type)===w.SUBTITLE&&(t.details===g.FRAG_GAP&&this.fragmentTracker.addAsGap(i),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ri.STOPPED&&(this.state=ri.IDLE))}
29onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&sE(this.levels,t)){this.levels=t.map(e=>new tA(e));return}this.tracksBuffered=[],this.levels=t.map(e=>{let t=new tA(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,w.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!(null!=(i=this.levels)&&i.length)||-1===this.currentTrackId){this.clearInterval();return}let r=this.levels[this.currentTrackId];if(!(null!=r&&r.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==ri.STOPPED&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i,r;let{currentTrackId:s,levels:a}=this,{details:n,id:l}=t;if(!a){this.warn(`Subtitle tracks were reset while loading level ${l}`);return}let o=a[l];if(l>=a.length||!o)return;this.log(`Subtitle track ${l} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let h=this.mainDetails,d=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;if(!h){this.startFragRequested=!1;return}o.details&&(d=this.alignPlaylists(n,o.details,null==(r=this.levelLastLoaded)?void 0:r.details)),n.alignedSliding||(i9(h,n,this),d=n.fragmentStart)}o.details=n,this.levelLastLoaded=o,h&&!this.startFragRequested&&this.setStartPosition(h,d),l===s&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:n,id:l,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){let{frag:t,part:i,payload:r}=e;i&&null!=r&&r.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(r,t,i)}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e;!this.fragContextChanged(t)&&null!=i&&i.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(i,t,null)}shouldDecrypt(e){let t=e.decryptdata;return!!(null!=t&&t.key&&t.iv&&ip(t.method))}decryptPayload(e,t,i){let r=t.decryptdata,s=performance.now();this.decrypter.decrypt(new Uint8Array(e),r.key.buffer,r.iv.buffer,iE(r.method)).then(e=>{this.fragContextChanged(t)||this.hls.trigger(m.FRAG_DECRYPTED,{frag:t,part:i,payload:e,stats:{tstart:s,tdecrypt:performance.now()}})}).catch(e=>{this.hls.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t,part:i}),i||(this.warn(`${e.name}: ${e.message}`),this.state=ri.IDLE)})}doTick(){if(this.state===ri.IDLE&&this.levels){var e,t;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;let{currentTrackId:i,levels:r}=this,s=r[i],a=null==s?void 0:s.details;if(!a||this.waitForLive(s)||this.waitForCdnTuneIn(a)){this.startFragRequested=!1;return}let{config:n}=this,l=this.playhead,{end:o,len:h}=ir.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],l,n.maxBufferHole);if(h>Math.max(this.hls.maxBufferLength+a.levelTargetDuration,(null==(e=this.hls.mainForwardBufferInfo)?void 0:e.len)||0)||h&&!this.buffering)return;let d=this.getNextFragment(o,a);if(d){if(N(d)){let e=d.sn-a.startSN,i=a.fragments[e-1];d.cc!==(null==i?void 0:i.cc)||null!=(t=a.partList)&&t.length||this.fragmentTracker.getState(i)!==tq.NOT_LOADED||(d=i)}this.loadFragment(d,s,o)}}}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);(r===tq.NOT_LOADED||r===tq.PARTIAL)&&super.loadFragment(e,t,i)}get mediaBufferTimeRanges(){return new n$(this.tracksBuffered[this.currentTrackId]||[])}}class n${constructor(e){this.buffered=void 0;let t=(t,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}let nU={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,
29185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},nB=e=>String.fromCharCode(nU[e]||e),nG={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},nK={17:2,18:4,21:6,22:8,23:10,19:13,20:15},nV={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},nH={25:2,26:4,29:6,30:8,31:10,27:13,28:15},nY=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class nW{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let i="function"==typeof t?t():t;eo.log(`${this.time} [${e}] ${i}`)}}}let nj=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t},nq=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class nX{constructor(){this.styles=nq}get foreground(){return this.styles.foreground}set foreground(e){let t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){let t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=nq}setStyles(e){let t=this.styles,i=Object.prototype.hasOwnProperty;this.styles={foreground:i.call(e,"foreground")?e.foreground:t.foreground,underline:i.call(e,"underline")?e.underline:t.underline,italics:i.call(e,"italics")?e.italics:t.italics,background:i.call(e,"background")?e.background:t.background,flash:i.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class nz{constructor(){this.uchar=" ",this.penState=new nX}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}}class nQ{constructor(e){this.chars=[],this.pos=0,this.currPenState=new nX,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<42;e++)this.chars.push(new nz);this.logger=e}equals(e){let t=this.chars,i=e.chars;for(let e=0;e<42;e++){let r=t[e],s=i[e];if(r.uchar!==s.uchar)return!1;let a=r.penState.styles,n=s.penState.styles;if(a!==n&&(a.foreground!==n.foreground||a.underline!==n.underline||a.italics!==n.italics||a.background!==n.background||a.flash!==n.flash))return!1}return!0}copy(e){for(let t=0;t<42;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=this.chars;for(let t=0;t<42;t++){let i=e[t];if(" "!==i.uchar)return!1;let r=i.penState.styles;if(r!==nq&&("white"!==r.foreground||r.underline||r.italics||"black"!==r.background||r.flash))return!1}return!0}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=42&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}moveCursor(e){let t=Math.min(this.pos+e,42);if(e>1)for(let e=this.pos+1;e<t;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=nB(e);if(this.pos>=42){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<42;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let i=0;i<42;i++){let r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class nZ{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<15;t++)this.rows.push(new nQ(e));this.logger=e}reset(){for(let e=0;e<15;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let i=0;i<15;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<15;t++){let i=this.rows[t].chars,r=e.rows[t].chars;for(let e=0;e<42;e++){let t=i[e],s=r[e];t.uchar=s.uchar,t.penState.styles=s.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<15;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+tR(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<15;e++)this.rows[e].clear();let e=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){let r=i.rows[e].cueStartTime,s=this.logger.time;if(null!==r&&null!==s&&r<s)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(i.rows[e+r])}}this.currRow=t;let i=this.rows[this.currRow];if(null!==e.indent){let t=Math.max(e.indent-1,0);i.setCursor(e.indent),e.color=i.chars[t].penState.foreground}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+tR(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;let t=[],i="",r=-1;for(let i=0;i<15;i++){let s=this.rows[i].getTextString();s&&(r=i+1,e?t.push("Row "+r+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class nJ{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new nZ(i),this.nonDisplayedMemory=new nZ(i),this.lastOutputScreen=new nZ(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),("MODE_PAINT-ON"===this.mode||"MODE_ROLL-UP"===this.mode)&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}
29ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{let i=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][i]}this.logger.log(2,"MIDROW: "+tR(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&!this.displayedMemory.isEmpty()&&(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e)}}class n0{constructor(e,t,i){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new nW,this.field=e,this.outputFilters=[null,t,i]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var i;this.outputFilters[e]=t,null==(i=this.channels[e])||i.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new nJ(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){var i;let r=127&t[e],s=127&t[e+1],a=!1,n=null;if(0===r&&0===s)continue;this.logger.log(3,()=>"["+nj([t[e],t[e+1]])+"] -> ("+nj([r,s])+")");let l=this.cmdHistory;if(r>=16&&r<=31){if(l.a===r&&l.b===s){l.a=null,l.b=null,this.logger.log(3,()=>"Repeated command ("+nj([r,s])+") is dropped");continue}(i=this.cmdHistory).a=r,i.b=s,(a=this.parseCmd(r,s))||(a=this.parseMidrow(r,s)),a||(a=this.parsePAC(r,s)),a||(a=this.parseBackgroundAttributes(r,s))}else l.a=null,l.b=null;if(!a&&(n=this.parseChars(r,s))){let e=this.currentChannel;e&&e>0?this.getChannel(e).insertChars(n):this.logger.log(2,"No channel found yet. TEXT-MODE?")}a||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+nj([r,s])+" orig: "+nj([t[e],t[e+1]]))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;let i=20===e||21===e||23===e?1:2,r=this.getChannel(i);return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if((i=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+nj([e,t])+")"),!0)}return!1}parsePAC(e,t){let i;let r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,s=(16===e||24===e)&&t>=64&&t<=95;if(!(r||s))return!1;let a=e<=23?1:2;return i=t>=64&&t<=95?1===a?nG[e]:nV[e]:1===a?nK[e]:nH[e],this.getChannel(a).setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0}interpretPAC(e,t){let i;let r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=(1&i)==1,i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(e,t){let i;let r=null,s=null;if(e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,()=>"Special char '"+nB(e)+"' in channel "+i),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes = "+nj(r).join(",")),r}
29parseBackgroundAttributes(e,t){let i;if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;let r={};return 16===e||24===e?(i=Math.floor((t-32)/2),r.background=nY[i],t%2==1&&(r.background=r.background+"_semi")):45===t?r.background="transparent":(r.foreground="black",47===t&&(r.underline=!0)),this.getChannel(e<=23?1:2).setBkgData(r),!0}reset(){var e;for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}(e=this.cmdHistory).a=null,e.b=null}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e)}}}class n1{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class n2{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=n4(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}}
29,e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new n1(this,"textTrack1"),t=new n1(this,"textTrack2"),i=new n1(this,"textTrack3"),r=new n1(this,"textTrack4");this.cea608Parser1=new n0(1,e,t),this.cea608Parser2=new n0(3,i,r)}addCues(e,t,i,r,s){var a,n;let l=!1;for(let e=s.length;e--;){let r=s[e],n=(a=r[0],Math.min(r[1],i)-Math.max(a,t));if(n>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],i),l=!0,n/(i-t)>.5))return}if(l||s.push([t,i]),this.config.renderTextTracksNatively){let s=this.cueCache[e];if(s){let e=this.Cues.newCue(null,t,i,r);e.length&&s.push.apply(s,e)}else{let s=this.captionsTracks[e].track;this.Cues.newCue(s,t,i,r)}}else{let s=this.Cues.newCue(null,t,i,r),a=null==(n=this.captionsProperties[e])?void 0:n.media;this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:s,track:e,closedCaptions:a})}}onInitPtsFound(e,{id:t,timestampOffsets:i}){let{unparsedVttFrags:r}=this;t===w.MAIN&&(this.initPTS=i),r.length&&(this.unparsedVttFrags=[],r.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(m.FRAG_LOADED,e):this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error:Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,cueCache:r,media:s}=this,{label:a,languageCode:n}=t[e];s&&(r[e]=[],i[e]=ni(s,"captions",a,n,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){let i=!!t.transferMedia;if(this.media=null,!i){if(this.config.renderTextTracksNatively){let{captionsTracks:e,cueCache:t}=this;for(let i in e)e[i].remove(),delete t[i]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=n4(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[];if(i.length&&!this.config.renderTextTracksNatively&&!sE(this.tracks,i)){let e=i.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}this.tracks=i}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e
29=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let i=`textTrack${t[1]}`,r=this.captionsProperties[i];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===w.MAIN){var i,r;let{cea608Parser1:e,cea608Parser2:s,lastSn:a}=this,{cc:n,sn:l}=t.frag,o=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;e&&s&&(l!==a+1||l===a&&o!==this.lastPartIndex+1||n!==this.lastCc)&&(e.reset(),s.reset()),this.lastCc=n,this.lastSn=l,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.level<this.tracks.length&&i.type===w.SUBTITLE){if(r.byteLength){let e=i.decryptdata,r="stats"in t;if(null==e||!e.encrypted||r){let e=this.tracks[i.level],r=this.vttCCs;r[i.cc]||(r[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),(null==e?void 0:e.textCodec)===a2?this._parseIMSC1(t):this._parseVTTs(t)}}else{let e="part"in t?t.part:null;this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:e,error:Error("Empty subtitle payload")})}}}_parseIMSC1(e){let{frag:t,payload:i}=e,r="part"in e?e.part:null,s=this.hls;a5(i,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:r})},e=>{s.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${e}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:r,error:e})})}_parseVTTs(e){var t;let{frag:i,payload:r}=e,s="part"in e?e.part:null,{initPTS:a,unparsedVttFrags:n}=this,l=a.length-1;if(!a[i.cc]&&-1===l){n.push(e);return}let o=this.hls,h=null==(t=i.initSegment)?void 0:t.data;!function(e,t,i,r,s,a,n){let l;let o=new az,h=eS(new Uint8Array(e)).trim().replace(aZ,"\n").split("\n"),d=[],u=t?function(e,t=1){return r5(e,9e4,1/t)}(t.baseTime,t.timescale):0,f="00:00.000",c=0,g=0,m=!1,p=!0;o.oncue=function(e){let a=i[r],n=i.ccOffset,o=(c-u)/9e4;if(m){if(null!=a&&a.new&&(n=i.ccOffset=a.start),o){if(!t){l=Error(aJ+"MPEGTS");return}n=o-i.presentationOffset}}else if(t)n=-t.baseTime/t.timescale;else{l=Error(aJ+"without X-TIMESTAMP-MAP");return}let h=e.endTime-e.startTime,f=st((e.startTime+n-g)*9e4,9e4*s)/9e4;e.startTime=Math.max(f,0),e.endTime=Math.max(f+h,0);let p=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(p)),e.id?r&&(e.id=`hlsjscc${r}_${e.id}`):e.id=a1(e.startTime,e.endTime,p),e.endTime>0&&d.push(e)},o.onparsingerror=function(e){l=e},o.onflush=function(){if(l){n(l);return}a(d)},h.forEach(e=>{if(p){if(e.startsWith("X-TIMESTAMP-MAP=")){p=!1,m=!0,e.slice(16).split(",").forEach(e=>{e.startsWith("LOCAL:")?f=e.slice(6):e.startsWith("MPEGTS:")&&(c=parseInt(e.slice(7)))});try{g=a0(f)/1e3}catch(e){l=e}return}""===e&&(p=!1)}o.parse(e+"\n")}),o.flush()}(h?eX(h,new Uint8Array(r)).buffer:r,this.initPTS[i.cc],this.vttCCs,i.cc,(s&&!h?s:i).start,e=>{this._appendCues(e,i.level),o.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:s})},t=>{let r=t.message.startsWith("Missing initPTS");if(o.logger.log(`${r?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${i.sn} @${i.start}): ${t}`),r){n.push(e);return}this.config.enableIMSC1&&this._fallbackToIMSC1(e),o.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:s,error:t})})}_fallbackToIMSC1(e){let{frag:t,payload:i}=e,r=this.tracks[t.level];r.textCodec||a5(i,this.initPTS[t.cc],()=>{r.textCodec=a2,this._parseIMSC1(e)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){var r;let i=null==(r=this.tracks[t].trackNode)?void 0:r.track;if(!i||"disabled"===i.mode)return;e.forEach(e=>nr(i,e))}else{let r=this.tracks[t];if(!r)return;let s=r.default?"default":"subtitles"+t;i.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:s,subtitleTrack:r})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===w.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:r}=t;if(i.type!==w.MAIN||"NONE"!==this.closedCaptionsForLevel(i))for(let e=0;e<r.length;e++){let t=r[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();let i=this.extractCea608Data(t);this.cea608Parser1.addData(r[e].pts,i[0]),this.cea608Parser2.addData(r[e].pts,i[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var i;let{type:e,timeRanges:r}=t;if("video"===e&&null!=(i=r[e])&&i.length){let{captionsTracks:e,cueC
29ache:t}=this;Object.keys(t).forEach(i=>{var r;let s=null==(r=e[i])?void 0:r.track;if(s){let e=t[i];for(let t=0;t<e.length;t++)nr(s,e[t])}delete t[i]})}}}onBufferFlushing(e,t){let{startOffset:i,endOffset:r,endOffsetSubtitles:s,type:a}=t,{media:n}=this;if(n&&!(n.currentTime<r)){if(!a||"video"===a){let{captionsTracks:e,cueCache:t}=this;Object.keys(e).forEach(t=>ns(e[t].track,i,r)),Object.keys(t).forEach(e=>{let s=t[e];for(let e=s.length;e--;){let t=s[e];t.startTime>=i&&t.endTime<=r&&s.splice(e,1)}})}this.config.renderTextTracksNatively&&0===i&&void 0!==s&&this.tracks.forEach(e=>{var t;let r=null==(t=e.trackNode)?void 0:t.track;r&&ns(r,i,s)})}}extractCea608Data(e){let t=[[],[]],i=31&e[0],r=2;for(let s=0;s<i;s++){let i=e[r++],s=127&e[r++],a=127&e[r++];if((0!==s||0!==a)&&(4&i)!=0){let e=3&i;(0===e||1===e)&&(t[e].push(s),t[e].push(a))}}return t}}function n4(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}let n3=/\s/;class n8{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new O}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,i){let r=this.stats;if(r.loading.start)throw Error("Loader can only be used once.");r.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry;if(Z(e,this.stats.retry,!0))this.retry(e);else{var t;eo.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=z(e,i.retry),i.retry++,eo.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==t?void 0:t.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}let n5=/(\d+)-(\d+)\/(\d+)/;class n6 extends n8{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||n9}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){let{config:e,context:t,stats:i}=this;if(!e||!t)return;i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;let r=function(e,t){let i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(K({},e.headers))};return e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),i}(t,this.controller.signal),s="arraybuffer"===t.responseType,a=s?"byteLength":"length",{maxTimeToFirstByteMs:n,maxLoadTimeMs:l}=e.loadPolicy;this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=n&&d(n)?n:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()}
29,e.timeout),(sd(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(r=>{var a;this.response=r;let n=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(n-i.loading.start)),!r.ok){let{status:e,statusText:t}=r;throw new n7(t||"fetch, bad network response",e,r)}i.loading.first=n,i.total=function(e){let t=e.get("Content-Range");if(t){let e=function(e){let t=n5.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(d(e))return e}let i=e.get("Content-Length");if(i)return parseInt(i)}(r.headers)||i.total;let o=null==(a=this.callbacks)?void 0:a.onProgress;return o&&d(e.highWaterMark)?this.loadProgressively(r,i,t,e.highWaterMark,o):s?r.arrayBuffer():"json"===t.responseType?r.json():r.text()}).then(r=>{var s,n;let l=this.response;if(!l)throw Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);let o=r[a];o&&(i.loaded=i.total=o);let h={url:l.url,data:r,code:l.status},u=null==(s=this.callbacks)?void 0:s.onProgress;u&&!d(e.highWaterMark)&&u(i,t,r,l),null==(n=this.callbacks)||n.onSuccess(h,i,t,l)}).catch(r=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;let s=r&&r.code||0,a=r?r.message:null,n=e.loadPolicy.errorRetry;if(Z(n,i.retry,!1,{url:t.url,data:void 0,code:s}))this.retry(n);else{var l;eo.error(`${s} while loading ${t.url}`),null==(l=this.callbacks)||l.onError({code:s,text:a},t,r?r.details:null,i)}})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,s){let a=new rn,n=e.body.getReader(),l=()=>n.read().then(n=>{if(n.done)return a.dataLength&&s(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let o=n.value,h=o.length;return t.loaded+=h,h<r||a.dataLength?(a.push(o),a.dataLength>=r&&s(t,i,a.flush().buffer,e)):s(t,i,o.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function n9(e,t){return new self.Request(e.url,t)}class n7 extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}let le=(e,t,i)=>Math.max(t,Math.min(e,i)),lt=/^age:\s*[\d.]+\s*$/im;class li extends n8{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let s=this.xhrSetup;s?Promise.resolve().then(()=>{if(this.loader===i&&!this.stats.aborted)return s.call(this,i,t.url,t)}).catch(e=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",t.url,!0),s.call(this,i,t.url,t)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(e=>{var s;null==(s=this.callbacks)||s.onError({code:i.status,text:e.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(let t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range",`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&d(s)?s:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){var a,n,l;self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let r=t.status,o="text"===t.responseType?t.responseText:null;if(r>=200&&r<300){let s=null!=o?o:t.response;if(null!=s){i.loading.end=Math.max(self.performance.now(),i.loading.first);let l="arraybuffer"===t.responseType?s.byteLength:s.length;i.loaded=i.total=l,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);let o=null==(a=this.callbacks)?void 0:a.onProgress;
29o&&o(i,e,s,t);let h={url:t.responseURL,data:s,code:r};e.rangeEnd&&l!==e.rangeEnd-e.rangeStart&&eo.warn(`Payload length ${l} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),null==(n=this.callbacks)||n.onSuccess(h,i,e,t);return}}let h=s.loadPolicy.errorRetry;Z(h,i.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(h):(eo.error(`${r} while loading ${e.url}`),null==(l=this.callbacks)||l.onError({code:r,text:t.statusText},e,t,i))}}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&<.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}let lr=H(H({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:li,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ik,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:nv,abrController:tx,bufferController:sL,capLevelController:sC,errorController:tH,fpsController:aG,id3TrackController:ng,gapController:nn,latencyController:nx},{cueHandler:{newCue(e,t,i,r){let s,a,n,l,o;let h=[],d=self.VTTCue||self.TextTrackCue;for(let f=0;f<r.rows.length;f++)if(s=r.rows[f],n=!0,l=0,o="",!s.isEmpty()){var u;for(let e=0;e<s.chars.length;e++)n3.test(s.chars[e].uchar)&&n?l++:(o+=s.chars[e].uchar,n=!1);s.cueStartTime=t,t===i&&(i+=1e-4),l>=16?l--:l++;let r=aX(o.trim()),c=a1(t,i,r);null!=e&&null!=(u=e.cues)&&u.getCueById(c)||((a=new d(t,i,r)).id=c,a.line=f+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),h.push(a))}return e&&h.length&&(h.sort((e,t)=>
29"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),h.forEach(t=>nr(e,t))),h}},enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:nN,subtitleTrackController:na,timelineController:n2,audioStreamController:sm,audioTrackController:sy,emeController:aN,cmcdController:aO,contentSteeringController:aM,iframeController:nA,interstitialsController:nF});class ls extends sp{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,r=[],s={},a={},n=!1,l=!1,o=!1,h=!1;t.levels.forEach(e=>{let t=e.attrs,d=ll(e,i),{audioCodec:u,videoCodec:f,imageCodec:c,width:g,height:m}=e;if(!d){this.log(`Some or all CODECS not supported "${t.CODECS}"`);return}n||(n=!!(g&&m)),l||(l=!!f),o||(o=!!u),h||(h=!!c);let{CODECS:p,"FRAME-RATE":E,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:T,"VIDEO-RANGE":S}=t,A=`${y||"."}-`,I=`${A}${e.bitrate}-${T}-${E}-${p}-${S}-${v}`;if(s[I]){if(s[I].uri===e.url||e.attrs["PATHWAY-ID"])e.iframes||(s[I].addGroupId("audio",t.AUDIO),s[I].addGroupId("text",t.SUBTITLES));else{let t=a[I]+=1;e.attrs["PATHWAY-ID"]=Array(t+1).join(".");let i=this.createLevel(e);s[I]=i,r.push(i)}}else{let t=this.createLevel(e);s[I]=t,a[I]=1,r.push(t)}}),this.filterAndSortMediaOptions(r,t,n,l,o,h)}createLevel(e){let t=new tA(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!ln(i.videoCodec,this.hls.config.preferManagedMediaSource)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(e.message),t.supportedResult=tf(e,[])}return t}filterAndSortMediaOptions(e,t,i,r,s,a){var n,l;let o=[],h=[],d=e,u=(null==(n=t.stats)?void 0:n.parsing)||{},f=this.hls.config.preferManagedMediaSource;if((i||r)&&s&&(d=d.filter(({videoCodec:e,videoRange:t,width:i,height:r})=>{var s;return(!!e||!!(i&&r))&&!!(s=t)&&tv.indexOf(s)>-1})),r&&a&&(d=d.filter(e=>!e.imageCodec)),0===d.length){Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i=`one or more CODECS in variant not supported: ${tR(t.levels.map(e=>e.attrs.CODECS).filter((e,t,i)=>i.indexOf(e)===t))}`,this.warn(i),e+=` (${i})`);let r=Error(e);this.hls.trigger(m.ERROR,{type:c.MEDIA_ERROR,details:g.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:i})}}),u.end=performance.now();return}t.audioTracks&&lo(o=t.audioTracks.filter(e=>!e.audioCodec||la(e.audioCodec,f))),t.subtitles&&lo(h=t.subtitles);let p=d.slice(0);d.sort((e,t)=>
29{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return tv.indexOf(e.videoRange)-tv.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let i=tt(e.videoCodec),r=tt(t.videoCodec);if(i!==r)return r-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let i=ti(e.codecSet),r=ti(t.codecSet);if(i!==r)return r-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let E=p[0];if(this.steering&&(d=this.steering.filterParsedLevels(d)).length!==p.length){for(let e=0;e<p.length;e++)if(p[e].pathwayId===d[0].pathwayId){E=p[e];break}}this._levels=d;for(let e=0;e<d.length;e++)if(d[e]===E){this._firstLevel=e;let t=E.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${t}`),(null==(l=this.hls.userConfig)?void 0:l.abrEwmaDefaultEstimate)===void 0){let e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}let v=t.iframeVariants.filter(e=>ll(e,f));this._iframeVariants=v;let y=s&&!r,T=this.hls.config,S=!!(T.audioStreamController&&T.audioTrackController),A={levels:d,audioTracks:o,subtitleTracks:h,iframeVariants:v,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:r,altAudio:S&&!y&&o.some(e=>!!e.url)};u.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,A)}get iframeVariants(){return 0===this._iframeVariants.length?null:this._iframeVariants}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){let i=Error("invalid level idx"),r=e<0;if(this.hls.trigger(m.ERROR,{type:c.OTHER_ERROR,details:g.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],n=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&r&&s===n)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${n?" with Pathway "+n:""} from level ${i}${s?" with Pathway "+s:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(m.LEVEL_SWITCHING,l);let o=a.details;if(!o||o.live){let e=this.switchParams(a.uri,null==r?void 0:r.details,o);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){let e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),i=e.filter(e=>-1!==t.indexOf(e));if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){!t.fatal&&t.context&&t.context.type===M.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===w.MAIN){let e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;let i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i,r;let{level:s,details:a}=t,n=t.levelInfo;if(!n){this.warn(`Invalid level index ${s}`),null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(s,t,e)}else null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLo
29ading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,s=e.attrs["PATHWAY-ID"],a=e.details,n=null==a?void 0:a.age;this.log(`Loading level index ${r}${(null==t?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${s?" Pathway "+s:""}${n&&a.live?" age "+n.toFixed(1)+(a.type?" "+a.type:""):""} ${i}`),this.hls.trigger(m.LEVEL_LOADING,{url:i,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return -1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){let t=this.currentLevelIndex;if(-1===this.manualLevelIndex&&e!==t&&-1!==e){let i=this.hls.config.abrSwitchInterval;if(i>0){let r=performance.now(),s=r-this.lastABRSwitchTime,a=1e3*i;if(this.lastABRSwitchTime>-1&&s<a){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(s)}ms < ${a}ms / ${i}s)`);return}this.lastABRSwitchTime=r,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(s)}ms >= ${a}ms / ${i}s)`)}}this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;let i=this._levels.filter((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));i4(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=i.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(m.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(m.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function la(e,t){return e9(e,"audio",t)}function ln(e,t){return e9(e,"video",t)}function ll(e,t){let{audioCodec:i,videoCodec:r}=e;i&&(e.audioCodec=i=ta(i,t)||void 0),r&&(r=e.videoCodec=function(e){let t=e.split(",");for(let e=0;e<t.length;e++){let i=t[e].split(".");i.length>2&&"avc1"===i[0]&&(t[e]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return t.join(",")}(r));let{unknownCodecs:s}=e;return(null==s||!s.length)&&(!i||!!la(i,t))&&(!r||!!ln(r,t))}function lo(e){let t={};e.forEach(e=>{let i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}class lh extends er{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyLoaderInfo){let r=this.keyLoaderInfo[i].loader;if(r){var t;if(e&&e!==(null==(t=r.context)?void 0:t.frag.type))return;r.abort()}}}destroy(){for(let e in this.keyLoaderInfo){let t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,i){return this.emeController?this.emeController.loadClear(e,t,i):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(i=>this.loadInternal(e,t,i)):this.loadInternal(e,t)}loadInternal(e,t,i){i&&e.setKeyFormat(i);let r=e.decryptdata;if(!r){let t=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(ld(e,g.KEY_LOAD_ERROR,t))}switch(r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":if("identity"===r.keyFormat)return this.loadKeyHTTP(e);return t?t.then(()=>this.loadKeyEME(e)):this.loadKeyEME(e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(e);default:return Promise.reject(ld(e,g.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&null!=(t=e.initSegment)&&t.data){let t=function(e){let t=[];return eW(e,e=>t.push(e.subarray(8,24))),t}(e.initSegment.data);if(t.length){let i=t[0],r=e.decryptdata.uri;if(i.some(e=>0!==e))this.log(`Using keyId found in init segment ${eR(i)} keyUri: ${r}`),iC.setKeyIdForUri(r,i);else{let e=iC.addKeyIdForUri(r);this.log(`Patching empty keyId with ${eR(e)} keyUri: ${r}`),i=e}e.decryptdata.keyId=i}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(ld(e,g.KEY_LOAD_ERROR,Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,i=t.uri;if(!i)return Promise.reject(ld(e,g.KEY_LOAD_ERROR,Error(`Invalid key URI: "${i}"`)));let r=this.keyLoaderInfo[i];if(r){if(r.decryptdata.key)return t.key=r.decryptdata.key,r.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:r});if(r.keyLoadPromise)return r.keyLoadPromise.then(i=>(t.key=r.decryptdata.key,H(H({},i),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+eR(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);let s=this.config,a=new s.loader(s);e.keyLoader=a;let n=this.keyLoaderInfo[i]={decryptdata:t,keyLoadPromise:null,loader:a};return n.keyLoadPromise=new Promise((t,r)=>{let l={type:M.KEY,keyInfo:n,frag:e,responseType:"arraybuffer",url:i},o=s.keyLoadPolicy.default,h={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};a.load(l,h,{onSuccess:(e,i,s,a)=>{let{frag:n,keyInfo:l,url:o}=s;
29if(!n.decryptdata||l!==this.keyLoaderInfo[o])return r(ld(n,g.KEY_LOAD_ERROR,Error("after key load, decryptdata unset or changed"),a));l.decryptdata.key=n.decryptdata.key=new Uint8Array(e.data),n.keyLoader=l.loader=l.keyLoadPromise=null,t({frag:n,keyInfo:l})},onError:(t,s,a,n)=>{this.resetLoader(s),r(ld(e,g.KEY_LOAD_ERROR,Error(`HTTP Error ${t.code} loading key ${t.text}`),a,H({url:i,data:void 0},t)))},onTimeout:(t,i,s)=>{this.resetLoader(i),r(ld(e,g.KEY_LOAD_TIMEOUT,Error("key loading timed out"),s))},onAbort:(t,i,s)=>{this.resetLoader(i),r(ld(e,g.INTERNAL_ABORTED,Error("key loading aborted"),s))}})})}resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,s=i.loader;t.keyLoader===s&&(t.keyLoader=i.loader=i.keyLoadPromise=null),delete this.keyLoaderInfo[r],s&&s.destroy()}}function ld(e,t=g.KEY_LOAD_ERROR,i,r,s){return new t9({type:c.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:i,networkDetails:r||null})}function lu(e){let{type:t}=e;switch(t){case M.AUDIO_TRACK:return w.AUDIO;case M.SUBTITLE_TRACK:return w.SUBTITLE;default:return w.MAIN}}function lf(e,t){let i=e.url;return(void 0===i||0===i.indexOf("data:"))&&(i=t.url),i}class lc{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,r=t.loader,s=new(i||r)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:M.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:i,level:r,pathwayId:s,url:a,deliveryDirectives:n,levelInfo:l}=t;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:M.LEVEL,url:a,deliveryDirectives:n,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:i,groupId:r,url:s,deliveryDirectives:a,track:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:M.AUDIO_TRACK,url:s,deliveryDirectives:a,levelOrTrack:n})}onSubtitleTrackLoading(e,t){let{id:i,groupId:r,url:s,deliveryDirectives:a,track:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:M.SUBTITLE_TRACK,url:s,deliveryDirectives:a,levelOrTrack:n})}onLevelsUpdated(e,t){let i=this.loaders[M.LEVEL];if(i){let e=i.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(i.abort(),delete this.loaders[M.LEVEL])}}load(e){var t;let i;let r=this.hls.config,s=this.getInternalLoader(e);if(s){let t=this.hls.logger,i=s.context;if((null==i?void 0:i.levelOrTrack)===e.levelOrTrack&&(i.url===e.url||i.deliveryDirectives&&!e.deliveryDirectives)){i.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${i.url}`);return}t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(i=e.type===M.MANIFEST?r.manifestLoadPolicy.default:K({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),d(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===M.LEVEL&&null!==e.level?t=this.hls.levels[e.level].details:e.type===M.AUDIO_TRACK&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===M.SUBTITLE_TRACK&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,r=t.targetduration;if(e&&r){let t=1e3*Math.max(3*e,.8*r);i=K({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}let a=i.errorRetry||i.timeoutRetry||{},n={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0};s.load(e,n,{onSuccess:(e,t,i,r)=>{let s=this.getInternalLoader(i);this.resetInternalLoader(i.type);let a=e.data;t.parsing.start=performance.now(),i$.isMediaPlaylist(a)||i.type!==M.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,i,r||null,s):this.handleMasterPlaylist(e,t,i,r)},onError:(e,t,i,r)=>{this.handleNetworkError(t,i,!1,e,r)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}})}
vendor: 4,112 bytes, line 29
29checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,r){let s=this.hls,a=e.data,n=lf(e,i),l=i$.parseMasterPlaylist(a,n);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);return}let{contentSteering:o,levels:h,iframeVariants:d,sessionData:u,sessionKeys:f,startTimeOffset:c,variableList:g}=l;this.variableList=g,h.forEach(e=>{let{unknownCodecs:t}=e;if(t){let{preferManagedMediaSource:i}=this.hls.config,{audioCodec:r,videoCodec:s}=e;for(let a=t.length;a--;){let n=t[a];e9(n,"audio",i)?(e.audioCodec=r=r?`${r},${n}`:n,e5.audio[r.substring(0,4)]=2,t.splice(a,1)):e9(n,"video",i)&&(e.videoCodec=s=s?`${s},${n}`:n,e5.video[s.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:p=[],SUBTITLES:E,"CLOSED-CAPTIONS":v}=i$.parseMasterPlaylistMedia(a,n,l);p.length&&!p.some(e=>!e.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new id({}),bitrate:0,url:""})),s.trigger(m.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:E,iframeVariants:d,captions:v,contentSteering:o,url:n,stats:t,networkDetails:r,sessionData:u,sessionKeys:f,startTimeOffset:c,variableList:g})}handleTrackOrLevelPlaylist(e,t,i,r,s){let a=this.hls,{id:n,level:l,type:o}=i,h=lf(e,i),u=d(l)?l:d(n)?n:0,f=lu(i),c=i$.parseLevelPlaylist(e.data,h,u,f,0,this.variableList);if(o===M.MANIFEST){let e={attrs:new id({}),bitrate:0,details:c,name:"",url:h};c.requestScheduled=t.loading.start+iJ(c,0),a.trigger(m.MANIFEST_LOADED,{levels:[e],audioTracks:[],iframeVariants:[],url:h,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=c,this.handlePlaylistLoaded(c,e,t,i,r,s)}handleManifestParsingError(e,t,i,r,s){this.hls.trigger(m.ERROR,{type:c.NETWORK_ERROR,details:g.MANIFEST_PARSING_ERROR,fatal:t.type===M.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,i=!1,r,s){let a=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===M.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===M.AUDIO_TRACK||e.type===M.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let n=Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=g.UNKNOWN,o=!1,h=this.getInternalLoader(e);switch(e.type){case M.MANIFEST:l=i?g.MANIFEST_LOAD_TIMEOUT:g.MANIFEST_LOAD_ERROR,o=!0;break;case M.LEVEL:l=i?g.LEVEL_LOAD_TIMEOUT:g.LEVEL_LOAD_ERROR,o=!1;break;case M.AUDIO_TRACK:l=i?g.AUDIO_TRACK_LOAD_TIMEOUT:g.AUDIO_TRACK_LOAD_ERROR,o=!1;break;case M.SUBTITLE_TRACK:l=i?g.SUBTITLE_TRACK_LOAD_TIMEOUT:g.SUBTITLE_LOAD_ERROR,o=!1}h&&this.resetInternalLoader(e.type);let d={type:c.NETWORK_ERROR,details:l,fatal:o,url:e.url,loader:h,context:e,error:n,networkDetails:t,stats:s};if(r){let i=e.url;t&&"url"in t&&(i=t.url),d.response=H({url:i,data:void 0},r)}this.hls.trigger(m.ERROR,d)}handlePlaylistLoaded(e,t,i,r,s,a){let n=this.hls,{type:l,level:o,levelOrTrack:h,id:d,groupId:u,deliveryDirectives:f}=r,p=lf(t,r),E=lu(r),v="number"==typeof r.level&&E===w.MAIN?o:void 0;h&&"iframes"in h&&h.iframes&&!e.iframesOnly&&(e.playlistParsingError=Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);let y=e.playlistParsingError;if(y){if(this.hls.logger.warn(`${y} ${e.url}`),!n.config.ignorePlaylistParsingErrors){n.trigger(m.ERROR,{type:c.NETWORK_ERROR,details:g.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:y,reason:y.message,response:t,context:r,level:v,parent:E,networkDetails:s,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){let a=e.playlistParsingError=Error("No Segments found in Playlist");
29n.trigger(m.ERROR,{type:c.NETWORK_ERROR,details:g.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:a,reason:a.message,response:t,context:r,level:v,parent:E,networkDetails:s,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case M.MANIFEST:case M.LEVEL:if(v){if(h){if(h!==n.levels[v]){let e=n.levels.indexOf(h);e>-1&&(v=e)}}else v=0}n.trigger(m.LEVEL_LOADED,{details:e,levelInfo:h||n.levels[0],level:v||0,id:d||0,stats:i,networkDetails:s,deliveryDirectives:f,withoutMultiVariant:l===M.MANIFEST,context:r});break;case M.AUDIO_TRACK:n.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:u||"",stats:i,networkDetails:s,deliveryDirectives:f,context:r});break;case M.SUBTITLE_TRACK:n.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:u||"",stats:i,networkDetails:s,deliveryDirectives:f,context:r})}}}class lg{static get version(){return rh}static isMSESupported(){return np()}static isSupported(){return function(){if(!np())return!1;let e=eh();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(te(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(te(t,"audio"))))}()}static getMediaSource(){return eh()}static get Events(){return m}static get MetadataSchema(){return rE}static get ErrorTypes(){return c}static get ErrorDetails(){return g}static get DefaultConfig(){return lg.defaultConfig?lg.defaultConfig:lr}static set DefaultConfig(e){lg.defaultConfig=e}constructor(e={}){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 ro,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.iframeC
29ontroller=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 t=this.logger=function(e,t,i){let r=en();if("object"==typeof console&&!0===e||"object"==typeof e){let s=["debug","log","info","warn","error"];s.forEach(t=>{r[t]=el(t,e,i)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.7.0`)}catch(e){return en()}s.forEach(t=>{eo[t]=el(t,e)})}else K(eo,r);return r}(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),i=this.config=function(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(void 0!==t.liveMaxUnchangedPlaylistRefresh){let e=t.liveMaxUnchangedPlaylistRefresh,r=le(e,2,1/0);r!==e&&i.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${e} to ${r}.`),t.liveMaxUnchangedPlaylistRefresh=r}let r=function e(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(e):Object.keys(t).reduce((i,r)=>(i[r]=e(t[r]),i),{}):t}(e),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{let a=`${"level"===e?"playlist":e}LoadPolicy`,n=void 0===t[a],l=[];s.forEach(i=>{let s=`${e}Loading${i}`,o=t[s];if(void 0!==o&&n){l.push(s);let e=r[a].default;switch(t[a]={default:e},i){case"TimeOut":e.maxLoadTimeMs=o,e.maxTimeToFirstByteMs=o;break;case"MaxRetry":e.errorRetry.maxNumRetry=o,e.timeoutRetry.maxNumRetry=o;break;case"RetryDelay":e.errorRetry.retryDelayMs=o,e.timeoutRetry.retryDelayMs=o;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=o,e.timeoutRetry.maxRetryDelayMs=o}}}),l.length&&i.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${tR(t[a])}`)}),H(H({},r),t)}(lg.DefaultConfig,e,t);this.userConfig=e,i.progressive&&function(e,t){let i=e.loader;i!==n6&&i!==li?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=n6,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(i,t);let{streamController:r,abrController:s,bufferController:a,capLevelController:n,errorController:l,fpsController:o,id3TrackController:h,iframeController:d,gapController:u}=i,f=new l(this),c=this.abrController=new s(this),g=new tX(this),p=i.interstitialsController,E=p?this.interstitialsController=new p(this,lg):null,v=a?this.bufferController=new a(this,g):null,y=n?this.capLevelController=new n(this):null,T=o?new o(this):null,S=i.cmcdController,A=S?this.cmcdController=new S(this):null,I=new lc(this),L=i.contentSteeringController,R=L?new L(this):null,b=this.levelController=new ls(this,R),D=h?new h(this):void 0,k=new lh(this.config,this.logger),P=this.streamController=new r(this,g,k),_=this.gapController=u?new u(this,g):void 0;y&&y.setStreamController(P);let C=[I,b,P];E&&C.splice(1,0,E),R&&C.splice(1,0,R),this.networkControllers=C;let O=[c];v&&O.push(v),_&&O.push(_),y&&O.push(y),T&&(T.setStreamController(P),O.push(T)),D&&O.push(D),O.push(g),this.audioTrackController=this.createController(i.audioTrackController,C);let M=i.audioStreamController;M&&C.push(this.audioStreamController=new M(this,g,k)),this.subtitleTrackController=this.createController(i.subtitleTrackController,C);let w=i.subtitleStreamController;
vendor: 1,568 bytes, line 29
29w&&C.push(this.subtititleStreamController=new w(this,g,k)),this.createController(i.timelineController,O),k.emeController=this.emeController=this.createController(i.emeController,O),A&&O.push(A),this.latencyController=this.createController(i.latencyController,O),this.coreComponents=O,this.iframeController=d?new d(this,lg):void 0,C.push(f);let F=f.onErrorOut;"function"==typeof F&&this.on(m.ERROR,F,f),this.on(m.MANIFEST_LOADED,I.onManifestLoaded,I)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;let i=e===m.ERROR;this.trigger(m.ERROR,{type:c.OTHER_ERROR,details:g.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(m.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>
29e.destroy()),this.coreComponents.length=0,this.iframeController=void 0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let t=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(m.ERROR,{type:c.OTHER_ERROR,details:g.ATTACH_MEDIA_ERROR,fatal:!0,error:t});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,r=t?e:{media:i};this._media=i,this.trigger(m.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia");let e={};this.trigger(m.MEDIA_DETACHING,e),this._media=null,this.trigger(m.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;let t=(null==(e=this.bufferController)?void 0:e.transferMedia())||null,i={transferMedia:t};return this.trigger(m.MEDIA_DETACHING,i),this.trigger(m.MEDIA_DETACHED,i),t}loadSource(e){var t;this.stopLoad();let i=this.media,r=this._url,s=this._url=C.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),i&&r&&(r!==s||null!=(t=this.bufferController)&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(m.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!this.started&&this.networkControllers);e++);}get loadingEnabled(){return this.started&&this.streamController.state!==ri.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[w.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[w.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[w.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=this.started,i=null==e?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(i?this.startLoad(i):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=em()),e}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return -1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=this.capLevelController,i=!!e;t&&i!==this.config.capLevelToPlayerSize&&(i?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){tE.indexOf(e)>-1&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return -1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let e;let{levels:t,autoLevelCapping:i,maxHdcpLevel:r}=this;if(e=-1===i&&null!=t&&t.length?t.length-1:i,r)for(let i=e;i--;){let e=t[i].attrs["HDCP-LEVEL"];if(e&&e<=r)return i}return e}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return(null==(e=this.audioStreamController)?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}
29setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){var e,t;return null!=(e=null==(t=this.audioStreamController)?void 0:t.nextAudioTrack)?e:-1}set nextAudioTrack(e){let{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return null!=(e=null==(t=this.latencyController)?void 0:t.liveSyncPosition)?e:null}get latency(){var e;return(null==(e=this.latencyController)?void 0:e.latency)||0}get maxLatency(){var e;return(null==(e=this.latencyController)?void 0:e.maxLatency)||0}get targetLatency(){var e;return(null==(e=this.latencyController)?void 0:e.targetLatency)||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){var e;return(null==(e=this.latencyController)?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!(null!=(e=this.bufferController)&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){return this.levelController.iframeVariants||[]}
29createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){return tc(e,tD(t),navigator.mediaCapabilities)}}lg.defaultConfig=void 0}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.