Files
haos_config/custom_components/hacs/hacs_frontend/frontend_latest/4768.461587f3e57e00e6.js
2026-01-30 23:31:00 -06:00

2 lines
279 KiB
JavaScript

export const ids=["4768"];export const modules={31126:function(t,e,r){var s=r(71998);t.exports=function(){var t=s(this),e="";return t.hasIndices&&(e+="d"),t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.unicodeSets&&(e+="v"),t.sticky&&(e+="y"),e}},32517:function(t,e,r){var s=r(1569),i=r(85779),n=r(27803),a=r(31126),o=r(29660),l=s.RegExp,d=l.prototype;i&&o((function(){var t=!0;try{l(".","d")}catch(e){t=!1}var e={},r="",s=t?"dgimsy":"gimsy",i=function(t,s){Object.defineProperty(e,t,{get:function(){return r+=s,!0}})},n={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var a in t&&(n.hasIndices="d"),n)i(a,n[a]);return Object.getOwnPropertyDescriptor(d,"flags").get.call(e)!==s||r!==s}))&&n(d,"flags",{configurable:!0,get:a})},17231:function(t,e,r){r.r(e),r.d(e,{AbrController:function(){return qe},AttrList:function(){return k},AudioStreamController:function(){return G},AudioTrackController:function(){return G},BasePlaylistController:function(){return Ve},BaseSegment:function(){return O},BaseStreamController:function(){return Zr},BufferController:function(){return Ze},CMCDController:function(){return G},CapLevelController:function(){return er},ChunkMetadata:function(){return Pr},ContentSteeringController:function(){return sr},DateRange:function(){return I},EMEController:function(){return G},ErrorActionFlags:function(){return Ge},ErrorController:function(){return He},ErrorDetails:function(){return S},ErrorTypes:function(){return T},Events:function(){return E},FPSController:function(){return rr},Fragment:function(){return N},Hls:function(){return oi},HlsSkip:function(){return Te},HlsUrlParameters:function(){return Se},KeySystemFormats:function(){return li},KeySystems:function(){return di},Level:function(){return Le},LevelDetails:function(){return U},LevelKey:function(){return wt},LoadStats:function(){return C},MetadataSchema:function(){return ue},NetworkErrorAction:function(){return $e},Part:function(){return B},PlaylistLevelType:function(){return ne},SubtitleStreamController:function(){return hi},SubtitleTrackController:function(){return G},TimelineController:function(){return ui},default:function(){return oi},getMediaSource:function(){return It},isMSESupported:function(){return es},isSupported:function(){return rs}});r(92745),r(84283),r(26200),r(25754),r(22246),r(32517),r(71375),r(15524),r(20267),r(39527),r(99790),r(41360),r(13334),r(34595),r(36993),r(21478),r(75656),r(50100),r(18084);function s(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var i,n,a,o,l,d={exports:{}};i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,n=/^(?=([^\/?#]*))\1([^]*)$/,a=/(?:\/|^)\.(?=\/)/g,o=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,d.exports=l={buildAbsoluteURL:function(t,e,r){if(r=r||{},t=t.trim(),!(e=e.trim())){if(!r.alwaysNormalize)return t;var s=l.parseURL(t);if(!s)throw new Error("Error trying to parse base URL.");return s.path=l.normalizePath(s.path),l.buildURLFromParts(s)}var i=l.parseURL(e);if(!i)throw new Error("Error trying to parse relative URL.");if(i.scheme)return r.alwaysNormalize?(i.path=l.normalizePath(i.path),l.buildURLFromParts(i)):e;var a=l.parseURL(t);if(!a)throw new Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var o=n.exec(a.path);a.netLoc=o[1],a.path=o[2]}a.netLoc&&!a.path&&(a.path="/");var d={scheme:a.scheme,netLoc:i.netLoc,path:null,params:i.params,query:i.query,fragment:i.fragment};if(!i.netLoc&&(d.netLoc=a.netLoc,"/"!==i.path[0]))if(i.path){var h=a.path,u=h.substring(0,h.lastIndexOf("/")+1)+i.path;d.path=l.normalizePath(u)}else d.path=a.path,i.params||(d.params=a.params,i.query||(d.query=a.query));return null===d.path&&(d.path=r.alwaysNormalize?l.normalizePath(i.path):i.path),l.buildURLFromParts(d)},parseURL:function(t){var e=i.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(a,"");t.length!==(t=t.replace(o,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}};var h=d.exports;function u(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,s)}return r}function c(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?u(Object(r),!0).forEach((function(e){g(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):u(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function f(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var s=r.call(t,e||"default");if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}function g(t,e,r){return(e=f(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function m(){return m=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])}return t},m.apply(this,arguments)}const p=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},v=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=y},y=Number.MAX_SAFE_INTEGER||9007199254740991;let E=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t}({}),T=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),S=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown",t}({});const L=function(){},R={trace:L,debug:L,log:L,warn:L,info:L,error:L};let A=R;function b(t,...e){e.forEach((function(e){A[e]=t[e]?t[e].bind(t):function(t){const e=self.console[t];return e?e.bind(self.console,`[${t}] >`):L}(e)}))}const D=A,_=/^(\d+)x(\d+)$/,x=/(.+?)=(".*?"|.*?)(?:,|$)/g;class k{constructor(t){"string"==typeof t&&(t=k.parseAttrList(t)),m(this,t)}get clientAttrs(){return Object.keys(this).filter((t=>"X-"===t.substring(0,2)))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const r=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)r[t]=parseInt(e.slice(2*t,2*t+2),16);return r}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const r=this[t];return r?parseFloat(r):e}enumeratedString(t){return this[t]}bool(t){return"YES"===this[t]}decimalResolution(t){const e=_.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const r={};for(x.lastIndex=0;null!==(e=x.exec(t));){let t=e[2];0===t.indexOf('"')&&t.lastIndexOf('"')===t.length-1&&(t=t.slice(1,-1));r[e[1].trim()]=t}return r}}function w(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}class I{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const r=e.attr;for(const e in r)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==r[e]){D.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=m(new k({}),r,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const t=new Date(this.attr["END-DATE"]);p(t.getTime())&&(this._endDate=t)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(p(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&p(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class C{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 P="audio",F="video",M="audiovideo";class O{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[P]:null,[F]:null,[M]:null},this.baseurl=t}setByteRange(t,e){const r=t.split("@",2);let s;s=1===r.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(r[1]),this._byteRange=[s,parseInt(r[0])+s]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=h.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class N extends O{constructor(t,e){super(e),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=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.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new C,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get decryptdata(){const{levelkeys:t}=this;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const t=Object.keys(this.levelkeys);if(1===t.length)return this._decryptdata=this.levelkeys[t[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;if(!p(this.programDateTime))return null;const t=p(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),e=t.length;if(e>1||1===e&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(t){if(this.levelkeys){const e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,r,s,i,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,i)):a[t]={startPTS:e,endPTS:r,startDTS:s,endDTS:i,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[P]=null,t[F]=null,t[M]=null}}class B extends O{constructor(t,e,r,s,i){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new C,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=s;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}class U{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,r=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!r||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&p(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}var $=void 0,G=s($);function H(t,e,r){return Uint8Array.prototype.slice?t.slice(e,r):new Uint8Array(Array.prototype.slice.call(t,e,r))}const V=(t,e)=>e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,K=(t,e)=>e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,W=(t,e)=>{const r=e;let s=0;for(;V(t,e);){s+=10;s+=Y(t,e+6),K(t,e+10)&&(s+=10),e+=s}if(s>0)return t.subarray(r,r+s)},Y=(t,e)=>{let r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3],r},j=(t,e)=>V(t,e)&&Y(t,e+6)+10<=t.length-e,q=t=>{const e=Q(t);for(let t=0;t<e.length;t++){const r=e[t];if(z(r))return rt(r)}},z=t=>t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,X=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),r=Y(t,4);return{type:e,size:r,data:t.subarray(10,10+r)}},Q=t=>{let e=0;const r=[];for(;V(t,e);){const s=Y(t,e+6);e+=10;const i=e+s;for(;e+8<i;){const s=X(t.subarray(e)),i=J(s);i&&r.push(i),e+=s.size+10}K(t,e)&&(e+=10)}return r},J=t=>"PRIV"===t.type?Z(t):"W"===t.type[0]?et(t):tt(t),Z=t=>{if(t.size<2)return;const e=st(t.data,!0),r=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:r.buffer}},tt=t=>{if(t.size<2)return;if("TXXX"===t.type){let e=1;const r=st(t.data.subarray(e),!0);e+=r.length+1;const s=st(t.data.subarray(e));return{key:t.type,info:r,data:s}}const e=st(t.data.subarray(1));return{key:t.type,data:e}},et=t=>{if("WXXX"===t.type){if(t.size<2)return;let e=1;const r=st(t.data.subarray(e),!0);e+=r.length+1;const s=st(t.data.subarray(e));return{key:t.type,info:r,data:s}}const e=st(t.data);return{key:t.type,data:e}},rt=t=>{if(8===t.data.byteLength){const e=new Uint8Array(t.data),r=1&e[3];let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,r&&(s+=47721858.84),Math.round(s)}},st=(t,e=!1)=>{const r=nt();if(r){const s=r.decode(t);if(e){const t=s.indexOf("\0");return-1!==t?s.substring(0,t):s}return s.replace(/\0/g,"")}const s=t.length;let i,n,a,o="",l=0;for(;l<s;){if(i=t[l++],0===i&&e)return o;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:n=t[l++],o+=String.fromCharCode((31&i)<<6|63&n);break;case 14:n=t[l++],a=t[l++],o+=String.fromCharCode((15&i)<<12|(63&n)<<6|63&a)}}return o};let it;function nt(){if(!navigator.userAgent.includes("PlayStation 4"))return it||void 0===self.TextDecoder||(it=new self.TextDecoder("utf-8")),it}const at=function(t){let e="";for(let r=0;r<t.length;r++){let s=t[r].toString(16);s.length<2&&(s="0"+s),e+=s}return e},ot=Math.pow(2,32)-1,lt=[].push,dt={video:1,audio:2,id3:3,text:4};function ht(t){return String.fromCharCode.apply(null,t)}function ut(t,e){const r=t[e]<<8|t[e+1];return r<0?65536+r:r}function ct(t,e){const r=gt(t,e);return r<0?4294967296+r:r}function ft(t,e){let r=ct(t,e);return r*=Math.pow(2,32),r+=ct(t,e+4),r}function gt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function mt(t,e,r){t[e]=r>>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r}function pt(t,e){const r=[];if(!e.length)return r;const s=t.byteLength;for(let i=0;i<s;){const n=ct(t,i),a=n>1?i+n:s;if(ht(t.subarray(i+4,i+8))===e[0])if(1===e.length)r.push(t.subarray(i+8,a));else{const s=pt(t.subarray(i+8,a),e.slice(1));s.length&&lt.apply(r,s)}i=a}return r}function vt(t){const e=[],r=t[0];let s=8;const i=ct(t,s);s+=4;let n=0,a=0;0===r?(n=ct(t,s),a=ct(t,s+4),s+=8):(n=ft(t,s),a=ft(t,s+8),s+=16),s+=2;let o=t.length+a;const l=ut(t,s);s+=2;for(let r=0;r<l;r++){let r=s;const n=ct(t,r);r+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return D.warn("SIDX has hierarchical references (not supported)"),null;const l=ct(t,r);r+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/i,start:o,end:o+a-1}}),o+=a,r+=4,s=r}return{earliestPresentationTime:n,timescale:i,version:r,referencesCount:l,references:e}}function yt(t){const e=[],r=pt(t,["moov","trak"]);for(let t=0;t<r.length;t++){const s=r[t],i=pt(s,["tkhd"])[0];if(i){let t=i[0];const r=ct(i,0===t?12:20),n=pt(s,["mdia","mdhd"])[0];if(n){t=n[0];const i=ct(n,0===t?12:20),a=pt(s,["mdia","hdlr"])[0];if(a){const t=ht(a.subarray(8,12)),n={soun:P,vide:F}[t];if(n){const t=Et(pt(s,["mdia","minf","stbl","stsd"])[0]);e[r]={timescale:i,type:n},e[n]=c({timescale:i,id:r},t)}}}}}return pt(t,["moov","mvex","trex"]).forEach((t=>{const r=ct(t,4),s=e[r];s&&(s.default={duration:ct(t,12),flags:ct(t,20)})})),e}function Et(t){const e=t.subarray(8),r=e.subarray(86),s=ht(e.subarray(4,8));let i=s;const n="enca"===s||"encv"===s;if(n){const t=pt(e,[s])[0];pt(t.subarray("enca"===s?28:78),["sinf"]).forEach((t=>{const e=pt(t,["schm"])[0];if(e){const r=ht(e.subarray(4,8));if("cbcs"===r||"cenc"===r){const e=pt(t,["frma"])[0];e&&(i=ht(e))}}}))}switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const t=pt(r,["avcC"])[0];i+="."+St(t[1])+St(t[2])+St(t[3]);break}case"mp4a":{const t=pt(e,[s])[0],r=pt(t.subarray(28),["esds"])[0];if(r&&r.length>12){let t=4;if(3!==r[t++])break;t=Tt(r,t),t+=2;const e=r[t++];if(128&e&&(t+=2),64&e&&(t+=r[t++]),4!==r[t++])break;t=Tt(r,t);const s=r[t++];if(64!==s)break;if(i+="."+St(s),t+=12,5!==r[t++])break;t=Tt(r,t);const n=r[t++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&r[t])>>5)),i+="."+a}break}case"hvc1":case"hev1":{const t=pt(r,["hvcC"])[0],e=t[1],s=["","A","B","C"][e>>6],n=31&e,a=ct(t,2),o=(32&e)>>5?"H":"L",l=t[12],d=t.subarray(6,12);i+="."+s+n,i+="."+a.toString(16).toUpperCase(),i+="."+o+l;let h="";for(let t=d.length;t--;){const e=d[t];if(e||h){h="."+e.toString(16).toUpperCase()+h}}i+=h;break}case"dvh1":case"dvhe":{const t=pt(r,["dvcC"])[0],e=t[2]>>1&127,s=t[2]<<5&32|t[3]>>3&31;i+="."+Lt(e)+"."+Lt(s);break}case"vp09":{const t=pt(r,["vpcC"])[0],e=t[4],s=t[5],n=t[6]>>4&15;i+="."+Lt(e)+"."+Lt(s)+"."+Lt(n);break}case"av01":{const t=pt(r,["av1C"])[0],e=t[1]>>>5,s=31&t[1],n=t[2]>>>7?"H":"M",a=(64&t[2])>>6,o=(32&t[2])>>5,l=2===e&&a?o?12:10:a?10:8,d=(16&t[2])>>4,h=(8&t[2])>>3,u=(4&t[2])>>2,c=3&t[2],f=1,g=1,m=1,p=0;i+="."+e+"."+Lt(s)+n+"."+Lt(l)+"."+d+"."+h+u+c+"."+Lt(f)+"."+Lt(g)+"."+Lt(m)+"."+p;break}}return{codec:i,encrypted:n}}function Tt(t,e){const r=e+5;for(;128&t[e++]&&e<r;);return e}function St(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Lt(t){return(t<10?"0":"")+t}function Rt(t,e){if(!t||!e)return t;const r=e.keyId;if(r&&e.isCommonEncryption){pt(t,["moov","trak"]).forEach((t=>{const e=pt(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let s=pt(e,["enca"]);const i=s.length>0;i||(s=pt(e,["encv"])),s.forEach((t=>{pt(i?t.subarray(28):t.subarray(78),["sinf"]).forEach((t=>{const e=function(t){const e=pt(t,["schm"])[0];if(e){const r=ht(e.subarray(4,8));if("cbcs"===r||"cenc"===r)return pt(t,["schi","tenc"])[0]}return D.error("[eme] missing 'schm' box"),null}(t);if(e){const t=e.subarray(8,24);t.some((t=>0!==t))||(D.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${at(t)} -> ${at(r)}`),e.set(r,8))}}))}))}))}return t}function At(t){const e=ct(t,0);let r=8;1&e&&(r+=4),4&e&&(r+=4);let s=0;const i=ct(t,4);for(let n=0;n<i;n++){if(256&e){s+=ct(t,r),r+=4}512&e&&(r+=4),1024&e&&(r+=4),2048&e&&(r+=4)}return s}function bt(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function Dt(t,e){const r=[],s=e.samples,i=e.timescale,n=e.id;let a=!1;return pt(s,["moof"]).map((o=>{const l=o.byteOffset-8;pt(o,["traf"]).map((o=>{const d=pt(o,["tfdt"]).map((t=>{const e=t[0];let r=ct(t,4);return 1===e&&(r*=Math.pow(2,32),r+=ct(t,8)),r/i}))[0];return void 0!==d&&(t=d),pt(o,["tfhd"]).map((d=>{const h=ct(d,4),u=16777215&ct(d,0);let c=0;const f=!!(16&u);let g=0;const m=!!(32&u);let p=8;h===n&&(!!(1&u)&&(p+=8),!!(2&u)&&(p+=4),!!(8&u)&&(c=ct(d,p),p+=4),f&&(g=ct(d,p),p+=4),m&&(p+=4),"video"===e.type&&(a=function(t){if(!t)return!1;const e=t.indexOf("."),r=e<0?t:t.substring(0,e);return"hvc1"===r||"hev1"===r||"dvh1"===r||"dvhe"===r}(e.codec)),pt(o,["trun"]).map((n=>{const o=n[0],d=16777215&ct(n,0),h=!!(1&d);let u=0;const f=!!(4&d),m=!!(256&d);let p=0;const v=!!(512&d);let y=0;const E=!!(1024&d),T=!!(2048&d);let S=0;const L=ct(n,4);let R=8;h&&(u=ct(n,R),R+=4),f&&(R+=4);let A=u+l;for(let l=0;l<L;l++){if(m?(p=ct(n,R),R+=4):p=c,v?(y=ct(n,R),R+=4):y=g,E&&(R+=4),T&&(S=0===o?ct(n,R):gt(n,R),R+=4),e.type===F){let e=0;for(;e<y;){const n=ct(s,A);if(A+=4,_t(a,s[A])){xt(s.subarray(A,A+n),a?2:1,t+S/i,r)}A+=n,e+=n+4}}t+=p/i}})))}))}))})),r}function _t(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function xt(t,e,r,s){const i=kt(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<i.length;){a=0;do{if(n>=i.length)break;l=i[n++],a+=l}while(255===l);o=0;do{if(n>=i.length)break;l=i[n++],o+=l}while(255===l);const t=i.length-n;let e=n;if(o<t)n+=o;else if(o>t){D.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===i[e++]){const t=ut(i,e);if(e+=2,49===t){const t=ct(i,e);if(e+=4,1195456820===t){const t=i[e++];if(3===t){const n=i[e++],o=64&n,l=o?2+3*(31&n):0,d=new Uint8Array(l);if(o){d[0]=n;for(let t=1;t<l;t++)d[t]=i[e++]}s.push({type:t,payloadType:a,pts:r,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let r=0;r<16;r++){const s=i[e++].toString(16);t.push(1==s.length?"0"+s:s),3!==r&&5!==r&&7!==r&&9!==r||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=i[e++];s.push({payloadType:a,pts:r,uuid:t.join(""),userData:st(l),userDataBytes:l})}}}function kt(t){const e=t.byteLength,r=[];let s=1;for(;s<e-2;)0===t[s]&&0===t[s+1]&&3===t[s+2]?(r.push(s+2),s+=2):s++;if(0===r.length)return t;const i=e-r.length,n=new Uint8Array(i);let a=0;for(s=0;s<i;a++,s++)a===r[0]&&(a++,r.shift()),n[s]=t[a];return n}class wt{static clearKeyUriToKeyIdMap(){}constructor(t,e,r,s=[1],i=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=e,this.keyFormat=r,this.keyFormatVersions=s,this.iv=i,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&"AES-128"!==t}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof t&&("AES-128"!==this.method||this.iv||D.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);const e=function(t){const e=new Uint8Array(16);for(let r=12;r<16;r++)e[r]=t>>8*(15-r)&255;return e}(t);return new wt(this.method,this.uri,"identity",this.keyFormatVersions,e)}return this}}function It(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const Ct={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,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Pt(t,e,r=!0){return!t.split(",").some((t=>!Ft(t,e,r)))}function Ft(t,e,r=!0){var s;const i=It(r);return null!=(s=null==i?void 0:i.isTypeSupported(Mt(t,e)))&&s}function Mt(t,e){return`${e}/mp4;codecs="${t}"`}function Ot(t){if(t){const e=t.substring(0,4);return Ct.video[e]}return 2}function Nt(t){return t.split(",").reduce(((t,e)=>{const r=Ct.video[e];return r?(2*r+t)/(t?3:2):(Ct.audio[e]+t)/(t?2:1)}),0)}const Bt={};const Ut=/flac|opus/i;function $t(t,e=!0){return t.replace(Ut,(t=>function(t,e=!0){if(Bt[t])return Bt[t];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let s=0;s<r.length;s++)if(Ft(r[s],"audio",e))return Bt[t]=r[s],r[s];return t}(t.toLowerCase(),e)))}function Gt(t,e){return t&&"mp4a"!==t?t:e}const Ht=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Vt=/#EXT-X-MEDIA:(.*)/g,Kt=/^#EXT(?:INF|-X-TARGETDURATION):/m,Wt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Yt=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class jt{static findGroup(t,e){for(let r=0;r<t.length;r++){const s=t[r];if(s.id===e)return s}}static resolve(t,e){return h.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Kt.test(t)}static parseMasterPlaylist(t,e){const r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},s=[];let i;for(Ht.lastIndex=0;null!=(i=Ht.exec(t));)if(i[1]){var n;const t=new k(i[1]),a=i[2],o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:jt.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Xt(t.CODECS,o),null!=(n=o.unknownCodecs)&&n.length||s.push(o),r.levels.push(o)}else if(i[3]){const t=i[3],s=i[4];switch(t){case"SESSION-DATA":{const t=new k(s),e=t["DATA-ID"];e&&(null===r.sessionData&&(r.sessionData={}),r.sessionData[e]=t);break}case"SESSION-KEY":{const t=qt(s,e);t.encrypted&&t.isSupported()?(null===r.sessionKeys&&(r.sessionKeys=[]),r.sessionKeys.push(t)):D.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${s}"`);break}case"DEFINE":break;case"CONTENT-STEERING":{const t=new k(s);r.contentSteering={uri:jt.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":r.startTimeOffset=zt(s)}}const a=s.length>0&&s.length<r.levels.length;return r.levels=a?s:r.levels,0===r.levels.length&&(r.playlistParsingError=new Error("no levels found in manifest")),r}static parseMasterPlaylistMedia(t,e,r){let s;const i={},n=r.levels,a={AUDIO:n.map((t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec}))),SUBTITLES:n.map((t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec}))),"CLOSED-CAPTIONS":[]};let o=0;for(Vt.lastIndex=0;null!==(s=Vt.exec(t));){const t=new k(s[1]),r=t.TYPE;if(r){const s=a[r],n=i[r]||[];i[r]=n;const l=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],h=t.CHANNELS,u=t.CHARACTERISTICS,c=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:r,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?jt.resolve(t.URI,e):""};if(d&&(f.assocLang=d),h&&(f.channels=h),u&&(f.characteristics=u),c&&(f.instreamId=c),null!=s&&s.length){const t=jt.findGroup(s,f.groupId)||s[0];Qt(f,t,"audioCodec"),Qt(f,t,"textCodec")}n.push(f)}}return i}static parseLevelPlaylist(t,e,r,s,i,n){const a=new U(e),o=a.fragments;let l,d,h,u=null,c=0,f=0,g=0,v=0,y=null,E=new N(s,e),T=-1,S=!1,L=null;for(Wt.lastIndex=0,a.m3u8=t,a.hasVariableRefs=!1;null!==(l=Wt.exec(t));){S&&(S=!1,E=new N(s,e),E.start=g,E.sn=c,E.cc=v,E.level=r,u&&(E.initSegment=u,E.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null,L&&(E.setByteRange(L),L=null)));const t=l[1];if(t){E.duration=parseFloat(t);const e=(" "+l[2]).slice(1);E.title=e||null,E.tagList.push(e?["INF",t,e]:["INF",t])}else if(l[3]){if(p(E.duration)){E.start=g,h&&te(E,h,a),E.sn=c,E.level=r,E.cc=v,o.push(E);const t=(" "+l[3]).slice(1);E.relurl=t,Jt(E,y),y=E,g+=E.duration,c++,f=0,S=!0}}else if(l[4]){const t=(" "+l[4]).slice(1);y?E.setByteRange(t,y):E.setByteRange(t)}else if(l[5])E.rawProgramDateTime=(" "+l[5]).slice(1),E.tagList.push(["PROGRAM-DATE-TIME",E.rawProgramDateTime]),-1===T&&(T=o.length);else{if(l=l[0].match(Yt),!l){D.warn("No matches on slow regex match for level playlist!");continue}for(d=1;d<l.length&&void 0===l[d];d++);const t=(" "+l[d]).slice(1),i=(" "+l[d+1]).slice(1),n=l[d+2]?(" "+l[d+2]).slice(1):"";switch(t){case"PLAYLIST-TYPE":a.type=i.toUpperCase();break;case"MEDIA-SEQUENCE":c=a.startSN=parseInt(i);break;case"SKIP":{const t=new k(i),e=t.decimalInteger("SKIPPED-SEGMENTS");if(p(e)){a.skippedSegments=e;for(let t=e;t--;)o.unshift(null);c+=e}const r=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(a.recentlyRemovedDateranges=r.split("\t"));break}case"TARGETDURATION":a.targetduration=Math.max(parseInt(i),1);break;case"VERSION":a.version=parseInt(i);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":case"DEFINE":break;case"ENDLIST":a.live=!1;break;case"#":(i||n)&&E.tagList.push(n?[i,n]:[i]);break;case"DISCONTINUITY":v++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([t]);break;case"BITRATE":E.tagList.push([t,i]);break;case"DATERANGE":{const t=new k(i),e=new I(t,a.dateRanges[t.ID]);e.isValid||a.skippedSegments?a.dateRanges[e.id]=e:D.warn(`Ignoring invalid DATERANGE tag: "${i}"`),E.tagList.push(["EXT-X-DATERANGE",i]);break}case"DISCONTINUITY-SEQUENCE":v=parseInt(i);break;case"KEY":{const t=qt(i,e);if(t.isSupported()){if("NONE"===t.method){h=void 0;break}h||(h={}),h[t.keyFormat]&&(h=m({},h)),h[t.keyFormat]=t}else D.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${i}"`);break}case"START":a.startTimeOffset=zt(i);break;case"MAP":{const t=new k(i);if(E.duration){const i=new N(s,e);Zt(i,t,r,h),u=i,E.initSegment=u,u.rawProgramDateTime&&!E.rawProgramDateTime&&(E.rawProgramDateTime=u.rawProgramDateTime)}else{const e=E.byteRangeEndOffset;if(e){const t=E.byteRangeStartOffset;L=`${e-t}@${t}`}else L=null;Zt(E,t,r,h),u=E,S=!0}break}case"SERVER-CONTROL":{const t=new k(i);a.canBlockReload=t.bool("CAN-BLOCK-RELOAD"),a.canSkipUntil=t.optionalFloat("CAN-SKIP-UNTIL",0),a.canSkipDateRanges=a.canSkipUntil>0&&t.bool("CAN-SKIP-DATERANGES"),a.partHoldBack=t.optionalFloat("PART-HOLD-BACK",0),a.holdBack=t.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const t=new k(i);a.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=a.partList;t||(t=a.partList=[]);const r=f>0?t[t.length-1]:void 0,s=f++,n=new k(i),o=new B(n,E,e,s,r);t.push(o),E.duration+=o.duration;break}case"PRELOAD-HINT":{const t=new k(i);a.preloadHint=t;break}case"RENDITION-REPORT":{const t=new k(i);a.renditionReports=a.renditionReports||[],a.renditionReports.push(t);break}default:D.warn(`line parsed but not handled: ${l}`)}}}y&&!y.relurl?(o.pop(),g-=y.duration,a.partList&&(a.fragmentHint=y)):a.partList&&(Jt(E,y),E.cc=v,a.fragmentHint=E,h&&te(E,h,a));const R=o.length,A=o[0],b=o[R-1];if(g+=a.skippedSegments*a.targetduration,g>0&&R&&b){a.averagetargetduration=g/R;const t=b.sn;a.endSN="initSegment"!==t?t:0,a.live||(b.endList=!0),A&&(a.startCC=A.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(g+=a.fragmentHint.duration),a.totalduration=g,a.endCC=v,T>0&&function(t,e){let r=t[e];for(let s=e;s--;){const e=t[s];if(!e)return;e.programDateTime=r.programDateTime-1e3*e.duration,r=e}}(o,T),a}}function qt(t,e,r){var s,i;const n=new k(t),a=null!=(s=n.METHOD)?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),d=n.KEYFORMATVERSIONS,h=null!=(i=n.KEYFORMAT)?i:"identity";o&&n.IV&&!l&&D.error(`Invalid IV: ${n.IV}`);const u=o?jt.resolve(o,e):"",c=(d||"1").split("/").map(Number).filter(Number.isFinite);return new wt(a,u,h,c,l)}function zt(t){const e=new k(t).decimalFloatingPoint("TIME-OFFSET");return p(e)?e:null}function Xt(t,e){let r=(t||"").split(/[ ,]+/).filter((t=>t));["video","audio","text"].forEach((t=>{const s=r.filter((e=>function(t,e){const r=Ct[e];return!!r&&!!r[t.slice(0,4)]}(e,t)));s.length&&(e[`${t}Codec`]=s.join(","),r=r.filter((t=>-1===s.indexOf(t))))})),e.unknownCodecs=r}function Qt(t,e,r){const s=e[r];s&&(t[r]=s)}function Jt(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),p(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Zt(t,e,r,s){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=r,t.sn="initSegment",s&&(t.levelkeys=s),t.initSegment=null}function te(t,e,r){t.levelkeys=e;const{encryptedFragments:s}=r;s.length&&s[s.length-1].levelkeys===e||!Object.keys(e).some((t=>e[t].isCommonEncryption))||s.push(t)}var ee="manifest",re="level",se="audioTrack",ie="subtitleTrack",ne={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function ae(t){const{type:e}=t;switch(e){case se:return ne.AUDIO;case ie:return ne.SUBTITLE;default:return ne.MAIN}}function oe(t,e){let r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}class le{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.LEVEL_LOADING,this.onLevelLoading,this),t.on(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.LEVEL_LOADING,this.onLevelLoading,this),t.off(E.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(E.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,r=e.pLoader,s=e.loader,i=new(r||s)(e);return this.loaders[t.type]=i,i}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:r}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ee,url:r,deliveryDirectives:null})}onLevelLoading(t,e){const{id:r,level:s,pathwayId:i,url:n,deliveryDirectives:a}=e;this.load({id:r,level:s,pathwayId:i,responseType:"text",type:re,url:n,deliveryDirectives:a})}onAudioTrackLoading(t,e){const{id:r,groupId:s,url:i,deliveryDirectives:n}=e;this.load({id:r,groupId:s,level:null,responseType:"text",type:se,url:i,deliveryDirectives:n})}onSubtitleTrackLoading(t,e){const{id:r,groupId:s,url:i,deliveryDirectives:n}=e;this.load({id:r,groupId:s,level:null,responseType:"text",type:ie,url:i,deliveryDirectives:n})}load(t){var e;const r=this.hls.config;let s,i=this.getInternalLoader(t);if(i){const e=i.context;if(e&&e.url===t.url&&e.level===t.level)return void D.trace("[playlist-loader]: playlist request ongoing");D.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),i.abort()}if(s=t.type===ee?r.manifestLoadPolicy.default:m({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(t),p(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===re&&null!==t.level?e=this.hls.levels[t.level].details:t.type===se&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===ie&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,r=e.targetduration;if(t&&r){const e=1e3*Math.max(3*t,.8*r);s=m({},s,{maxTimeToFirstByteMs:Math.min(e,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,s.maxTimeToFirstByteMs)})}}}const n=s.errorRetry||s.timeoutRetry||{},a={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},o={onSuccess:(t,e,r,s)=>{const i=this.getInternalLoader(r);this.resetInternalLoader(r.type);const n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),jt.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(t,e,r,s||null,i):this.handleMasterPlaylist(t,e,r,s)):this.handleManifestParsingError(t,r,new Error("no EXTM3U delimiter"),s||null,e)},onError:(t,e,r,s)=>{this.handleNetworkError(e,r,!1,t,s)},onTimeout:(t,e,r)=>{this.handleNetworkError(e,r,!0,void 0,t)}};i.load(t,a,o)}handleMasterPlaylist(t,e,r,s){const i=this.hls,n=t.data,a=oe(t,r),o=jt.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,r,o.playlistParsingError,s,e);const{contentSteering:l,levels:d,sessionData:h,sessionKeys:u,startTimeOffset:c,variableList:f}=o;this.variableList=f;const{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=jt.parseMasterPlaylistMedia(n,a,o);if(g.length){g.some((t=>!t.url))||!d[0].audioCodec||d[0].attrs.AUDIO||(D.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new k({}),bitrate:0,url:""}))}i.trigger(E.MANIFEST_LOADED,{levels:d,audioTracks:g,subtitles:m,captions:p,contentSteering:l,url:a,stats:e,networkDetails:s,sessionData:h,sessionKeys:u,startTimeOffset:c,variableList:f})}handleTrackOrLevelPlaylist(t,e,r,s,i){const n=this.hls,{id:a,level:o,type:l}=r,d=oe(t,r),h=p(o)?o:p(a)?a:0,u=ae(r),c=jt.parseLevelPlaylist(t.data,d,h,u,0,this.variableList);if(l===ee){const t={attrs:new k({}),bitrate:0,details:c,name:"",url:d};n.trigger(E.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:d,stats:e,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),r.levelDetails=c,this.handlePlaylistLoaded(c,t,e,r,s,i)}handleManifestParsingError(t,e,r,s,i){this.hls.trigger(E.ERROR,{type:T.NETWORK_ERROR,details:S.MANIFEST_PARSING_ERROR,fatal:e.type===ee,url:t.url,err:r,error:r,reason:r.message,response:t,context:e,networkDetails:s,stats:i})}handleNetworkError(t,e,r=!1,s,i){let n=`A network ${r?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===re?n+=`: ${t.level} id: ${t.id}`:t.type!==se&&t.type!==ie||(n+=` id: ${t.id} group-id: "${t.groupId}"`);const a=new Error(n);D.warn(`[playlist-loader]: ${n}`);let o=S.UNKNOWN,l=!1;const d=this.getInternalLoader(t);switch(t.type){case ee:o=r?S.MANIFEST_LOAD_TIMEOUT:S.MANIFEST_LOAD_ERROR,l=!0;break;case re:o=r?S.LEVEL_LOAD_TIMEOUT:S.LEVEL_LOAD_ERROR,l=!1;break;case se:o=r?S.AUDIO_TRACK_LOAD_TIMEOUT:S.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case ie:o=r?S.SUBTITLE_TRACK_LOAD_TIMEOUT:S.SUBTITLE_LOAD_ERROR,l=!1}d&&this.resetInternalLoader(t.type);const h={type:T.NETWORK_ERROR,details:o,fatal:l,url:t.url,loader:d,context:t,error:a,networkDetails:e,stats:i};if(s){const r=(null==e?void 0:e.url)||t.url;h.response=c({url:r,data:void 0},s)}this.hls.trigger(E.ERROR,h)}handlePlaylistLoaded(t,e,r,s,i,n){const a=this.hls,{type:o,level:l,id:d,groupId:h,deliveryDirectives:u}=s,c=oe(e,s),f=ae(s),g="number"==typeof s.level&&f===ne.MAIN?l:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void a.trigger(E.ERROR,{type:T.NETWORK_ERROR,details:S.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:t,reason:t.message,response:e,context:s,level:g,parent:f,networkDetails:i,stats:r})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const m=t.playlistParsingError;if(m)a.trigger(E.ERROR,{type:T.NETWORK_ERROR,details:S.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:e,context:s,level:g,parent:f,networkDetails:i,stats:r});else switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case ee:case re:a.trigger(E.LEVEL_LOADED,{details:t,level:g||0,id:d||0,stats:r,networkDetails:i,deliveryDirectives:u});break;case se:a.trigger(E.AUDIO_TRACK_LOADED,{details:t,id:d||0,groupId:h||"",stats:r,networkDetails:i,deliveryDirectives:u});break;case ie:a.trigger(E.SUBTITLE_TRACK_LOADED,{details:t,id:d||0,groupId:h||"",stats:r,networkDetails:i,deliveryDirectives:u})}}}function de(t,e){let r;try{r=new Event("addtrack")}catch(t){r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function he(t,e,r,s){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&t.cues.length>0){const i=function(t,e,r){const s=[],i=function(t,e){if(e<t[0].startTime)return 0;const r=t.length-1;if(e>t[r].endTime)return-1;let s=0,i=r;for(;s<=i;){const n=Math.floor((i+s)/2);if(e<t[n].startTime)i=n-1;else{if(!(e>t[n].startTime&&s<r))return n;s=n+1}}return t[s].startTime-e<e-t[i].startTime?s:i}(t,e);if(i>-1)for(let n=i,a=t.length;n<a;n++){const i=t[n];if(i.startTime>=e&&i.endTime<=r)s.push(i);else if(i.startTime>r)return s}return s}(t.cues,e,r);for(let e=0;e<i.length;e++)s&&!s(i[e])||t.removeCue(i[e])}"disabled"===i&&(t.mode=i)}var ue={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};function ce(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function fe(t,e,r,s,i){let n=new t(e,r,"");try{n.value=s,i&&(n.type=i)}catch(a){n=new t(e,r,JSON.stringify(i?c({type:i},s):s))}return n}const ge=(()=>{const t=ce();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function me(t,e){return t.getTime()/1e3-e}class pe{constructor(t){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:t}=this;t.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(E.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(!function(t){const e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(let e=t.cues.length;e--;)t.removeCue(t.cues[e]);"disabled"===e&&(t.mode=e)}(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const e=this.getID3Track(t.textTracks);return e.mode="hidden",e}getID3Track(t){if(this.media){for(let e=0;e<t.length;e++){const r=t[e];if("metadata"===r.kind&&"id3"===r.label)return de(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:r,enableID3MetadataCues:s}}}=this;if(!r&&!s)return;const{samples:i}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=ce();if(n)for(let t=0;t<i.length;t++){const e=i[t].type;if(e===ue.emsg&&!r||!s)continue;const a=Q(i[t].data);if(a){const r=i[t].pts;let s=r+i[t].duration;s>ge&&(s=ge);s-r<=0&&(s=r+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!z(i)){this.updateId3CueEnds(r,e);const t=fe(n,r,s,i,e);t&&this.id3Track.addCue(t)}}}}}updateId3CueEnds(t,e){var r;const s=null==(r=this.id3Track)?void 0:r.cues;if(s)for(let r=s.length;r--;){const i=s[r];i.type===e&&i.startTime<t&&i.endTime===ge&&(i.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:r,type:s}){const{id3Track:i,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(i&&(a||o)){let t;t="audio"===s?t=>t.type===ue.audioId3&&o:"video"===s?t=>t.type===ue.emsg&&a:t=>t.type===ue.audioId3&&o||t.type===ue.emsg&&a,he(i,e,r,t)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:r,id3Track:s}=this,{dateRanges:i}=e,n=Object.keys(i);if(s){const t=Object.keys(r).filter((t=>!n.includes(t)));for(let e=t.length;e--;){const i=t[e];Object.keys(r[i].cues).forEach((t=>{s.removeCue(r[i].cues[t])})),delete r[i]}}const a=e.fragments[e.fragments.length-1];if(0===n.length||!p(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,l=ce();for(let t=0;t<n.length;t++){const e=n[t],s=i[e],a=me(s.startDate,o),u=r[e],c=(null==u?void 0:u.cues)||{};let f=(null==u?void 0:u.durationKnown)||!1,g=ge;const m=s.endDate;if(m)g=me(m,o),f=!0;else if(s.endOnNext&&!f){const t=n.reduce(((t,e)=>{if(e!==s.id){const r=i[e];if(r.class===s.class&&r.startDate>s.startDate&&(!t||s.startDate<t.startDate))return r}return t}),null);t&&(g=me(t.startDate,o),f=!0)}const p=Object.keys(s.attr);for(let t=0;t<p.length;t++){const r=p[t];if("ID"===(h=r)||"CLASS"===h||"START-DATE"===h||"DURATION"===h||"END-DATE"===h||"END-ON-NEXT"===h)continue;const i=c[r];if(i)f&&!u.durationKnown&&(i.endTime=g);else if(l){let t=s.attr[r];w(r)&&(d=t,t=Uint8Array.from(d.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const i=fe(l,a,g,{key:r,data:t},ue.dateRange);i&&(i.id=e,this.id3Track.addCue(i),c[r]=i)}}r[e]={cues:c,dateRange:s,durationKnown:f}}var d,h}}class ve{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=t,this.config=t.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:t,levelDetails:e}=this;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}get targetLatency(){const{levelDetails:t}=this;if(null===t)return null;const{holdBack:e,partHoldBack:r,targetduration:s}=t,{liveSyncDuration:i,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&r||e;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==i?i:n*s);const d=s;return l+Math.min(1*this.stallCount,d)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,r=this.levelDetails;if(null===t||null===e||null===r)return null;const s=r.edge,i=t-e-this.edgeStalled,n=s-r.totalduration,a=s-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,i),a)}get drift(){const{levelDetails:t}=this;return null===t?1:t.drift}get edgeStalled(){const{levelDetails:t}=this;if(null===t)return 0;const e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t,levelDetails:e}=this;if(!t||!e)return 0;const r=t.buffered.length;return(r?t.buffered.end(r-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(E.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(E.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(E.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:e}){this.levelDetails=e,e.advanced&&this.timeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(t,e){var r;e.details===S.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(r=this.levelDetails)&&r.live&&D.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:t,levelDetails:e}=this;if(!t||!e)return;this.currentTime=t.currentTime;const r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:i}=this.config;if(!s||1===i||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=r-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,i)),r=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;t.playbackRate=Math.min(e,Math.max(1,r))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}estimateLiveEdge(){const{levelDetails:t}=this;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}const ye=["NONE","TYPE-0","TYPE-1",null];const Ee=["SDR","PQ","HLG"];var Te={No:"",Yes:"YES",v2:"v2"};class Se{constructor(t,e,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=r}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href}}class Le{constructor(t){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.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.codecSet=[t.videoCodec,t.audioCodec].filter((t=>!!t)).map((t=>t.substring(0,4))).join(","),this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return Re(this._audioGroups,t)}hasSubtitleGroup(t){return Re(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function Re(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Ae(t,e){const r=e.startPTS;if(p(r)){let s,i=0;e.sn>t.sn?(i=r-t.start,s=t):(i=t.start-r,s=e),s.duration!==i&&(s.duration=i)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function be(t,e,r,s,i,n){s-r<=0&&(D.warn("Fragment should have a positive duration",e),s=r+e.duration,n=i+e.duration);let a=r,o=s;const l=e.startPTS,d=e.endPTS;if(p(l)){const t=Math.abs(l-r);p(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,a=Math.max(r,l),r=Math.min(r,l),i=Math.min(i,e.startDTS),o=Math.min(s,d),s=Math.max(s,d),n=Math.max(n,e.endDTS)}const h=r-e.start;0!==e.start&&(e.start=r),e.duration=s-e.start,e.startPTS=r,e.maxStartPTS=a,e.startDTS=i,e.endPTS=s,e.minEndPTS=o,e.endDTS=n;const u=e.sn;if(!t||u<t.startSN||u>t.endSN)return 0;let c;const f=u-t.startSN,g=t.fragments;for(g[f]=e,c=f;c>0;c--)Ae(g[c],g[c-1]);for(c=f;c<g.length-1;c++)Ae(g[c],g[c+1]);return t.fragmentHint&&Ae(g[g.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,h}function De(t,e){let r=null;const s=t.fragments;for(let t=s.length-1;t>=0;t--){const e=s[t].initSegment;if(e){r=e;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let i,n=0;if(function(t,e,r){const s=e.skippedSegments,i=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(s?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let t=i;t<=n;t++){const i=l[a+t];let n=o[t];s&&!n&&t<s&&(n=e.fragments[t]=i),i&&n&&r(i,n)}}(t,e,((t,s)=>{t.relurl&&(n=t.cc-s.cc),p(t.startPTS)&&p(t.endPTS)&&(s.start=s.startPTS=t.startPTS,s.startDTS=t.startDTS,s.maxStartPTS=t.maxStartPTS,s.endPTS=t.endPTS,s.endDTS=t.endDTS,s.minEndPTS=t.minEndPTS,s.duration=t.endPTS-t.startPTS,s.duration&&(i=s),e.PTSKnown=e.alignedSliding=!0),s.elementaryStreams=t.elementaryStreams,s.loader=t.loader,s.stats=t.stats,t.initSegment&&(s.initSegment=t.initSegment,r=t.initSegment)})),r){(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach((t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=r)?void 0:e.relurl)||(t.initSegment=r)}))}if(e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some((t=>!t)),e.deltaUpdateFailed){D.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=e.skippedSegments;t--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=function(t,e,r){const s=m({},t);r&&r.forEach((t=>{delete s[t]}));return Object.keys(e).forEach((t=>{const r=new I(e[t].attr,s[t]);r.isValid?s[t]=r:D.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[t].attr)}"`)})),s}(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(n){D.warn("discontinuity sliding from playlist, take drift into account");for(let t=0;t<a.length;t++)a[t].cc+=n}e.skippedSegments&&(e.startCC=e.fragments[0].cc),function(t,e,r){if(t&&e){let s=0;for(let i=0,n=t.length;i<=n;i++){const n=t[i],a=e[i+s];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?r(n,a):s--}}}(t.partList,e.partList,((t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats})),i?be(e,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):_e(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const t=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=t),e.driftEndTime=o,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function _e(t,e){const r=e.startSN+e.skippedSegments-t.startSN,s=t.fragments;r<0||r>=s.length||function(t,e){if(e){const r=t.fragments;for(let s=t.skippedSegments;s<r.length;s++)r[s].start+=e;t.fragmentHint&&(t.fragmentHint.start+=e)}}(e,s[r].start)}function xe(t,e,r){var s;return null!=t&&t.details?ke(null==(s=t.details)?void 0:s.partList,e,r):null}function ke(t,e,r){if(t)for(let s=t.length;s--;){const i=t[s];if(i.index===r&&i.fragment.sn===e)return i}return null}function we(t){t.forEach(((t,e)=>{const{details:r}=t;null!=r&&r.fragments&&r.fragments.forEach((t=>{t.level=e}))}))}function Ie(t){switch(t.details){case S.FRAG_LOAD_TIMEOUT:case S.KEY_LOAD_TIMEOUT:case S.LEVEL_LOAD_TIMEOUT:case S.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ce(t,e){const r=Ie(e);return t.default[(r?"timeout":"error")+"Retry"]}function Pe(t,e){const r="linear"===t.backoff?1:Math.pow(2,e);return Math.min(r*t.retryDelayMs,t.maxRetryDelayMs)}function Fe(t){return c(c({},t),{errorRetry:null,timeoutRetry:null})}function Me(t,e,r,s){if(!t)return!1;const i=null==s?void 0:s.code,n=e<t.maxNumRetry&&(function(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}(i)||!!r);return t.shouldRetry?t.shouldRetry(t,e,r,s,n):n}const Oe=function(t,e){let r=0,s=t.length-1,i=null,n=null;for(;r<=s;){i=(r+s)/2|0,n=t[i];const a=e(n);if(a>0)r=i+1;else{if(!(a<0))return n;s=i-1}}return null};function Ne(t,e,r=0,s=0){let i=null;if(t){i=e[t.sn-e[0].sn+1]||null;const s=t.endDTS-r;s>0&&s<15e-7&&(r+=15e-7)}else 0===r&&0===e[0].start&&(i=e[0]);if(i&&(!t||t.level===i.level)&&0===Be(r,s,i))return i;const n=Oe(e,Be.bind(null,r,s));return!n||n===t&&i?i:n}function Be(t=0,e=0,r){if(r.start<=t&&r.start+r.duration>t)return 0;const s=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-s<=t?1:r.start-s>t&&r.start?-1:0}function Ue(t,e,r){const s=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-s>t}var $e={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Ge={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class He{constructor(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=D.log.bind(D,"[info]:"),this.warn=D.warn.bind(D,"[warning]:"),this.error=D.error.bind(D,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(E.ERROR,this.onError,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(E.ERROR,this.onError,this),t.off(E.ERROR,this.onErrorOut,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===ne.MAIN?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var r,s;if(e.fatal)return;const i=this.hls,n=e.context;switch(e.details){case S.FRAG_LOAD_ERROR:case S.FRAG_LOAD_TIMEOUT:case S.KEY_LOAD_ERROR:case S.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case S.FRAG_PARSING_ERROR:if(null!=(r=e.frag)&&r.gap)return void(e.errorAction={action:$e.DoNothing,flags:Ge.None});case S.FRAG_GAP:case S.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=$e.SendAlternateToPenaltyBox);case S.LEVEL_EMPTY_ERROR:case S.LEVEL_PARSING_ERROR:{var a,o;const t=e.parent===ne.MAIN?e.level:i.loadLevel;e.details===S.LEVEL_EMPTY_ERROR&&null!=(a=e.context)&&null!=(o=a.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case S.LEVEL_LOAD_ERROR:case S.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.level)));case S.AUDIO_TRACK_LOAD_ERROR:case S.AUDIO_TRACK_LOAD_TIMEOUT:case S.SUBTITLE_LOAD_ERROR:case S.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const t=i.levels[i.loadLevel];if(t&&(n.type===se&&t.hasAudioGroup(n.groupId)||n.type===ie&&t.hasSubtitleGroup(n.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.loadLevel),e.errorAction.action=$e.SendAlternateToPenaltyBox,void(e.errorAction.flags=Ge.MoveAllAlternatesMatchingHost)}return;case S.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=i.levels[i.loadLevel],r=null==t?void 0:t.attrs["HDCP-LEVEL"];r?e.errorAction={action:$e.SendAlternateToPenaltyBox,flags:Ge.MoveAllAlternatesMatchingHDCP,hdcpLevel:r}:this.keySystemError(e)}return;case S.BUFFER_ADD_CODEC_ERROR:case S.REMUX_ALLOC_ERROR:case S.BUFFER_APPEND_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(s=e.level)?s:i.loadLevel));case S.INTERNAL_EXCEPTION:case S.BUFFER_APPENDING_ERROR:case S.BUFFER_FULL_ERROR:case S.LEVEL_SWITCH_ERROR:case S.BUFFER_STALLED_ERROR:case S.BUFFER_SEEK_OVER_HOLE:case S.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:$e.DoNothing,flags:Ge.None})}e.type===T.KEY_SYSTEM_ERROR&&this.keySystemError(e)}keySystemError(t){const e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e)}getPlaylistRetryOrSwitchAction(t,e){const r=Ce(this.hls.config.playlistLoadPolicy,t),s=this.playlistError++;if(Me(r,s,Ie(t),t.response))return{action:$e.RetryRequest,flags:Ge.None,retryConfig:r,retryCount:s};const i=this.getLevelSwitchAction(t,e);return r&&(i.retryConfig=r,i.retryCount=s),i}getFragRetryOrSwitchAction(t){const e=this.hls,r=this.getVariantLevelIndex(t.frag),s=e.levels[r],{fragLoadPolicy:i,keyLoadPolicy:n}=e.config,a=Ce(t.details.startsWith("key")?n:i,t),o=e.levels.reduce(((t,e)=>t+e.fragmentError),0);if(s){t.details!==S.FRAG_GAP&&s.fragmentError++;if(Me(a,o,Ie(t),t.response))return{action:$e.RetryRequest,flags:Ge.None,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,r);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const r=this.hls;null==e&&(e=r.loadLevel);const s=this.hls.levels[e];if(s){var i,n;const e=t.details;s.loadError++,e===S.BUFFER_APPEND_ERROR&&s.fragmentError++;let l=-1;const{levels:d,loadLevel:h,minAutoLevel:u,maxAutoLevel:c}=r;r.autoLevelEnabled||(r.loadLevel=-1);const f=null==(i=t.frag)?void 0:i.type,g=(f===ne.AUDIO&&e===S.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===S.BUFFER_ADD_CODEC_ERROR||e===S.BUFFER_APPEND_ERROR))&&d.some((({audioCodec:t})=>s.audioCodec!==t)),m="video"===t.sourceBufferName&&(e===S.BUFFER_ADD_CODEC_ERROR||e===S.BUFFER_APPEND_ERROR)&&d.some((({codecSet:t,audioCodec:e})=>s.codecSet!==t&&s.audioCodec===e)),{type:p,groupId:v}=null!=(n=t.context)?n:{};for(let r=d.length;r--;){const i=(r+h)%d.length;if(i!==h&&i>=u&&i<=c&&0===d[i].loadError){var a,o;const r=d[i];if(e===S.FRAG_GAP&&t.frag){const e=d[i].details;if(e){const r=Ne(t.frag,e.fragments,t.frag.start);if(null!=r&&r.gap)continue}}else{if(p===se&&r.hasAudioGroup(v)||p===ie&&r.hasSubtitleGroup(v))continue;if(f===ne.AUDIO&&null!=(a=s.audioGroups)&&a.some((t=>r.hasAudioGroup(t)))||f===ne.SUBTITLE&&null!=(o=s.subtitleGroups)&&o.some((t=>r.hasSubtitleGroup(t)))||g&&s.audioCodec===r.audioCodec||!g&&s.audioCodec!==r.audioCodec||m&&s.codecSet===r.codecSet)continue}l=i;break}}if(l>-1&&r.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:$e.SendAlternateToPenaltyBox,flags:Ge.None,nextAutoLevel:l}}return{action:$e.SendAlternateToPenaltyBox,flags:Ge.MoveAllAlternatesMatchingHost}}onErrorOut(t,e){var r;switch(null==(r=e.errorAction)?void 0:r.action){case $e.DoNothing:break;case $e.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===S.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0;case $e.RetryRequest:}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,r=t.errorAction;if(!r)return;const{flags:s,hdcpLevel:i,nextAutoLevel:n}=r;switch(s){case Ge.None:this.switchLevel(t,n);break;case Ge.MoveAllAlternatesMatchingHDCP:i&&(e.maxHdcpLevel=ye[ye.indexOf(i)-1],r.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}r.resolved||this.switchLevel(t,n)}switchLevel(t,e){void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}}class Ve{constructor(t,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=D.log.bind(D,`${e}:`),this.warn=D.warn.bind(D,`${e}:`),this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e){const r=null==e?void 0:e.renditionReports;if(r){let s=-1;for(let i=0;i<r.length;i++){const n=r[i];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){D.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){s=i;break}a===t.substring(0,a.length)&&(s=i)}if(-1!==s){const t=r[s],i=parseInt(t["LAST-MSN"])||(null==e?void 0:e.lastPartSn);let n=parseInt(t["LAST-PART"])||(null==e?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);n>=0&&t>e.partTarget&&(n+=1)}return new Se(i,n>=0?n:void 0,Te.No)}}}loadPlaylist(t){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}shouldReloadPlaylist(t){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(t)}playlistLoaded(t,e,r){const{details:s,stats:i}=e,n=self.performance.now(),a=i.loading.first?Math.max(0,n-i.loading.first):0;if(s.advancedDateTime=Date.now()-a,s.live||null!=r&&r.live){if(s.reloaded(r),r&&this.log(`live playlist ${t} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),r&&s.fragments.length>0&&De(r,s),!this.canLoad||!s.live)return;let a,o,l;if(s.canBlockReload&&s.endSN&&s.advanced){const t=this.hls.config.lowLatencyMode,i=s.lastPartSn,n=s.endSN,d=s.lastPartIndex,h=i===n;-1!==d?(o=h?n+1:i,l=h?t?0:d:d+1):o=n+1;const u=s.age,c=u+s.ageHeader;let f=Math.min(c-s.partTarget,1.5*s.targetduration);if(f>0){if(r&&f>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${f} with playlist age: ${s.age}`),f=0;else{const t=Math.floor(f/s.targetduration);if(o+=t,void 0!==l){l+=Math.round(f%s.targetduration/s.partTarget)}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${f} skip sn ${t} to part ${l}`)}s.tuneInGoal=f}if(a=this.getDeliveryDirectives(s,e.deliveryDirectives,o,l),t||!h)return void this.loadPlaylist(a)}else(s.canBlockReload||s.canSkipUntil)&&(a=this.getDeliveryDirectives(s,e.deliveryDirectives,o,l));const d=this.hls.mainForwardBufferInfo,h=d?d.end-d.len:0,u=function(t,e=1/0){let r=1e3*t.targetduration;if(t.updated){const s=t.fragments,i=4;if(s.length&&r*i>e){const t=1e3*s[s.length-1].duration;t<r&&(r=t)}}else r/=2;return Math.round(r)}(s,1e3*(s.edge-h));s.updated&&n>this.requestScheduled+u&&(this.requestScheduled=i.loading.start),void 0!==o&&s.canBlockReload?this.requestScheduled=i.loading.first+u-(1e3*s.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+u<n?this.requestScheduled=n:this.requestScheduled-n<=0&&(this.requestScheduled+=u);let c=this.requestScheduled-n;c=Math.max(0,c),this.log(`reload live playlist ${t} in ${Math.round(c)} ms`),this.timer=self.setTimeout((()=>this.loadPlaylist(a)),c)}else this.clearTimer()}getDeliveryDirectives(t,e,r,s){let i=function(t,e){const{canSkipUntil:r,canSkipDateRanges:s,endSN:i}=t;return r&&(void 0!==e?e-i:0)<r?s?Te.v2:Te.Yes:Te.No}(t,r);return null!=e&&e.skip&&t.deltaUpdateFailed&&(r=e.msn,s=e.part,i=Te.No),new Se(r,s,i)}checkRetry(t){const e=t.details,r=Ie(t),s=t.errorAction,{action:i,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(i===$e.RetryRequest||!s.resolved&&i===$e.SendAlternateToPenaltyBox);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(r&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{const t=Pe(a,n);this.timer=self.setTimeout((()=>this.loadPlaylist()),t),this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`)}t.levelRetry=!0,s.resolved=!0}return o}}class Ke{constructor(t,e=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}sample(t,e){const r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class We{constructor(t,e,r,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ke(t),this.fast_=new Ke(e),this.defaultTTFB_=s,this.ttfb_=new Ke(t)}update(t,e){const{slow_:r,fast_:s,ttfb_:i}=this;r.halfLife!==t&&(this.slow_=new Ke(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.fast_=new Ke(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new Ke(t,i.getEstimate(),i.getTotalWeight()))}sample(t,e){const r=(t=Math.max(t,this.minDelayMs_))/1e3,s=8*e/r;this.fast_.sample(r,s),this.slow_.sample(r,s)}sampleTTFB(t){const e=t/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(r,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}function Ye(t,e){let r=!1,s=[];return t&&(r="SDR"!==t,s=[t]),e&&(s=e.allowedVideoRanges||Ee.slice(0),r=void 0!==e.preferHDR?e.preferHDR:function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),s=r?s.filter((t=>"SDR"!==t)):["SDR"]),{preferHDR:r,allowedVideoRanges:s}}function je(t,e){D.log(`[abr] start candidates with "${t}" ignored because ${e}`)}class qe{constructor(t){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:e,hls:r}=this,{autoLevelEnabled:s,media:i}=r;if(!t||!i)return;const n=performance.now(),a=e?e.stats:t.stats,o=e?e.duration:t.duration,l=n-a.loading.start,d=r.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||t.level<=d)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!s||i.paused||!i.playbackRate||!i.readyState)return;const h=r.mainForwardBufferInfo;if(null===h)return;const u=this.bwEstimator.getEstimateTTFB(),c=Math.abs(i.playbackRate);if(l<=Math.max(u,o/(2*c)*1e3))return;const f=h.len/c,g=a.loading.first?a.loading.first-a.loading.start:-1,m=a.loaded&&g>-1,v=this.getBwEstimate(),y=r.levels,T=y[t.level],S=a.total||Math.max(a.loaded,Math.round(o*T.averageBitrate/8));let L=m?l-g:l;L<1&&m&&(L=Math.min(l,8*a.loaded/v));const R=m?1e3*a.loaded/L:0,A=R?(S-a.loaded)/R:8*S/v+u/1e3;if(A<=f)return;const b=R?8*R:v;let _,x=Number.POSITIVE_INFINITY;for(_=t.level-1;_>d;_--){const t=y[_].maxBitrate;if(x=this.getTimeToLoadFrag(u/1e3,b,o*t,!y[_].details),x<f)break}if(x>=A)return;if(x>10*o)return;r.nextLoadLevel=r.nextAutoLevel=_,m?this.bwEstimator.sample(l-Math.min(u,g),a.loaded):this.bwEstimator.sampleTTFB(l);const k=y[_].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>k&&this.resetEstimator(k),this.clearTimer(),D.warn(`[abr] Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} is loading too slowly;\n Time to underbuffer: ${f.toFixed(3)} s\n Estimated load time for current fragment: ${A.toFixed(3)} s\n Estimated load time for down switch fragment: ${x.toFixed(3)} s\n TTFB estimate: ${0|g} ms\n Current BW estimate: ${p(v)?0|v:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${_} @ ${0|k} bps`),r.trigger(E.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:a})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(D.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new We(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.FRAG_LOADING,this.onFragLoading,this),t.on(E.FRAG_LOADED,this.onFragLoaded,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this),t.on(E.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(E.LEVEL_LOADED,this.onLevelLoaded,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(E.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.FRAG_LOADING,this.onFragLoading,this),t.off(E.FRAG_LOADED,this.onFragLoaded,this),t.off(E.FRAG_BUFFERED,this.onFragBuffered,this),t.off(E.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(E.LEVEL_LOADED,this.onLevelLoaded,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(E.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(E.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,e){const r=e.frag;if(!this.ignoreFragment(r)){var s;if(!r.bitrateTest)this.fragCurrent=r,this.partCurrent=null!=(s=e.part)?s:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case S.BUFFER_ADD_CODEC_ERROR:case S.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case S.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:r,partCurrent:s}=this;if(t&&r&&t.sn===r.sn&&t.level===r.level){const e=performance.now(),r=s?s.stats:t.stats,i=e-r.loading.start,n=r.loading.first?r.loading.first-r.loading.start:-1;if(r.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(i-Math.min(t,n),r.loaded)}else this.bwEstimator.sampleTTFB(i)}break}}}getTimeToLoadFrag(t,e,r,s){return t+r/e+(s?this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const r=this.hls.config,{loading:s}=e.stats,i=s.end-s.start;p(i)&&(this.lastLevelLoadSec=i/1e3),e.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD)}onFragLoaded(t,{frag:e,part:r}){const s=r?r.stats:e.stats;if(e.type===ne.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=r?r.duration:e.duration,i=this.hls.levels[e.level],n=(i.loaded?i.loaded.bytes:0)+s.loaded,a=(i.loaded?i.loaded.duration:0)+t;i.loaded={bytes:n,duration:a},i.realBitrate=Math.round(8*n/a)}if(e.bitrateTest){const t={stats:s,frag:e,part:r,id:e.type};this.onFragBuffered(E.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:r,part:s}=e,i=null!=s&&s.stats.loaded?s.stats:r.stats;if(i.aborted)return;if(this.ignoreFragment(r))return;const n=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,i.loaded),i.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==ne.MAIN||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,r=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,i=this.findBestLevel(r,e,t,0,s,1,1);if(i>-1)return i;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return D.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${a}`),a}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const s=e&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,s)&&e[t].loadError<=e[s].loadError)return t}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:r}=this,{maxAutoLevel:s,config:i,minAutoLevel:n}=r,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=i.abrBandWidthFactor,h=i.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,s,l,0,d,h);if(t>=0)return t}let u=a?Math.min(a,i.maxStarvationDelay):i.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){u=(a?Math.min(a,i.maxLoadingDelay):i.maxLoadingDelay)-t,D.info(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),d=h=1}}const c=this.findBestLevel(o,n,s,l,u,d,h);if(D.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${c}`),c>-1)return c;const f=r.levels[n],g=r.levels[r.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:r.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const r=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,s=t.mainForwardBufferInfo;return(s?s.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,r,s,i,n,a){var o;const l=s+i,d=this.lastLoadedFragLevel,h=-1===d?this.hls.firstLevel:d,{fragCurrent:u,partCurrent:c}=this,{levels:f,allAudioTracks:g,loadLevel:m,config:v}=this.hls;if(1===f.length)return 0;const y=f[h],E=!(null==y||null==(o=y.details)||!o.live),T=-1===m||-1===d;let S,L="SDR",R=(null==y?void 0:y.frameRate)||0;const{audioPreference:A,videoPreference:b}=v,_=this.audioTracksByGroup||(this.audioTracksByGroup=function(t){return t.reduce(((t,e)=>{let r=t.groups[e.groupId];r||(r=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(e);const s=e.channels||"2";return r.channels[s]=(r.channels[s]||0)+1,r.hasDefault=r.hasDefault||e.default,r.hasAutoSelect=r.hasAutoSelect||e.autoselect,r.hasDefault&&(t.hasDefaultAudio=!0),r.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t}),{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(g));if(T){if(-1!==this.firstSelection)return this.firstSelection;const s=this.codecTiers||(this.codecTiers=function(t,e,r,s){return t.slice(r,s+1).reduce(((t,r)=>{if(!r.codecSet)return t;const s=r.audioGroups;let i=t[r.codecSet];i||(t[r.codecSet]=i={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!s,fragmentError:0}),i.minBitrate=Math.min(i.minBitrate,r.bitrate);const n=Math.min(r.height,r.width);return i.minHeight=Math.min(i.minHeight,n),i.minFramerate=Math.min(i.minFramerate,r.frameRate),i.maxScore=Math.max(i.maxScore,r.score),i.fragmentError+=r.fragmentError,i.videoRanges[r.videoRange]=(i.videoRanges[r.videoRange]||0)+1,s&&s.forEach((t=>{if(!t)return;const r=e.groups[t];i.hasDefaultAudio=i.hasDefaultAudio||e.hasDefaultAudio?r.hasDefault:r.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(r.channels).forEach((t=>{i.channels[t]=(i.channels[t]||0)+r.channels[t]}))})),t}),{})}(f,_,e,r)),i=function(t,e,r,s,i){const n=Object.keys(t),a=null==s?void 0:s.channels,o=null==s?void 0:s.audioCodec,l=a&&2===parseInt(a);let d=!0,h=!1,u=1/0,c=1/0,f=1/0,g=0,m=[];const{preferHDR:v,allowedVideoRanges:y}=Ye(e,i);for(let e=n.length;e--;){const r=t[n[e]];d=r.channels[2]>0,u=Math.min(u,r.minHeight),c=Math.min(c,r.minFramerate),f=Math.min(f,r.minBitrate);const s=y.filter((t=>r.videoRanges[t]>0));s.length>0&&(h=!0,m=s)}u=p(u)?u:0,c=p(c)?c:0;const E=Math.max(1080,u),T=Math.max(30,c);return f=p(f)?f:r,r=Math.max(f,r),h||(e=void 0,m=[]),{codecSet:n.reduce(((e,s)=>{const i=t[s];if(s===e)return e;if(i.minBitrate>r)return je(s,`min bitrate of ${i.minBitrate} > current estimate of ${r}`),e;if(!i.hasDefaultAudio)return je(s,"no renditions with default or auto-select sound found"),e;if(o&&s.indexOf(o.substring(0,4))%5!=0)return je(s,`audio codec preference "${o}" not found`),e;if(a&&!l){if(!i.channels[a])return je(s,`no renditions with ${a} channel sound found (channels options: ${Object.keys(i.channels)})`),e}else if((!o||l)&&d&&0===i.channels[2])return je(s,"no renditions with stereo sound found"),e;return i.minHeight>E?(je(s,`min resolution of ${i.minHeight} > maximum of ${E}`),e):i.minFramerate>T?(je(s,`min framerate of ${i.minFramerate} > maximum of ${T}`),e):m.some((t=>i.videoRanges[t]>0))?i.maxScore<g?(je(s,`max score of ${i.maxScore} < selected max of ${g}`),e):e&&(Nt(s)>=Nt(e)||i.fragmentError>t[e].fragmentError)?e:(g=i.maxScore,s):(je(s,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),e)}),void 0),videoRanges:m,preferHDR:v,minFramerate:c,minBitrate:f}}(s,L,t,A,b),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:l,preferHDR:d}=i;S=n,L=d?a[a.length-1]:a[0],R=o,t=Math.max(t,l),D.log(`[abr] picked start tier ${JSON.stringify(i)}`)}else S=null==y?void 0:y.codecSet,L=null==y?void 0:y.videoRange;const x=c?c.duration:u?u.duration:0,k=this.bwEstimator.getEstimateTTFB()/1e3,w=[];for(let o=r;o>=e;o--){var I;const e=f[o],u=o>h;if(!e)continue;if(S&&e.codecSet!==S||L&&e.videoRange!==L||u&&R>e.frameRate||!u&&R>0&&R<e.frameRate||e.supportedResult&&(null==(I=e.supportedResult.decodingInfoResults)||!I[0].smooth)){w.push(o);continue}const g=e.details,v=(c?null==g?void 0:g.partTarget:null==g?void 0:g.averagetargetduration)||x;let A;A=u?a*t:n*t;const b=x&&s>=2*x&&0===i?f[o].averageBitrate:f[o].maxBitrate,_=this.getTimeToLoadFrag(k,A,b*v,void 0===g);if(A>=b&&(o===d||0===e.loadError&&0===e.fragmentError)&&(_<=k||!p(_)||E&&!this.bitrateTestDelay||_<l)){const t=this.forcedAutoLevel;return o===m||-1!==t&&t===m||(w.length&&D.trace(`[abr] Skipped level(s) ${w.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${f[w[0]].codecs}" ${f[w[0]].videoRange}; not compatible with "${y.codecs}" ${L}`),D.info(`[abr] switch candidate:${h}->${o} adjustedbw(${Math.round(A)})-bitrate=${Math.round(A-b)} ttfb:${k.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${_.toFixed(1)} firstSelection:${T} codecSet:${S} videoRange:${L} hls.loadLevel:${m}`)),T&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:r}=this.hls,s=Math.min(Math.max(t,r),e);this._nextAutoLevel!==s&&(this.nextAutoLevelKey="",this._nextAutoLevel=s)}}const ze={length:0,start:()=>0,end:()=>0};class Xe{static isBuffered(t,e){try{if(t){const r=Xe.getBuffered(t);for(let t=0;t<r.length;t++)if(e>=r.start(t)&&e<=r.end(t))return!0}}catch(t){}return!1}static bufferInfo(t,e,r){try{if(t){const s=Xe.getBuffered(t),i=[];let n;for(n=0;n<s.length;n++)i.push({start:s.start(n),end:s.end(n)});return this.bufferedInfo(i,e,r)}}catch(t){}return{len:0,start:e,end:e,nextStart:void 0}}static bufferedInfo(t,e,r){e=Math.max(0,e),t.sort((function(t,e){const r=t.start-e.start;return r||e.end-t.end}));let s=[];if(r)for(let e=0;e<t.length;e++){const i=s.length;if(i){const n=s[i-1].end;t[e].start-n<r?t[e].end>n&&(s[i-1].end=t[e].end):s.push(t[e])}else s.push(t[e])}else s=t;let i,n=0,a=e,o=e;for(let t=0;t<s.length;t++){const l=s[t].start,d=s[t].end;if(e+r>=l&&e<d)a=l,o=d,n=o-e;else if(e+r<l){i=l;break}}return{len:n,start:a||0,end:o||0,nextStart:i}}static getBuffered(t){try{return t.buffered}catch(t){return D.log("failed to get media.buffered",t),ze}}}class Qe{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e,r){const s=this.queues[e];s.push(t),1!==s.length||r||this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const r=new Promise((t=>{e=t})),s={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(s,t),r}executeNext(t){const e=this.queues[t];if(e.length){const r=e[0];try{r.execute()}catch(e){D.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${e}`),r.onError(e);const s=this.buffers[t];null!=s&&s.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Je=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class Ze{constructor(t){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=t=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:t,mediaSource:e}=this;this.log("Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(E.MEDIA_ATTACHED,{media:t,mediaSource:e})),e&&e.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&D.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t;const e="[buffer-controller]";this.appendSource=t.config.preferManagedMediaSource&&"undefined"!=typeof self&&self.ManagedMediaSource,this.log=D.log.bind(D,e),this.warn=D.warn.bind(D,e),this.error=D.error.bind(D,e),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:t}=this;t.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.BUFFER_RESET,this.onBufferReset,this),t.on(E.BUFFER_APPENDING,this.onBufferAppending,this),t.on(E.BUFFER_CODECS,this.onBufferCodecs,this),t.on(E.BUFFER_EOS,this.onBufferEos,this),t.on(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(E.FRAG_PARSED,this.onFragParsed,this),t.on(E.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.BUFFER_RESET,this.onBufferReset,this),t.off(E.BUFFER_APPENDING,this.onBufferAppending,this),t.off(E.BUFFER_CODECS,this.onBufferCodecs,this),t.off(E.BUFFER_EOS,this.onBufferEos,this),t.off(E.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(E.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(E.FRAG_PARSED,this.onFragParsed,this),t.off(E.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Qe(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,e){let r=2;e.audio&&!e.video||e.altAudio,r=1,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,e){const r=this.media=e.media,s=It(this.appendSource);if(r&&s){var i;const t=this.mediaSource=new s;this.log(`created media source: ${null==(i=t.constructor)?void 0:i.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming));const e=this._objectUrl=self.URL.createObjectURL(t);if(this.appendSource)try{r.removeAttribute("src");const s=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||s&&t instanceof s,tr(r),function(t,e){const r=self.document.createElement("source");r.type="video/mp4",r.src=e,t.appendChild(r)}(r,e),r.load()}catch(t){r.src=e}else r.src=e;r.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:r}=this;if(e){if(this.log("media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.removeEventListener("startstreaming",this._onStartStreaming),e.removeEventListener("endstreaming",this._onEndStreaming)),t&&(t.removeEventListener("emptied",this._onMediaEmptied),r&&self.URL.revokeObjectURL(r),this.mediaSrc===r?(t.removeAttribute("src"),this.appendSource&&tr(t),t.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(E.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach((t=>{this.resetBuffer(t)})),this._initSourceBuffer()}resetBuffer(t){const e=this.sourceBuffer[t];try{var r;if(e)this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(r=this.mediaSource)&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e)}catch(e){this.warn(`onBufferReset ${t}`,e)}}onBufferCodecs(t,e){const r=this.getSourceBufferTypes().length,s=Object.keys(e);if(s.forEach((t=>{if(r){const r=this.tracks[t];if(r&&"function"==typeof r.buffer.changeType){var s;const{id:i,codec:n,levelCodec:a,container:o,metadata:l}=e[t],d=Gt(r.codec,r.levelCodec),h=null==d?void 0:d.replace(Je,"$1");let u=Gt(n,a);const c=null==(s=u)?void 0:s.replace(Je,"$1");if(u&&h!==c){"audio"===t.slice(0,5)&&(u=$t(u,this.appendSource));const e=`${o};codecs=${u}`;this.appendChangeType(t,e),this.log(`switching codec ${d} to ${u}`),this.tracks[t]={buffer:r.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:i}}}}else this.pendingTracks[t]=e[t]})),r)return;const i=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==i&&(this.log(`${i} bufferCodec event(s) expected ${s.join(",")}`),this.bufferCodecEventsExpected=i),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(t,e){const{operationQueue:r}=this,s={execute:()=>{const s=this.sourceBuffer[t];s&&(this.log(`changing ${t} sourceBuffer type to ${e}`),s.changeType(e)),r.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};r.append(s,t,!!this.pendingTracks[t])}onBufferAppending(t,e){const{hls:r,operationQueue:s,tracks:i}=this,{data:n,type:a,frag:o,part:l,chunkMeta:d}=e,h=d.buffering[a],u=self.performance.now();h.start=u;const c=o.stats.buffering,f=l?l.stats.buffering:null;0===c.start&&(c.start=u),f&&0===f.start&&(f.start=u);const g=i.audio;let m=!1;"audio"===a&&"audio/mpeg"===(null==g?void 0:g.container)&&(m=!this.lastMpegAudioChunk||1===d.id||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const p=o.start,v={execute:()=>{if(h.executeStart=self.performance.now(),m){const t=this.sourceBuffer[a];if(t){const e=p-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${p} (delta: ${e}) sn: ${o.sn})`),t.timestampOffset=p)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();h.executeEnd=h.end=t,0===c.first&&(c.first=t),f&&0===f.first&&(f.first=t);const{sourceBuffer:e}=this,r={};for(const t in e)r[t]=Xe.getBuffered(e[t]);this.appendErrors[a]=0,"audio"===a||"video"===a?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(E.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:d,parent:o.type,timeRanges:r})},onError:t=>{const e={type:T.MEDIA_ERROR,parent:o.type,details:S.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:d,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)e.details=S.BUFFER_FULL_ERROR;else{const t=++this.appendErrors[a];e.details=S.BUFFER_APPEND_ERROR,this.warn(`Failed ${t}/${r.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),t>=r.config.appendErrorMaxRetry&&(e.fatal=!0)}r.trigger(E.ERROR,e)}};s.append(v,a,!!this.pendingTracks[a])}onBufferFlushing(t,e){const{operationQueue:r}=this,s=t=>({execute:this.removeExecutor.bind(this,t,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(E.BUFFER_FLUSHED,{type:t})},onError:e=>{this.warn(`Failed to remove from ${t} SourceBuffer`,e)}});e.type?r.append(s(e.type),e.type):this.getSourceBufferTypes().forEach((t=>{r.append(s(t),t)}))}onFragParsed(t,e){const{frag:r,part:s}=e,i=[],n=s?s.elementaryStreams:r.elementaryStreams;n[M]?i.push("audiovideo"):(n[P]&&i.push("audio"),n[F]&&i.push("video"));0===i.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers((()=>{const t=self.performance.now();r.stats.buffering.end=t,s&&(s.stats.buffering.end=t);const e=s?s.stats:r.stats;this.hls.trigger(E.FRAG_BUFFERED,{frag:r,part:s,stats:e,id:r.type})}),i)}onFragChanged(t,e){this.trimBuffers()}onBufferEos(t,e){this.getSourceBufferTypes().reduce(((t,r)=>{const s=this.sourceBuffer[r];return!s||e.type&&e.type!==r||(s.ending=!0,s.ended||(s.ended=!0,this.log(`${r} sourceBuffer now EOS`))),t&&!(s&&!s.ended)}),!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers((()=>{this.getSourceBufferTypes().forEach((t=>{const e=this.sourceBuffer[t];e&&(e.ending=!1)}));const{mediaSource:t}=this;t&&"open"===t.readyState?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream()):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})))}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:t,details:e,media:r}=this;if(!r||null===e)return;if(!this.getSourceBufferTypes().length)return;const s=t.config,i=r.currentTime,n=e.levelTargetDuration,a=e.live&&null!==s.liveBackBufferLength?s.liveBackBufferLength:s.backBufferLength;if(p(a)&&a>0){const t=Math.max(a,n),e=Math.floor(i/n)*n-t;this.flushBackBuffer(i,n,e)}if(p(s.frontBufferFlushThreshold)&&s.frontBufferFlushThreshold>0){const t=Math.max(s.maxBufferLength,s.frontBufferFlushThreshold),e=Math.max(t,n),r=Math.floor(i/n)*n+e;this.flushFrontBuffer(i,n,r)}}flushBackBuffer(t,e,r){const{details:s,sourceBuffer:i}=this;this.getSourceBufferTypes().forEach((n=>{const a=i[n];if(a){const i=Xe.getBuffered(a);if(i.length>0&&r>i.start(0)){if(this.hls.trigger(E.BACK_BUFFER_REACHED,{bufferEnd:r}),null!=s&&s.live)this.hls.trigger(E.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(a.ended&&i.end(i.length-1)-t<2*e)return void this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:n})}}}))}flushFrontBuffer(t,e,r){const{sourceBuffer:s}=this;this.getSourceBufferTypes().forEach((i=>{const n=s[i];if(n){const s=Xe.getBuffered(n),a=s.length;if(a<2)return;const o=s.start(a-1),l=s.end(a-1);if(r>o||t>=o&&t<=l)return;if(n.ended&&t-l<2*e)return void this.log(`Cannot flush ${i} front buffer while SourceBuffer is in ended state`);this.hls.trigger(E.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:i})}}))}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:t,hls:e,media:r,mediaSource:s}=this,i=t.fragments[0].start+t.totalduration,n=r.duration,a=p(s.duration)?s.duration:0;t.live&&e.config.liveDurationInfinity?(s.duration=1/0,this.updateSeekableRange(t)):(i>a&&i>n||!p(n))&&(this.log(`Updating Media Source duration to ${i.toFixed(3)}`),s.duration=i)}updateSeekableRange(t){const e=this.mediaSource,r=t.fragments;if(r.length&&t.live&&null!=e&&e.setLiveSeekableRange){const s=Math.max(0,r[0].start),i=Math.max(s,s+t.totalduration);this.log(`Media Source duration is set to ${e.duration}. Setting seekable range to ${s}-${i}.`),e.setLiveSeekableRange(s,i)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:r}=this,s=Object.keys(r).length;if(s&&(!t||2===s||"audiovideo"in r)){this.createSourceBuffers(r),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(E.BUFFER_CREATED,{tracks:this.tracks}),t.forEach((t=>{e.executeNext(t)}));else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:r}=this;if(!r)throw Error("createSourceBuffers called when mediaSource was null");for(const s in t)if(!e[s]){const i=t[s];if(!i)throw Error(`source buffer exists for track ${s}, however track does not`);let n=i.levelCodec||i.codec;n&&"audio"===s.slice(0,5)&&(n=$t(n,this.appendSource));const a=`${i.container};codecs=${n}`;this.log(`creating sourceBuffer(${a})`);try{const t=e[s]=r.addSourceBuffer(a),o=s;this.addBufferListener(o,"updatestart",this._onSBUpdateStart),this.addBufferListener(o,"updateend",this._onSBUpdateEnd),this.addBufferListener(o,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(o,"bufferedchange",((t,e)=>{const r=e.removedRanges;null!=r&&r.length&&this.hls.trigger(E.BUFFER_FLUSHED,{type:s})})),this.tracks[s]={buffer:t,codec:n,container:i.container,levelCodec:i.levelCodec,metadata:i.metadata,id:i.id}}catch(t){this.error(`error while trying to add sourceBuffer: ${t.message}`),this.hls.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:s,mimeType:a})}}}get mediaSrc(){var t;const e=(null==(t=this.media)?void 0:t.firstChild)||this.media;return null==e?void 0:e.src}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){var e;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const{operationQueue:r}=this;r.current(t).onComplete(),r.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){var r;const s=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(r=this.mediaSource)?void 0:r.readyState}`);this.error(`${s}`,e),this.hls.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:s,fatal:!1});const i=this.operationQueue.current(t);i&&i.onError(s)}removeExecutor(t,e,r){const{media:s,mediaSource:i,operationQueue:n,sourceBuffer:a}=this,o=a[t];if(!s||!i||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(t);const l=p(s.duration)?s.duration:1/0,d=p(i.duration)?i.duration:1/0,h=Math.max(0,e),u=Math.min(r,l,d);u>h&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${h},${u}] from the ${t} SourceBuffer`),o.remove(h,u)):n.shiftAndExecuteNext(t)}appendExecutor(t,e){const r=this.sourceBuffer[e];if(r)r.ended=!1,r.appendBuffer(t);else if(!this.pendingTracks[e])throw new Error(`Attempting to append to the ${e} SourceBuffer, but it does not exist`)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);const{operationQueue:r}=this,s=e.map((t=>r.appendBlocker(t)));Promise.all(s).then((()=>{t(),e.forEach((t=>{const e=this.sourceBuffer[t];null!=e&&e.updating||r.shiftAndExecuteNext(t)}))}))}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,r){const s=this.sourceBuffer[t];if(!s)return;const i=r.bind(this,t);this.listeners[t].push({event:e,listener:i}),s.addEventListener(e,i)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach((t=>{e.removeEventListener(t.event,t.listener)}))}}function tr(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach((e=>{t.removeChild(e)}))}class er{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(E.BUFFER_CODECS,this.onBufferCodecs,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(E.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(E.BUFFER_CODECS,this.onBufferCodecs,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const r=this.hls.levels[e.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(t,e){this.media=e.media instanceof HTMLVideoElement?e.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,e){const r=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,r.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&p(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const t=this.hls.levels;if(t.length){const e=this.hls,r=this.getMaxLevel(t.length-1);r!==this.autoLevelCapping&&D.log(`Setting autoLevelCapping to ${r}: ${t[r].height}p@${t[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=r,e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}}getMaxLevel(t){const e=this.hls.levels;if(!e.length)return-1;const r=e.filter(((e,r)=>this.isLevelAllowed(e)&&r<=t));return this.clientRect=null,er.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}isLevelAllowed(t){return!this.restrictedLevels.some((e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height))}static getMaxLevelByMediaSize(t,e,r){if(null==t||!t.length)return-1;let s=t.length-1;const i=Math.max(e,r);for(let e=0;e<t.length;e+=1){const r=t[e];if((r.width>=i||r.height>=i)&&(n=r,!(a=t[e+1])||n.width!==a.width||n.height!==a.height)){s=e;break}}var n,a;return s}}class rr{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(E.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(E.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const r=this.hls.config;if(r.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,r){const s=performance.now();if(e){if(this.lastTime){const t=s-this.lastTime,i=r-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*i/t,o=this.hls;if(o.trigger(E.FPS_DROP,{currentDropped:i,currentDecoded:n,totalDroppedFrames:r}),a>0&&i>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;D.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(E.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=r,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}class sr{constructor(t){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=t,this.log=D.log.bind(D,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter((e=>e!==t)))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:r}=e;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:r}=e;if((null==r?void 0:r.action)===$e.SendAlternateToPenaltyBox&&r.flags===Ge.MoveAllAlternatesMatchingHost){const t=this.levels;let s=this.pathwayPriority,i=this.pathwayId;if(e.context){const{groupId:r,pathwayId:s,type:n}=e.context;r&&t?i=this.getPathwayForGroupId(r,n,i):s&&(i=s)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!s&&t&&(s=t.reduce(((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t)),[])),s&&s.length>1&&(this.updatePathwayPriority(s),r.resolved=this.pathwayId!==i),r.resolved||D.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${i} levels: ${t?t.length:t} priorities: ${JSON.stringify(s)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const r=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),e=this.getLevelsForPathway(r),this.pathwayId=r}return e.length!==t.length?(this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e):t}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter((e=>t===e.pathwayId))}updatePathwayPriority(t){let e;this.pathwayPriority=t;const r=this.penalizedPathways,s=performance.now();Object.keys(r).forEach((t=>{s-r[t]>3e5&&delete r[t]}));for(let s=0;s<t.length;s++){const i=t[s];if(i in r)continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,a=this.hls.levels[n];if(e=this.getLevelsForPathway(i),e.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,we(e),this.hls.trigger(E.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];a&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==a.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==a.bitrate&&this.log(`Unstable Pathways change from bitrate ${a.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,r){const s=this.getLevelsForPathway(r).concat(this.levels||[]);for(let r=0;r<s.length;r++)if(e===se&&s[r].hasAudioGroup(t)||e===ie&&s[r].hasSubtitleGroup(t))return s[r].pathwayId;return r}clonePathways(t){const e=this.levels;if(!e)return;const r={},s={};t.forEach((t=>{const{ID:i,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some((t=>t.pathwayId===i)))return;const o=this.getLevelsForPathway(n).map((t=>{const e=new k(t.attrs);e["PATHWAY-ID"]=i;const n=e.AUDIO&&`${e.AUDIO}_clone_${i}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${i}`;n&&(r[e.AUDIO]=n,e.AUDIO=n),o&&(s[e.SUBTITLES]=o,e.SUBTITLES=o);const l=nr(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=new Le({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)d.addGroupId("audio",`${t.audioGroups[e]}_clone_${i}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)d.addGroupId("text",`${t.subtitleGroups[e]}_clone_${i}`);return d}));e.push(...o),ir(this.audioTracks,r,a,i),ir(this.subtitleTracks,s,a,i)}))}loadSteeringManifest(t){const e=this.hls.config,r=e.loader;let s;this.loader&&this.loader.destroy(),this.loader=new r(e);try{s=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==s.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+t)}const i={responseType:"json",url:s.href},n=e.steeringManifestLoadPolicy.default,a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,r,i)=>{this.log(`Loaded steering manifest: "${s}"`);const n=t.data;if(1!==n.VERSION)return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":a,"PATHWAY-CLONES":o,"PATHWAY-PRIORITY":l}=n;if(a)try{this.uri=new self.URL(a,s).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||r.url),o&&this.clonePathways(o);const d={steeringManifest:n,url:s.toString()};this.hls.trigger(E.STEERING_MANIFEST_LOADED,d),l&&this.updatePathwayPriority(l)},onError:(t,e,r,s)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let i=1e3*this.timeToLoad;if(429!==t.code)this.scheduleRefresh(this.uri||e.url,i);else{const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(i=1e3*parseFloat(e))}this.log(`Steering manifest ${e.url} rate limited`)}},onTimeout:(t,e,r)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(i,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout((()=>{var e;const r=null==(e=this.hls)?void 0:e.media;!r||r.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)}),e)}}function ir(t,e,r,s){t&&Object.keys(e).forEach((i=>{const n=t.filter((t=>t.groupId===i)).map((t=>{const n=m({},t);return n.details=void 0,n.attrs=new k(n.attrs),n.url=n.attrs.URI=nr(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),n.groupId=n.attrs["GROUP-ID"]=e[i],n.attrs["PATHWAY-ID"]=s,n}));t.push(...n)}))}function nr(t,e,r,s){const{HOST:i,PARAMS:n,[r]:a}=s;let o;e&&(o=null==a?void 0:a[e],o&&(t=o));const l=new self.URL(t);return i&&!o&&(l.host=i),n&&Object.keys(n).sort().forEach((t=>{t&&l.searchParams.set(t,n[t])})),l.href}const ar=/^age:\s*[\d.]+\s*$/im;class or{constructor(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new C,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null,this.stats=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,e,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const r=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then((()=>{if(!this.stats.aborted)return i(r,e.url)})).catch((t=>(r.open("GET",e.url,!0),i(r,e.url)))).then((()=>{this.stats.aborted||this.openAndSendXhr(r,e,t)})).catch((t=>{this.callbacks.onError({code:r.status,text:t.message},e,r,s)})):this.openAndSendXhr(r,e,t)}openAndSendXhr(t,e,r){t.readyState||t.open("GET",e.url,!0);const s=e.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:n}=r.loadPolicy;if(s)for(const e in s)t.setRequestHeader(e,s[e]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),r.timeout=i&&p(i)?i:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:r}=this;if(!t||!e)return;const s=e.readyState,i=this.config;if(!r.aborted&&s>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===s)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const s=e.status,n="text"!==e.responseType;if(s>=200&&s<300&&(n&&e.response||null!==e.responseText)){r.loading.end=Math.max(self.performance.now(),r.loading.first);const i=n?e.response:e.responseText,a="arraybuffer"===e.responseType?i.byteLength:i.length;if(r.loaded=r.total=a,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(r,t,i,e),!this.callbacks)return;const l={url:e.responseURL,data:i,code:s};this.callbacks.onSuccess(l,r,t,e)}else{const n=i.loadPolicy.errorRetry;Me(n,r.retry,!1,{url:t.url,data:void 0,code:s})?this.retry(n):(D.error(`${s} while loading ${t.url}`),this.callbacks.onError({code:s,text:e.statusText},t,e,r))}}}loadtimeout(){var t;const e=null==(t=this.config)?void 0:t.loadPolicy.timeoutRetry;if(Me(e,this.stats.retry,!0))this.retry(e);else{var r;D.warn(`timeout while loading ${null==(r=this.context)?void 0:r.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:r}=this;this.retryDelay=Pe(t,r.retry),r.retry++,D.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${r.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&ar.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}class lr{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let r;return t.length?(r=1===t.length?t[0]:function(t,e){const r=new Uint8Array(e);let s=0;for(let e=0;e<t.length;e++){const i=t[e];r.set(i,s),s+=i.length}return r}(t,e),this.reset(),r):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}const dr=/(\d+)-(\d+)\/(\d+)/;class hr{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||ur,this.controller=new self.AbortController,this.stats=new C}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,e,r){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const i=function(t,e){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(m({},t.headers))};t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return r}(t,this.controller.signal),n=r.onProgress,a="arraybuffer"===t.responseType,o=a?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:d}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=r,this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),e.timeout=l&&p(l)?l:d,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),r.onTimeout(s,t,this.response)}),e.timeout),self.fetch(this.request).then((i=>{this.response=this.loader=i;const o=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=d,this.requestTimeout=self.setTimeout((()=>{this.abortInternal(),r.onTimeout(s,t,this.response)}),d-(o-s.loading.start)),!i.ok){const{status:t,statusText:e}=i;throw new cr(e||"fetch, bad network response",t,i)}return s.loading.first=o,s.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=dr.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(p(t))return t}const r=t.get("Content-Length");if(r)return parseInt(r)}(i.headers)||s.total,n&&p(e.highWaterMark)?this.loadProgressively(i,s,t,e.highWaterMark,n):a?i.arrayBuffer():"json"===t.responseType?i.json():i.text()})).then((i=>{const a=this.response;if(!a)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=i[o];l&&(s.loaded=s.total=l);const d={url:a.url,data:i,code:a.status};n&&!p(e.highWaterMark)&&n(s,t,i,a),r.onSuccess(d,s,t,a)})).catch((e=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const i=e&&e.code||0,n=e?e.message:null;r.onError({code:i,text:n},t,e?e.details:null,s)}))}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,r,s=0,i){const n=new lr,a=t.body.getReader(),o=()=>a.read().then((a=>{if(a.done)return n.dataLength&&i(e,r,n.flush(),t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<s||n.dataLength?(n.push(l),n.dataLength>=s&&i(e,r,n.flush(),t)):i(e,r,l,t),o()})).catch((()=>Promise.reject()));return o()}}function ur(t,e){return new self.Request(t.url,e)}class cr extends Error{constructor(t,e,r){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=r}}const fr=c(c({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:or,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:qe,bufferController:Ze,capLevelController:er,errorController:He,fpsController:rr,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:null,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:G,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:sr});function gr(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(gr):Object.keys(t).reduce(((e,r)=>(e[r]=gr(t[r]),e)),{}):t}function mr(t){const e=t.loader;if(e!==hr&&e!==or)D.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=hr,t.progressive=!0,t.enableSoftwareAES=!0,D.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let pr;class vr extends Ve{constructor(t,e){super(t,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(E.LEVEL_LOADED,this.onLevelLoaded,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this),t.on(E.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(E.LEVEL_LOADED,this.onLevelLoaded,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(E.FRAG_BUFFERED,this.onFragBuffered,this),t.off(E.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach((t=>{t.loadError=0,t.fragmentError=0})),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const r=this.hls.config.preferManagedMediaSource,s=[],i={},n={};let a=!1,o=!1,l=!1;e.levels.forEach((t=>{var e,d;const h=t.attrs;let{audioCodec:u,videoCodec:c}=t;-1!==(null==(e=u)?void 0:e.indexOf("mp4a.40.34"))&&(pr||(pr=/chrome|firefox/i.test(navigator.userAgent)),pr&&(t.audioCodec=u=void 0)),u&&(t.audioCodec=u=$t(u,r)),0===(null==(d=c)?void 0:d.indexOf("avc1"))&&(c=t.videoCodec=function(t){const e=t.split(".");if(e.length>2){let t=e.shift()+".";return t+=parseInt(e.shift()).toString(16),t+=("000"+parseInt(e.shift()).toString(16)).slice(-4),t}return t}(c));const{width:f,height:g,unknownCodecs:m}=t;if(a||(a=!(!f||!g)),o||(o=!!c),l||(l=!!u),null!=m&&m.length||u&&!Pt(u,"audio",r)||c&&!Pt(c,"video",r))return;const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=h,L=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${p}-${S}-${y}`;if(i[L])if(i[L].uri===t.url||t.attrs["PATHWAY-ID"])i[L].addGroupId("audio",h.AUDIO),i[L].addGroupId("text",h.SUBTITLES);else{const e=n[L]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const r=new Le(t);i[L]=r,s.push(r)}else{const e=new Le(t);i[L]=e,n[L]=1,s.push(e)}})),this.filterAndSortMediaOptions(s,e,a,o,l)}filterAndSortMediaOptions(t,e,r,s,i){let n=[],a=[],o=t;if((r||s)&&i&&(o=o.filter((({videoCodec:t,videoRange:e,width:r,height:s})=>{return(!!t||!(!r||!s))&&(!!(i=e)&&Ee.indexOf(i)>-1);var i}))),0===o.length)return void Promise.resolve().then((()=>{if(this.hls){e.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(e.levels[0].attrs)}`);const t=new Error("no level with compatible codecs found in manifest");this.hls.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:t,reason:t.message})}}));if(e.audioTracks){const{preferManagedMediaSource:t}=this.hls.config;n=e.audioTracks.filter((e=>!e.audioCodec||Pt(e.audioCodec,"audio",t))),yr(n)}e.subtitles&&(a=e.subtitles,yr(a));const l=o.slice(0);o.sort(((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return Ee.indexOf(t.videoRange)-Ee.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const r=Ot(t.videoCodec),s=Ot(e.videoCodec);if(r!==s)return s-r}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const r=Nt(t.codecSet),s=Nt(e.codecSet);if(r!==s)return s-r}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0}));let d=l[0];if(this.steering&&(o=this.steering.filterParsedLevels(o),o.length!==l.length))for(let t=0;t<l.length;t++)if(l[t].pathwayId===o[0].pathwayId){d=l[t];break}this._levels=o;for(let t=0;t<o.length;t++)if(o[t]===d){var h;this._firstLevel=t;const e=d.bitrate,r=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${e}`),void 0===(null==(h=this.hls.userConfig)?void 0:h.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>r&&r===fr.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const u=i&&!s,c={levels:o,audioTracks:n,subtitleTracks:a,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:i,video:s,altAudio:!u&&n.some((t=>!!t.url))};this.hls.trigger(E.MANIFEST_PARSED,c),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const r=new Error("invalid level idx"),s=t<0;if(this.hls.trigger(E.ERROR,{type:T.OTHER_ERROR,details:S.LEVEL_SWITCH_ERROR,level:t,fatal:s,error:r,reason:r.message}),s)return;t=Math.min(t,e.length-1)}const r=this.currentLevelIndex,s=this.currentLevel,i=s?s.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,r===t&&n.details&&s&&i===a)return;this.log(`Switching to level ${t} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${a?" with Pathway "+a:""} from level ${r}${i?" with Pathway "+i:""}`);const o={level:t,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(E.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==s?void 0:s.details);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){!e.fatal&&e.context&&e.context.type===re&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===ne.MAIN){const t=e.elementaryStreams;if(!Object.keys(t).some((e=>!!t[e])))return;const r=this._levels[e.level];null!=r&&r.loadError&&(this.log(`Resetting level error count of ${r.loadError} on frag buffered`),r.loadError=0)}}onLevelLoaded(t,e){var r;const{level:s,details:i}=e,n=this._levels[s];var a;if(!n)return this.warn(`Invalid level index ${s}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(i.deltaUpdateFailed=!0));s===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(s,e,n.details)):null!=(r=e.deliveryDirectives)&&r.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,r=this.currentLevel;if(r&&this.shouldLoadPlaylist(r)){let s=r.uri;if(t)try{s=t.addDirectives(s)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}const i=r.attrs["PATHWAY-ID"];this.log(`Loading level index ${e}${void 0!==(null==t?void 0:t.msn)?" at sn "+t.msn+" part "+t.part:""} with${i?" Pathway "+i:""} ${s}`),this.clearTimer(),this.hls.trigger(E.LEVEL_LOADING,{url:s,level:e,pathwayId:r.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;const r=this._levels.filter(((e,r)=>r!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach((t=>t.level=-1))),!1)));we(r),this._levels=r,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(E.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(E.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function yr(t){const e={};t.forEach((t=>{const r=t.groupId||"";t.id=e[r]=e[r]||0,e[r]++}))}var Er="NOT_LOADED",Tr="APPENDING",Sr="PARTIAL",Lr="OK";class Rr{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(E.BUFFER_APPENDED,this.onBufferAppended,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this),t.on(E.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(E.BUFFER_APPENDED,this.onBufferAppended,this),t.off(E.FRAG_BUFFERED,this.onFragBuffered,this),t.off(E.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const r=this.activePartLists[e];if(r)for(let e=r.length;e--;){const s=r[e];if(!s)break;const i=s.end;if(s.start<=t&&null!==i&&t<=i)return s}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:r}=this,s=Object.keys(r);for(let i=s.length;i--;){const n=r[s[i]];if((null==n?void 0:n.body.type)===e&&n.buffered){const e=n.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,r,s){this.timeRanges&&(this.timeRanges[t]=e);const i=(null==s?void 0:s.fragment.sn)||-1;Object.keys(this.fragments).forEach((s=>{const n=this.fragments[s];if(!n)return;if(i>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===r&&this.removeFragment(n.body));const a=n.range[t];a&&a.time.some((t=>{const r=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return r&&this.removeFragment(n.body),r}))}))}detectPartialFragments(t){const e=this.timeRanges,{frag:r,part:s}=t;if(!e||"initSegment"===r.sn)return;const i=br(r),n=this.fragments[i];if(!n||n.buffered&&r.gap)return;const a=!r.relurl;if(Object.keys(e).forEach((t=>{const i=r.elementaryStreams[t];if(!i)return;const o=e[t],l=a||!0===i.partial;n.range[t]=this.getBufferedTimes(r,s,l,o)})),n.loaded=null,Object.keys(n.range).length){n.buffered=!0;(n.body.endList=r.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Ar(n)||this.removeParts(r.sn-1,r.type)}else this.removeFragment(n.body)}removeParts(t,e){const r=this.activePartLists[e];r&&(this.activePartLists[e]=r.filter((e=>e.fragment.sn>=t)))}fragBuffered(t,e){const r=br(t);let s=this.fragments[r];!s&&e&&(s=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(t,e,r,s){const i={time:[],partial:r},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<s.length;t++){const e=s.start(t)-this.bufferPadding,r=s.end(t)+this.bufferPadding;if(l>=e&&o<=r){i.time.push({startPTS:Math.max(n,s.start(t)),endPTS:Math.min(a,s.end(t))});break}if(n<r&&a>e){const e=Math.max(n,s.start(t)),r=Math.min(a,s.end(t));r>e&&(i.partial=!0,i.time.push({startPTS:e,endPTS:r}))}else if(a<=e)break}return i}getPartialFragment(t){let e,r,s,i=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach((l=>{const d=o[l];d&&Ar(d)&&(r=d.body.start-a,s=d.body.end+a,t>=r&&t<=s&&(e=Math.min(t-r,s-t),n<=e&&(i=d.body,n=e)))})),i}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Ar(e))}getState(t){const e=br(t),r=this.fragments[e];return r?r.buffered?Ar(r)?Sr:Lr:Tr:Er}isTimeBuffered(t,e,r){let s,i;for(let n=0;n<r.length;n++){if(s=r.start(n)-this.bufferPadding,i=r.end(n)+this.bufferPadding,t>=s&&e<=i)return!0;if(e<=s)return!1}return!1}onFragLoaded(t,e){const{frag:r,part:s}=e;if("initSegment"===r.sn||r.bitrateTest)return;const i=s?null:e,n=br(r);this.fragments[n]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:r,part:s,timeRanges:i}=e;if("initSegment"===r.sn)return;const n=r.type;if(s){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(s)}this.timeRanges=i,Object.keys(i).forEach((t=>{const e=i[t];this.detectEvictedFragments(t,e,n,s)}))}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=br(t);return!!this.fragments[e]}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,r,s,i){s&&!this.hasGaps||Object.keys(this.fragments).forEach((n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==r||s&&!o.gap||o.start<e&&o.end>t&&(a.buffered||i)&&this.removeFragment(o)}))}removeFragment(t){const e=br(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const e=t.sn;this.activePartLists[t.type]=r.filter((t=>t.fragment.sn!==e))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function Ar(t){var e,r,s;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(r=t.range.audio)?void 0:r.partial)||(null==(s=t.range.audiovideo)?void 0:s.partial))}function br(t){return`${t.type}_${t.level}_${t.sn}`}const Dr=Math.pow(2,17);class _r{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e){const r=t.url;if(!r)return Promise.reject(new wr({type:T.NETWORK_ERROR,details:S.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const s=this.config,i=s.fLoader,n=s.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some((t=>"GAP"===t[0])))return void o(kr(t));t.gap=!1}const l=this.loader=t.loader=i?new i(s):new n(s),d=xr(t),h=Fe(s.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Dr};t.stats=l.stats,l.load(d,u,{onSuccess:(e,r,s,i)=>{this.resetLoader(t,l);let n=e.data;s.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),a({frag:t,part:null,payload:n,networkDetails:i})},onError:(e,s,i,n)=>{this.resetLoader(t,l),o(new wr({type:T.NETWORK_ERROR,details:S.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:c({url:r,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:i,stats:n}))},onAbort:(e,r,s)=>{this.resetLoader(t,l),o(new wr({type:T.NETWORK_ERROR,details:S.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:s,stats:e}))},onTimeout:(e,r,s)=>{this.resetLoader(t,l),o(new wr({type:T.NETWORK_ERROR,details:S.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:e}))},onProgress:(r,s,i,n)=>{e&&e({frag:t,part:null,payload:i,networkDetails:n})}})}))}loadPart(t,e,r){this.abort();const s=this.config,i=s.fLoader,n=s.loader;return new Promise(((a,o)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void o(kr(t,e));const l=this.loader=t.loader=i?new i(s):new n(s),d=xr(t,e),h=Fe(s.fragLoadPolicy.default),u={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Dr};e.stats=l.stats,l.load(d,u,{onSuccess:(s,i,n,o)=>{this.resetLoader(t,l),this.updateStatsFromPart(t,e);const d={frag:t,part:e,payload:s.data,networkDetails:o};r(d),a(d)},onError:(r,s,i,n)=>{this.resetLoader(t,l),o(new wr({type:T.NETWORK_ERROR,details:S.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:c({url:d.url,data:void 0},r),error:new Error(`HTTP Error ${r.code} ${r.text}`),networkDetails:i,stats:n}))},onAbort:(r,s,i)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,l),o(new wr({type:T.NETWORK_ERROR,details:S.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:i,stats:r}))},onTimeout:(r,s,i)=>{this.resetLoader(t,l),o(new wr({type:T.NETWORK_ERROR,details:S.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:i,stats:r}))}})}))}updateStatsFromPart(t,e){const r=t.stats,s=e.stats,i=s.total;if(r.loaded+=s.loaded,i){const s=Math.round(t.duration/e.duration),n=Math.min(Math.round(r.loaded/i),s),a=(s-n)*Math.round(r.loaded/n);r.total=r.loaded+a}else r.total=Math.max(r.loaded,r.total);const n=r.loading,a=s.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function xr(t,e=null){const r=e||t,s={frag:t,part:e,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},i=r.byteRangeStartOffset,n=r.byteRangeEndOffset;if(p(i)&&p(n)){var a;let e=i,r=n;if("initSegment"===t.sn&&"AES-128"===(null==(a=t.decryptdata)?void 0:a.method)){const t=n-i;t%16&&(r=n+(16-t%16)),0!==i&&(s.resetIV=!0,e=i-16)}s.rangeStart=e,s.rangeEnd=r}return s}function kr(t,e){const r=new Error(`GAP ${t.gap?"tag":"attribute"} found`),s={type:T.MEDIA_ERROR,details:S.FRAG_GAP,fatal:!1,frag:t,error:r,networkDetails:null};return e&&(s.part=e),(e||t).stats.aborted=!0,new wr(s)}class wr extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Ir{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const r in this.keyUriToKeyInfo){const s=this.keyUriToKeyInfo[r].loader;if(s){var e;if(t&&t!==(null==(e=s.context)?void 0:e.frag.type))return;s.abort()}}}detach(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(t,e=S.KEY_LOAD_ERROR,r,s,i){return new wr({type:T.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:i,error:r,networkDetails:s})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:r,cc:s}=t;for(let t=0;t<e.length;t++){const i=e[t];if(s<=i.cc&&("initSegment"===r||"initSegment"===i.sn||r<i.sn)){this.emeController.selectKeySystemFormat(i).then((t=>{i.setKeyFormat(t)}));break}}}}load(t){return!t.decryptdata&&t.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(t).then((e=>this.loadInternal(t,e))):this.loadInternal(t)}loadInternal(t,e){var r,s;e&&t.setKeyFormat(e);const i=t.decryptdata;if(!i){const r=new Error(e?`Expected frag.decryptdata to be defined after setting format ${e}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(t,S.KEY_LOAD_ERROR,r))}const n=i.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,S.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(r=a)&&r.decryptdata.key)return i.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var o;if(null!=(s=a)&&s.keyLoadPromise)switch(null==(o=a.mediaKeySessionContext)?void 0:o.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return a.keyLoadPromise.then((e=>(i.key=e.keyInfo.decryptdata.key,{frag:t,keyInfo:a})))}switch(a=this.keyUriToKeyInfo[n]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===i.keyFormat?this.loadKeyHTTP(a,t):this.loadKeyEME(a,t);case"AES-128":return this.loadKeyHTTP(a,t);default:return Promise.reject(this.createKeyLoadError(t,S.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t,e){const r={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(r);if(e)return(t.keyLoadPromise=e.then((e=>(t.mediaKeySessionContext=e,r)))).catch((e=>{throw t.keyLoadPromise=null,e}))}return Promise.resolve(r)}loadKeyHTTP(t,e){const r=this.config,s=new(0,r.loader)(r);return e.keyLoader=t.loader=s,t.keyLoadPromise=new Promise(((i,n)=>{const a={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},o=r.keyLoadPolicy.default,l={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,r,s)=>{const{frag:a,keyInfo:o,url:l}=r;if(!a.decryptdata||o!==this.keyUriToKeyInfo[l])return n(this.createKeyLoadError(a,S.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));o.decryptdata.key=a.decryptdata.key=new Uint8Array(t.data),a.keyLoader=null,o.loader=null,i({frag:a,keyInfo:o})},onError:(t,r,s,i)=>{this.resetLoader(r),n(this.createKeyLoadError(e,S.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),s,c({url:a.url,data:void 0},t)))},onTimeout:(t,r,s)=>{this.resetLoader(r),n(this.createKeyLoadError(e,S.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),s))},onAbort:(t,r,s)=>{this.resetLoader(r),n(this.createKeyLoadError(e,S.INTERNAL_ABORTED,new Error("key loading aborted"),s))}};s.load(a,l,d)}))}resetLoader(t){const{frag:e,keyInfo:r,url:s}=t,i=r.loader;e.keyLoader===i&&(e.keyLoader=null,r.loader=null),delete this.keyUriToKeyInfo[s],i&&i.destroy()}}class Cr{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Pr{constructor(t,e,r,s=0,i=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=r,this.size=s,this.part=i,this.partial=n}}function Fr(t,e){for(let s=0,i=t.length;s<i;s++){var r;if((null==(r=t[s])?void 0:r.cc)===e)return t[s]}return null}function Mr(t,e){if(t){const r=t.start+e;t.start=t.startPTS=r,t.endPTS=r+t.duration}}function Or(t,e){const r=e.fragments;for(let e=0,s=r.length;e<s;e++)Mr(r[e],t);e.fragmentHint&&Mr(e.fragmentHint,t),e.alignedSliding=!0}function Nr(t,e,r){e&&(!function(t,e,r){if(function(t,e,r){return!(!e||!(r.endCC>r.startCC||t&&t.cc<r.startCC))}(t,r,e)){const t=function(t,e){const r=t.fragments,s=e.fragments;if(!s.length||!r.length)return void D.log("No fragments to align");const i=Fr(r,s[0].cc);if(i&&(!i||i.startPTS))return i;D.log("No frag in previous level to align on")}(r,e);t&&p(t.start)&&(D.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),Or(t.start,e))}}(t,r,e),!r.alignedSliding&&e&&function(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const r=t.fragments,s=e.fragments;if(!r.length||!s.length)return;let i,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(i=Fr(s,a),n=Fr(r,a));i&&n||(i=s[Math.floor(s.length/2)],n=Fr(r,i.cc)||r[Math.floor(r.length/2)]);const o=i.programDateTime,l=n.programDateTime;if(!o||!l)return;Or((l-o)/1e3-(n.start-i.start),t)}(r,e),r.alignedSliding||!e||r.skippedSegments||_e(e,r))}class Br{constructor(t,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=t,this.aesIV=e}decrypt(t,e){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t)}}class Ur{constructor(t,e){this.subtle=void 0,this.key=void 0,this.subtle=t,this.key=e}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class $r{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),r=new Uint32Array(4);for(let t=0;t<4;t++)r[t]=e.getUint32(4*t);return r}initTable(){const t=this.sBox,e=this.invSBox,r=this.subMix,s=r[0],i=r[1],n=r[2],a=r[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],u=o[3],c=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)c[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let r=g^g<<1^g<<2^g<<3^g<<4;r=r>>>8^255&r^99,t[f]=r,e[r]=f;const o=c[f],m=c[o],p=c[m];let v=257*c[r]^16843008*r;s[f]=v<<24|v>>>8,i[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[r]=v<<24|v>>>8,d[r]=v<<16|v>>>16,h[r]=v<<8|v>>>24,u[r]=v,f?(f=o^c[c[c[p^o]]],g^=c[c[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let r=!0,s=0;for(;s<e.length&&r;)r=e[s]===this.key[s],s++;if(r)return;this.key=e;const i=this.keySize=e.length;if(4!==i&&6!==i&&8!==i)throw new Error("Invalid aes key size="+i);const n=this.ksRows=4*(i+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),d=this.invKeySchedule=new Uint32Array(n),h=this.sBox,u=this.rcon,c=this.invSubMix,f=c[0],g=c[1],m=c[2],p=c[3];let v,y;for(a=0;a<n;a++)a<i?v=l[a]=e[a]:(y=v,a%i==0?(y=y<<8|y>>>24,y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y],y^=u[a/i|0]<<24):i>6&&a%i==4&&(y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y]),l[a]=v=(l[a-i]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[h[y>>>24]]^g[h[y>>>16&255]]^m[h[y>>>8&255]]^p[h[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,r){const s=this.keySize+6,i=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],h=a[3],u=this.uint8ArrayToUint32Array_(r);let c=u[0],f=u[1],g=u[2],m=u[3];const p=new Int32Array(t),v=new Int32Array(p.length);let y,E,T,S,L,R,A,b,D,_,x,k,w,I;const C=this.networkToHostOrderSwap;for(;e<p.length;){for(D=C(p[e]),_=C(p[e+1]),x=C(p[e+2]),k=C(p[e+3]),L=D^i[0],R=k^i[1],A=x^i[2],b=_^i[3],w=4,I=1;I<s;I++)y=o[L>>>24]^l[R>>16&255]^d[A>>8&255]^h[255&b]^i[w],E=o[R>>>24]^l[A>>16&255]^d[b>>8&255]^h[255&L]^i[w+1],T=o[A>>>24]^l[b>>16&255]^d[L>>8&255]^h[255&R]^i[w+2],S=o[b>>>24]^l[L>>16&255]^d[R>>8&255]^h[255&A]^i[w+3],L=y,R=E,A=T,b=S,w+=4;y=n[L>>>24]<<24^n[R>>16&255]<<16^n[A>>8&255]<<8^n[255&b]^i[w],E=n[R>>>24]<<24^n[A>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^i[w+1],T=n[A>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&R]^i[w+2],S=n[b>>>24]<<24^n[L>>16&255]<<16^n[R>>8&255]<<8^n[255&A]^i[w+3],v[e]=C(y^c),v[e+1]=C(S^f),v[e+2]=C(T^g),v[e+3]=C(E^m),c=D,f=_,g=x,m=k,e+=4}return v.buffer}}class Gr{constructor(t,{removePKCS7Padding:e=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=t.enableSoftwareAES,this.removePKCS7Padding=e,e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}null===this.subtle&&(this.useSoftware=!0)}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const r=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,r=e&&new DataView(t.buffer).getUint8(e-1);return r?H(t,0,e-r):t}(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,r){return this.useSoftware?new Promise(((s,i)=>{this.softwareDecrypt(new Uint8Array(t),e,r);const n=this.flush();n?s(n.buffer):i(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(t),e,r)}softwareDecrypt(t,e,r){const{currentIV:s,currentResult:i,remainderData:n}=this;this.logOnce("JS AES decrypt"),n&&(t=bt(n,t),this.remainderData=null);const a=this.getValidChunk(t);if(!a.length)return null;s&&(r=s);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new $r),o.expandKey(e);const l=i;return this.currentResult=o.decrypt(a.buffer,0,r),this.currentIV=H(a,-16).buffer,l||null}webCryptoDecrypt(t,e,r){const s=this.subtle;return this.key===e&&this.fastAesKey||(this.key=e,this.fastAesKey=new Ur(s,e)),this.fastAesKey.expandKey().then((e=>{if(!s)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Br(s,new Uint8Array(r)).decrypt(t.buffer,e)})).catch((s=>(D.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(t,e,r))))}onWebCryptoError(t,e,r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,r);const s=this.flush();if(s)return s.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const r=t.length-t.length%16;return r!==t.length&&(e=H(t,0,r),this.remainderData=H(t,r)),e}logOnce(t){this.logEnabled&&(D.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Hr=function(t){let e="";const r=t.length;for(let s=0;s<r;s++)e+=`[${t.start(s).toFixed(3)}-${t.end(s).toFixed(3)}]`;return e},Vr="STOPPED",Kr="IDLE",Wr="KEY_LOADING",Yr="FRAG_LOADING",jr="FRAG_LOADING_WAITING_RETRY",qr="PARSING",zr="PARSED",Xr="ENDED",Qr="ERROR",Jr="WAITING_LEVEL";class Zr extends Cr{constructor(t,e,r,s,i){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Vr,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=i,this.logPrefix=s,this.log=D.log.bind(D,`${s}:`),this.warn=D.warn.bind(D,`${s}:`),this.hls=t,this.fragmentLoader=new _r(t.config),this.keyLoader=r,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Gr(t.config),t.on(E.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Vr}_streamEnded(t,e){if(e.live||t.nextStart||!t.end||!this.media)return!1;const r=e.partList;if(null!=r&&r.length){const t=r[r.length-1];return Xe.isBuffered(this.media,t.start+t.duration/2)}const s=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(s)}getLevelDetails(){var t;if(this.levels&&null!==this.levelLastLoaded)return null==(t=this.levelLastLoaded)?void 0:t.details}onMediaAttached(t,e){const r=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),r.addEventListener("seeking",this.onvseeking),r.addEventListener("ended",this.onvended);const s=this.config;this.levels&&s.autoStartLoad&&this.state===Vr&&this.startLoad(s.startPosition)}onMediaDetaching(){const t=this.media;null!=t&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:t,fragCurrent:e,media:r,mediaBuffer:s,state:i}=this,n=r?r.currentTime:0,a=Xe.bufferInfo(s||r,n,t.maxBufferHole);if(this.log(`media seeking to ${p(n)?n.toFixed(3):n}, state: ${i}`),this.state===Xr)this.resetLoadingState();else if(e){const r=t.maxFragLookUpTolerance,s=e.start-r,i=e.start+e.duration+r;if(!a.len||i<a.start||s>a.end){const t=n>i;(n<s||t)&&(t&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}r&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),this.lastCurrentTime=n),this.loadedmetadata||a.len||(this.nextLoadPosition=this.startPosition=n),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(E.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=Vr,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,r){this._loadFragForPlayback(t,e,r)}_loadFragForPlayback(t,e,r){this._doFragLoad(t,e,r,(e=>{if(this.fragContextChanged(t))return this.warn(`Fragment ${t.sn}${e.part?" p: "+e.part.index:""} of level ${t.level} was dropped during download.`),void this.fragmentTracker.removeFragment(t);t.stats.chunkCount++,this._handleFragmentLoadProgress(e)})).then((e=>{if(!e)return;const r=this.state;this.fragContextChanged(t)?(r===Yr||!this.fragCurrent&&r===qr)&&(this.fragmentTracker.removeFragment(t),this.state=Kr):("payload"in e&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(E.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))})).catch((e=>{this.state!==Vr&&this.state!==Qr&&(this.warn(e),this.resetFragmentLoading(t))}))}clearTrackerIfNeeded(t){var e;const{fragmentTracker:r}=this;if(r.getState(t)===Tr){const e=t.type,s=this.getFwdBufferInfo(this.mediaBuffer,e),i=Math.max(t.duration,s?s.len:this.config.maxBufferLength);this.reduceMaxBufferLength(i)&&r.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?r.removeAllFragments():r.hasParts(t.type)&&(r.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),r.getState(t)===Sr&&r.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}flushMainBuffer(t,e,r=null){if(!(t-e))return;const s={startOffset:t,endOffset:e,type:r};this.hls.trigger(E.BUFFER_FLUSHING,s)}_loadInitSegment(t,e){this._doFragLoad(t,e).then((e=>{if(!e||this.fragContextChanged(t)||!this.levels)throw new Error("init load aborted");return e})).then((e=>{const{hls:r}=this,{payload:s}=e,i=t.decryptdata;if(s&&s.byteLength>0&&null!=i&&i.key&&i.iv&&"AES-128"===i.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer).catch((e=>{throw r.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((s=>{const i=self.performance.now();return r.trigger(E.FRAG_DECRYPTED,{frag:t,payload:s,stats:{tstart:n,tdecrypt:i}}),e.payload=s,this.completeInitSegmentLoad(e)}))}return this.completeInitSegmentLoad(e)})).catch((e=>{this.state!==Vr&&this.state!==Qr&&(this.warn(e),this.resetFragmentLoading(t))}))}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const r=t.frag.stats;this.state=Kr,t.frag.data=new Uint8Array(t.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.sn!==e.sn||t.level!==e.level}fragBufferedComplete(t,e){var r,s,i,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.playlistType===ne.MAIN?"level":"track"} ${t.level} (frag:[${(null!=(r=t.startPTS)?r:NaN).toFixed(3)}-${(null!=(s=t.endPTS)?s:NaN).toFixed(3)}] > buffer:${a?Hr(Xe.getBuffered(a)):"(detached)"})`),"initSegment"!==t.sn){var o;if(t.type!==ne.SUBTITLE){const e=t.elementaryStreams;if(!Object.keys(e).some((t=>!!e[t])))return void(this.state=Kr)}const e=null==(o=this.levels)?void 0:o[t.level];null!=e&&e.fragmentError&&(this.log(`Resetting level fragment error count of ${e.fragmentError} on frag buffered`),e.fragmentError=0)}this.state=Kr,a&&(!this.loadedmetadata&&t.type==ne.MAIN&&a.buffered.length&&(null==(i=this.fragCurrent)?void 0:i.sn)===(null==(n=this.fragPrevious)?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const{frag:r,part:s,partsLoaded:i}=t,n=!i||0===i.length||i.some((t=>!t)),a=new Pr(r.level,r.sn,r.stats.chunkCount+1,0,s?s.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,r=null,s){var i;const n=null==e?void 0:e.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let a=null;if(!t.encrypted||null!=(i=t.decryptdata)&&i.key?!t.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(t,n.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level}`),this.state=Wr,this.fragCurrent=t,a=this.keyLoader.load(t).then((t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(E.KEY_LOADED,t),this.state===Wr&&(this.state=Kr),t})),this.hls.trigger(E.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),r=Math.max(t.start,r||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){const i=n.partList;if(i&&s){r>t.end&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(i,t,r);if(o>-1){const l=i[o];let d;return this.log(`Loading part sn: ${t.sn} p: ${l.index} cc: ${t.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${o}-${i.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=Yr,d=a?a.then((r=>!r||this.fragContextChanged(r.frag)?null:this.doFragPartsLoad(t,l,e,s))).catch((t=>this.handleFragLoadError(t))):this.doFragPartsLoad(t,l,e,s).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(E.FRAG_LOADING,{frag:t,part:l,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!t.url||this.loadedEndOfParts(i,r))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(r.toFixed(3))}`),p(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Yr;const o=this.config.progressive;let l;return l=o&&a?a.then((e=>!e||this.fragContextChanged(null==e?void 0:e.frag)?null:this.fragmentLoader.load(t,s))).catch((t=>this.handleFragLoadError(t))):Promise.all([this.fragmentLoader.load(t,o?s:void 0),a]).then((([t])=>(!o&&t&&s&&s(t),t))).catch((t=>this.handleFragLoadError(t))),this.hls.trigger(E.FRAG_LOADING,{frag:t,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):l}doFragPartsLoad(t,e,r,s){return new Promise(((i,n)=>{var a;const o=[],l=null==(a=r.details)?void 0:a.partList,d=e=>{this.fragmentLoader.loadPart(t,e,s).then((s=>{o[e.index]=s;const n=s.part;this.hls.trigger(E.FRAG_LOADED,s);const a=xe(r,t.sn,e.index+1)||ke(l,t.sn,e.index+1);if(!a)return i({frag:t,part:n,partsLoaded:o});d(a)})).catch(n)};d(e)}))}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===S.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(E.ERROR,e)}else this.hls.trigger(E.ERROR,{type:T.OTHER_ERROR,details:S.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==qr)return void(this.fragCurrent||this.state===Vr||this.state===Qr||(this.state=Kr));const{frag:r,part:s,level:i}=e,n=self.performance.now();r.stats.parsing.end=n,s&&(s.stats.parsing.end=n),this.updateLevelTiming(r,s,i,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:r}=this,{level:s,sn:i,part:n}=t;if(null==e||!e[s])return this.warn(`Levels object was unset while buffering fragment ${i} of level ${s}. The current chunk will not be buffered.`),null;const a=e[s],o=n>-1?xe(a,i,n):null,l=o?o.fragment:function(t,e,r){if(null==t||!t.details)return null;const s=t.details;let i=s.fragments[e-s.startSN];return i||(i=s.fragmentHint,i&&i.sn===e?i:e<s.startSN&&r&&r.sn===e?r:null)}(a,i,r);return l?(r&&r!==l&&(l.stats=r.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(t,e,r,s,i){var n;if(!t||this.state!==qr)return;const{data1:a,data2:o}=t;let l=a;if(a&&o&&(l=bt(a,o)),null==(n=l)||!n.length)return;const d={type:t.type,frag:e,part:r,chunkMeta:s,parent:e.type,data:l};if(this.hls.trigger(E.BUFFER_APPENDING,d),t.dropped&&t.independent&&!r){if(i)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!Xe.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const r=e.currentTime,s=Xe.bufferInfo(e,r,0),i=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*i),a=Math.max(Math.min(t.start-n,s.end-n),r+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){const r=this.getLoadPosition();return p(r)?this.getFwdBufferInfoAtPos(t,r,e):null}getFwdBufferInfoAtPos(t,e,r){const{config:{maxBufferHole:s}}=this,i=Xe.bufferInfo(t,e,s);if(0===i.len&&void 0!==i.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,r);if(n&&i.nextStart<n.end)return Xe.bufferInfo(t,e,Math.max(i.nextStart,s))}return i}getMaxBufferLength(t){const{config:e}=this;let r;return r=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(r,e.maxMaxBufferLength)}reduceMaxBufferLength(t){const e=this.config,r=t||e.maxBufferLength;return e.maxMaxBufferLength>=r&&(e.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${e.maxMaxBufferLength}s`),!0)}getAppendedFrag(t,e=ne.MAIN){const r=this.fragmentTracker.getAppendedFrag(t,ne.MAIN);return r&&"fragment"in r?r.fragment:r}getNextFragment(t,e){const r=e.fragments,s=r.length;if(!s)return null;const{config:i}=this,n=r[0].start;let a;if(e.live){const o=i.initialLiveManifestSize;if(s<o)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${o})`),null;(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n)&&(a=this.getInitialLiveFragment(e,r),this.startPosition=this.nextLoadPosition=a?this.hls.liveSyncPosition||a.start:t)}else t<=n&&(a=r[0]);if(!a){const r=i.lowLatencyMode?e.partEnd:e.fragmentEnd;a=this.getFragmentAtPosition(t,r,e)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(t,e){const r=this.fragmentTracker.getState(t);return(r===Lr||r===Sr&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,r,s,i){const n=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(null===a)return a;if(t=a,n&&t&&!t.gap&&r.nextStart){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,s);if(null!==e&&r.len+e.len>=i)return this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${t.sn}`),null}return t}mapToInitFragWhenRequired(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment}getNextPart(t,e,r){let s=-1,i=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,s>-1&&r<o.start)break;const l=o.loaded;l?s=-1:(i||o.independent||n)&&o.fragment===e&&(s=a),i=l}return s}loadedEndOfParts(t,e){const r=t[t.length-1];return r&&e>r.start&&r.loaded}getInitialLiveFragment(t,e){const r=this.fragPrevious;let s=null;if(r){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`),s=function(t,e,r){if(null===e||!Array.isArray(t)||!t.length||!p(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;r=r||0;for(let s=0;s<t.length;++s){const i=t[s];if(Ue(e,r,i))return i}return null}(e,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const i=r.sn+1;if(i>=t.startSN&&i<=t.endSN){const n=e[i-t.startSN];r.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=function(t,e){return Oe(t,(t=>t.cc<e?1:t.cc>e?-1:0))}(e,r.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(s=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return s}getFragmentAtPosition(t,e,r){const{config:s}=this;let{fragPrevious:i}=this,{fragments:n,endSN:a}=r;const{fragmentHint:o}=r,l=s.maxFragLookUpTolerance,d=r.partList,h=!!(s.lowLatencyMode&&null!=d&&d.length&&o);let u;if(h&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),t<e){u=Ne(i,n,t,t>e-l?0:l)}else u=n[n.length-1];if(u){const t=u.sn-r.startSN,e=this.fragmentTracker.getState(u);if((e===Lr||e===Sr&&u.gap)&&(i=u),i&&u.sn===i.sn&&(!h||d[0].fragment.sn>u.sn)){if(i&&u.level===i.level){const e=n[t+1];u=u.sn<a&&this.fragmentTracker.getState(e)!==Lr?e:null}}}return u}synchronizeToLiveEdge(t){const{config:e,media:r}=this;if(!r)return;const s=this.hls.liveSyncPosition,i=r.currentTime,n=t.fragments[0].start,a=t.edge,o=i>=n-e.maxFragLookUpTolerance&&i<=a;if(null!==s&&r.duration>s&&(i<s||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!o&&r.readyState<4||i<a-n)&&(this.loadedmetadata||(this.nextLoadPosition=s),r.readyState&&(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s.toFixed(3)}`),r.currentTime=s))}}alignPlaylists(t,e,r){const s=t.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const i=t.fragments[0].start,n=!e,a=t.alignedSliding&&p(i);if(n||!a&&!i){const{fragPrevious:i}=this;Nr(i,r,t);const n=t.fragments[0].start;return this.log(`Live playlist sliding: ${n.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} prev-sn: ${i?i.sn:"na"} fragments: ${s}`),n}return i}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,e){let r=this.startPosition;if(r<e&&(r=-1),-1===r||-1===this.lastCurrentTime){const s=null!==this.startTimeOffset,i=s?this.startTimeOffset:t.startTimeOffset;null!==i&&p(i)?(r=e+i,i<0&&(r+=t.totalduration),r=Math.min(Math.max(e,r),e+t.totalduration),this.log(`Start time offset ${i} found in ${s?"multivariant":"media"} playlist, adjust startPosition to ${r}`),this.startPosition=r):t.live?r=this.hls.liveSyncPosition||e:this.startPosition=r=0,this.lastCurrentTime=r}this.nextLoadPosition=r}getLoadPosition(){const{media:t}=this;let e=0;return this.loadedmetadata&&t?e=t.currentTime:this.nextLoadPosition&&(e=this.nextLoadPosition),e}handleFragLoadAborted(t,e){this.transmuxer&&"initSegment"!==t.sn&&t.stats.aborted&&(this.warn(`Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===jr)||(this.state=Kr)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const r=e.frag;if(!r||r.type!==t||!this.levels)return;var s;if(this.fragContextChanged(r))return void this.warn(`Frag load error must match current frag to retry ${r.url} > ${null==(s=this.fragCurrent)?void 0:s.url}`);const i=e.details===S.FRAG_GAP;i&&this.fragmentTracker.fragBuffered(r,!0);const n=e.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===$e.RetryRequest&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const s=Pe(l,o);this.warn(`Fragment ${r.sn} of ${t} ${r.level} errored with ${e.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${s}ms`),n.resolved=!0,this.retryDate=self.performance.now()+s,this.state=jr}else if(l&&n){if(this.resetFragmentErrors(t),!(o<l.maxNumRetry))return void D.warn(`${e.details} reached or exceeded max retry (${o})`);i||a===$e.RemoveAlternatePermanently||(n.resolved=!0)}else(null==n?void 0:n.action)===$e.SendAlternateToPenaltyBox?this.state=Jr:this.state=Qr;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===qr||this.state===zr){const e=t.parent,r=this.getFwdBufferInfo(this.mediaBuffer,e),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len);const i=!s;return i&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${e} buffer`),t.frag&&(this.fragmentTracker.removeFragment(t.frag),this.nextLoadPosition=t.frag.start),this.resetLoadingState(),i}return!1}resetFragmentErrors(t){t===ne.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Vr&&(this.state=Kr)}afterBufferFlushed(t,e,r){if(!t)return;const s=Xe.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,s,r),this.state===Xr&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Kr}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=t?t.details:null;null!=e&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.warn(`The loading context changed while buffering fragment ${t.sn} of level ${t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,r,s){var i;const n=r.details;if(!n)return void this.warn("level.details undefined");if(!Object.keys(t.elementaryStreams).reduce(((e,i)=>{const a=t.elementaryStreams[i];if(a){const o=a.endPTS-a.startPTS;if(o<=0)return this.warn(`Could not parse fragment ${t.sn} ${i} duration reliably (${o})`),e||!1;const l=s?0:be(n,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(E.LEVEL_PTS_UPDATED,{details:n,level:r,drift:l,type:i,frag:t,start:a.startPTS,end:a.endPTS}),!0}return e}),!1)&&null===(null==(i=this.transmuxer)?void 0:i.error)){const e=new Error(`Found no media in fragment ${t.sn} of level ${t.level} resetting transmuxer to fallback to playlist timing`);if(0===r.fragmentError&&(r.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(e.message),this.hls.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of level "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=zr,this.hls.trigger(E.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function ts(){return self.SourceBuffer||self.WebKitSourceBuffer}function es(){if(!It())return!1;const t=ts();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}function rs(){if(!es())return!1;const t=It();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((e=>t.isTypeSupported(Mt(e,"video"))))||["mp4a.40.2","fLaC"].some((e=>t.isTypeSupported(Mt(e,"audio")))))}function ss(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class is{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,r,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,r){}demux(t,e){this.cachedData&&(t=bt(this.cachedData,t),this.cachedData=null);let r,s=W(t,0),i=s?s.length:0;const n=this._audioTrack,a=this._id3Track,o=s?q(s):void 0,l=t.length;for((null===this.basePTS||0===this.frameIndex&&p(o))&&(this.basePTS=ns(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),s&&s.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ue.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(t,i)){const e=this.appendFrame(n,t,i);e?(this.frameIndex++,this.lastPTS=e.sample.pts,i+=e.length,r=i):i=l}else j(t,i)?(s=W(t,i),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:ue.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const e=H(t,r);this.cachedData?this.cachedData=bt(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:ss(),id3Track:a,textTrack:ss()}}demuxSampleAes(t,e,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:ss(),id3Track:this._id3Track,textTrack:ss()}}destroy(){}}const ns=(t,e,r)=>{if(p(t))return 90*t;return 9e4*e+(r?9e4*r.baseTime/r.timescale:0)};function as(t,e){return 255===t[e]&&240==(246&t[e+1])}function os(t,e){return 1&t[e+1]?7:9}function ls(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function ds(t,e){return e+1<t.length&&as(t,e)}function hs(t,e){if(ds(t,e)){const r=os(t,e);if(e+r>=t.length)return!1;const s=ls(t,e);if(s<=r)return!1;const i=e+s;return i===t.length||ds(t,i)}return!1}function us(t,e,r,s,i){if(!t.samplerate){const n=function(t,e,r,s){let i,n,a,o;const l=navigator.userAgent.toLowerCase(),d=s,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=1+((192&e[r+2])>>>6);const u=(60&e[r+2])>>>2;if(!(u>h.length-1))return a=(1&e[r+2])<<2,a|=(192&e[r+3])>>>6,D.log(`manifest codec:${s}, ADTS type:${i}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(i=5,o=new Array(4),n=u-3):(i=2,o=new Array(2),n=u):-1!==l.indexOf("android")?(i=2,o=new Array(2),n=u):(i=5,o=new Array(4),s&&(-1!==s.indexOf("mp4a.40.29")||-1!==s.indexOf("mp4a.40.5"))||!s&&u>=6?n=u-3:((s&&-1!==s.indexOf("mp4a.40.2")&&(u>=6&&1===a||/vivaldi/i.test(l))||!s&&1===a)&&(i=2,o=new Array(2)),n=u)),o[0]=i<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=a<<3,5===i&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:h[u],channelCount:a,codec:"mp4a.40."+i,manifestCodec:d};{const e=new Error(`invalid ADTS sampling index:${u}`);t.emit(E.ERROR,E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}}(e,r,s,i);if(!n)return;t.config=n.config,t.samplerate=n.samplerate,t.channelCount=n.channelCount,t.codec=n.codec,t.manifestCodec=n.manifestCodec,D.log(`parsed codec:${t.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function cs(t){return 9216e4/t}function fs(t,e,r,s,i){const n=s+i*cs(t.samplerate),a=function(t,e){const r=os(t,e);if(e+r<=t.length){const s=ls(t,e)-r;if(s>0)return{headerLength:r,frameLength:s}}}(e,r);let o;if(a){const{frameLength:s,headerLength:i}=a,l=i+s,d=Math.max(0,r+l-e.length);d?(o=new Uint8Array(l-i),o.set(e.subarray(r+i,e.length),0)):o=e.subarray(r+i,r+l);const h={unit:o,pts:n};return d||t.samples.push(h),{sample:h,length:l,missing:d}}const l=e.length-r;o=new Uint8Array(l),o.set(e.subarray(r,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let gs=null;const ms=[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],ps=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],vs=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ys=[0,1,1,4];function Es(t,e,r,s,i){if(r+24>e.length)return;const n=Ts(e,r);if(n&&r+n.frameLength<=e.length){const a=s+i*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(r,r+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Ts(t,e){const r=t[e+1]>>3&3,s=t[e+1]>>1&3,i=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==r&&0!==i&&15!==i&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*ms[14*(3===r?3-s:3===s?3:4)+i-1],d=ps[3*(3===r?0:2===r?1:2)+n],h=3===o?1:2,u=vs[r][s],c=ys[s],f=8*u*c,g=Math.floor(u*l/d+a)*c;if(null===gs){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);gs=t?parseInt(t[1]):0}return!!gs&&gs<=87&&2===s&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function Ss(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function Ls(t,e){return e+1<t.length&&Ss(t,e)}function Rs(t,e){if(e+1<t.length&&Ss(t,e)){const r=4,s=Ts(t,e);let i=r;null!=s&&s.frameLength&&(i=s.frameLength);const n=e+i;return n===t.length||Ls(t,n)}return!1}const As=/\/emsg[-/]ID3/i;class bs{constructor(){this.VideoSample=null}createVideoSample(t,e,r,s){return{key:t,frame:!1,pts:e,dts:r,units:[],debug:s,length:0}}getLastNalUnit(t){var e;let r,s=this.VideoSample;if(s&&0!==s.units.length||(s=t[t.length-1]),null!=(e=s)&&e.units){const t=s.units;r=t[t.length-1]}return r}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const r=e.samples,s=r.length;if(!s)return void e.dropped++;{const e=r[s-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}t.debug.length&&D.log(t.pts+"/"+t.dts+":"+t.debug)}}class Ds{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,r=t.byteLength-e,s=new Uint8Array(4),i=Math.min(4,e);if(0===i)throw new Error("no bytes available");s.set(t.subarray(r,r+i)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*i,this.bytesAvailable-=i}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const r=this.word>>>32-e;if(t>32&&D.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?r<<e|this.readBits(e):r}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(t){let e,r=8,s=8;for(let i=0;i<t;i++)0!==s&&(e=this.readEG(),s=(r+e+256)%256),r=0===s?r:s}readSPS(){let t,e,r,s=0,i=0,n=0,a=0;const o=this.readUByte.bind(this),l=this.readBits.bind(this),d=this.readUEG.bind(this),h=this.readBoolean.bind(this),u=this.skipBits.bind(this),c=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);o();const m=o();if(l(5),u(3),o(),f(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){const t=d();if(3===t&&u(1),f(),f(),u(1),h())for(e=3!==t?8:12,r=0;r<e;r++)h()&&g(r<6?16:64)}f();const p=d();if(0===p)d();else if(1===p)for(u(1),c(),c(),t=d(),r=0;r<t;r++)c();f(),u(1);const v=d(),y=d(),E=l(1);0===E&&u(1),u(1),h()&&(s=d(),i=d(),n=d(),a=d());let T=[1,1];if(h()&&h()){switch(o()){case 1:T=[1,1];break;case 2:T=[12,11];break;case 3:T=[10,11];break;case 4:T=[16,11];break;case 5:T=[40,33];break;case 6:T=[24,11];break;case 7:T=[20,11];break;case 8:T=[32,11];break;case 9:T=[80,33];break;case 10:T=[18,11];break;case 11:T=[15,11];break;case 12:T=[64,33];break;case 13:T=[160,99];break;case 14:T=[4,3];break;case 15:T=[3,2];break;case 16:T=[2,1];break;case 255:T=[o()<<8|o(),o()<<8|o()]}}return{width:Math.ceil(16*(v+1)-2*s-2*i),height:(2-E)*(y+1)*16-(E?2:4)*(n+a),pixelRatio:T}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class _s extends bs{parseAVCPES(t,e,r,s,i){const n=this.parseAVCNALu(t,r.data);let a,o=this.VideoSample,l=!1;r.data=null,o&&n.length&&!t.audFound&&(this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts,"")),n.forEach((s=>{var n;switch(s.type){case 1:{let e=!1;a=!0;const i=s.data;if(l&&i.length>4){const t=new Ds(i).readSliceType();2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var d;if(e)null!=(d=o)&&d.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts,"")),o.frame=!0,o.key=e;break}case 5:a=!0,null!=(n=o)&&n.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,xt(s.data,1,r.pts,e.samples);break;case 7:{var h,u;a=!0,l=!0;const e=s.data,r=new Ds(e).readSPS();if(!t.sps||t.width!==r.width||t.height!==r.height||(null==(h=t.pixelRatio)?void 0:h[0])!==r.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==r.pixelRatio[1]){t.width=r.width,t.height=r.height,t.pixelRatio=r.pixelRatio,t.sps=[e],t.duration=i;const s=e.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let e=s[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}break}case 8:a=!0,t.pps=[s.data];break;case 9:a=!0,t.audFound=!0,o&&this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+s.type+" ")}if(o&&a){o.units.push(s)}})),s&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)}parseAVCNALu(t,e){const r=e.byteLength;let s=t.naluState||0;const i=s,n=[];let a,o,l,d=0,h=-1,u=0;for(-1===s&&(h=0,u=31&e[0],s=0,d=1);d<r;)if(a=e[d++],s)if(1!==s)if(a)if(1===a){if(o=d-s-1,h>=0){const t={data:e.subarray(h,o),type:u};n.push(t)}else{const r=this.getLastNalUnit(t.samples);r&&(i&&d<=4-i&&r.state&&(r.data=r.data.subarray(0,r.data.byteLength-i)),o>0&&(r.data=bt(r.data,e.subarray(0,o)),r.state=0))}d<r?(l=31&e[d],h=d,u=l,s=0):s=-1}else s=0;else s=3;else s=a?0:2;else s=a?0:1;if(h>=0&&s>=0){const t={data:e.subarray(h,r),type:u,state:s};n.push(t)}if(0===n.length){const r=this.getLastNalUnit(t.samples);r&&(r.data=bt(r.data,e))}return t.naluState=s,n}}class xs{constructor(t,e,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new Gr(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,r){const s=t[e].unit;if(s.length<=16)return;const i=s.subarray(16,s.length-s.length%16),n=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(n).then((i=>{const n=new Uint8Array(i);s.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,r)}))}decryptAacSamples(t,e,r){for(;;e++){if(e>=t.length)return void r();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e);let s=0;for(let e=32;e<t.length-16;e+=160,s+=16)r.set(t.subarray(e,e+16),s);return r}getAvcDecryptedUnit(t,e){const r=new Uint8Array(e);let s=0;for(let e=32;e<t.length-16;e+=160,s+=16)t.set(r.subarray(s,s+16),e);return t}decryptAvcSample(t,e,r,s,i){const n=kt(i.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then((a=>{i.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,r+1,s)}))}decryptAvcSamples(t,e,r,s){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,r=0){if(e>=t.length)return void s();const i=t[e].units;for(;!(r>=i.length);r++){const n=i[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,r,s,n),this.decrypter.isSync())))return}}}}const ks=188;class ws{constructor(t,e,r){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._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=e,this.typeSupported=r,this.videoParser=new _s}static probe(t){const e=ws.syncOffset(t);return e>0&&D.warn(`MPEG2-TS detected but first sync word found @ offset ${e}`),-1!==e}static syncOffset(t){const e=t.length;let r=Math.min(940,e-ks)+1,s=0;for(;s<r;){let i=!1,n=-1,a=0;for(let o=s;o<e;o+=ks){if(71!==t[o]||e-o!==ks&&71!==t[o+ks]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(r=Math.min(n+18612,t.length-ks)+1)),i||(i=0===Is(t,o)),i&&a>1&&(0===n&&a>2||o+ks>r))return n}s++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:dt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,r,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ws.createTrack("video"),this._audioTrack=ws.createTrack("audio",s),this._id3Track=ws.createTrack("id3"),this._txtTrack=ws.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=r,this._duration=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:r}=this;t&&(t.pesData=null),e&&(e.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,r=!1,s=!1){let i;r||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let d=n.pid,h=n.pesData,u=a.pid,c=o.pid,f=a.pesData,g=o.pesData,m=null,p=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&(y=(t=bt(this.remainderData,t)).length,this.remainderData=null),y<ks&&!s)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const L=Math.max(0,ws.syncOffset(t));y-=(y-L)%ks,y<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let R=0;for(let e=L;e<y;e+=ks)if(71===t[e]){const s=!!(64&t[e+1]),y=Is(t,e);let E;if((48&t[e+3])>>4>1){if(E=e+5+t[e+4],E===e+ks)continue}else E=e+4;switch(y){case d:s&&(h&&(i=Ms(h))&&this.videoParser.parseAVCPES(n,l,i,!1,this._duration),h={data:[],size:0}),h&&(h.data.push(t.subarray(E,e+ks)),h.size+=e+ks-E);break;case u:if(s){if(f&&(i=Ms(f)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,i);break;case"mp3":this.parseMPEGPES(a,i)}f={data:[],size:0}}f&&(f.data.push(t.subarray(E,e+ks)),f.size+=e+ks-E);break;case c:s&&(g&&(i=Ms(g))&&this.parseID3PES(o,i),g={data:[],size:0}),g&&(g.data.push(t.subarray(E,e+ks)),g.size+=e+ks-E);break;case 0:s&&(E+=t[E]+1),v=this._pmtId=Cs(t,E);break;case v:{s&&(E+=t[E]+1);const i=Ps(t,E,this.typeSupported,r);d=i.videoPid,d>0&&(n.pid=d,n.segmentCodec=i.segmentVideoCodec),u=i.audioPid,u>0&&(a.pid=u,a.segmentCodec=i.segmentAudioCodec),c=i.id3Pid,c>0&&(o.pid=c),null===m||p||(D.warn(`MPEG-TS PMT found at ${e} after unknown PID '${m}'. Backtracking to sync byte @${L} to parse all TS packets.`),m=null,e=L-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=y}}else R++;if(R>0){const t=new Error(`Found ${R} TS packet/s that do not start with 0x47`);this.observer.emit(E.ERROR,E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message})}n.pesData=h,a.pesData=f,o.pesData=g;const A={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return s&&this.extractRemainingSamples(A),A}flush(){const{remainderData:t}=this;let e;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(t){const{audioTrack:e,videoTrack:r,id3Track:s,textTrack:i}=t,n=r.pesData,a=e.pesData,o=s.pesData;let l;if(n&&(l=Ms(n))?(this.videoParser.parseAVCPES(r,i,l,!0,this._duration),r.pesData=null):r.pesData=n,a&&(l=Ms(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l)}e.pesData=null}else null!=a&&a.size&&D.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=Ms(o))?(this.parseID3PES(s,l),s.pesData=null):s.pesData=o}demuxSampleAes(t,e,r){const s=this.demux(t,r,!0,!this.config.progressive),i=this.sampleAes=new xs(this.observer,this.config,e);return this.decrypt(s,i)}decrypt(t,e){return new Promise((r=>{const{audioTrack:s,videoTrack:i}=t;s.samples&&"aac"===s.segmentCodec?e.decryptAacSamples(s.samples,0,(()=>{i.samples?e.decryptAvcSamples(i.samples,0,0,(()=>{r(t)})):r(t)})):i.samples&&e.decryptAvcSamples(i.samples,0,0,(()=>{r(t)}))}))}destroy(){this._duration=0}parseAACPES(t,e){let r=0;const s=this.aacOverFlow;let i,n,a,o=e.data;if(s){this.aacOverFlow=null;const e=s.missing,i=s.sample.unit.byteLength;if(-1===e)o=bt(s.sample.unit,o);else{const n=i-e;s.sample.unit.set(o.subarray(0,e),n),t.samples.push(s.sample),r=s.missing}}for(i=r,n=o.length;i<n-1&&!ds(o,i);i++);if(i!==r){let t;const e=i<n-1;t=e?`AAC PES did not start with ADTS header,offset:${i}`:"No ADTS header found in AAC PES";const r=new Error(t);if(D.warn(`parsing error: ${t}`),this.observer.emit(E.ERROR,E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_PARSING_ERROR,fatal:!1,levelRetry:e,error:r,reason:t}),!e)return}if(us(t,this.observer,o,i,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!s)return void D.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=cs(t.samplerate);a=s.sample.pts+e}}let l,d=0;for(;i<n;){if(l=fs(t,o,i,a,d),i+=l.length,l.missing){this.aacOverFlow=l;break}for(d++;i<n-1&&!ds(o,i);i++);}}parseMPEGPES(t,e){const r=e.data,s=r.length;let i=0,n=0;const a=e.pts;if(void 0!==a)for(;n<s;)if(Ls(r,n)){const e=Es(t,r,n,a,i);if(!e)break;n+=e.length,i++}else n++;else D.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){}parseID3PES(t,e){if(void 0===e.pts)return void D.warn("[tsdemuxer]: ID3 PES unknown PTS");const r=m({},e,{type:this._videoTrack?ue.emsg:ue.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}}function Is(t,e){return((31&t[e+1])<<8)+t[e+2]}function Cs(t,e){return(31&t[e+10])<<8|t[e+11]}function Ps(t,e,r,s){const i={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},n=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<n;){const n=Is(t,e),a=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!s){Fs("ADTS AAC");break}case 15:-1===i.audioPid&&(i.audioPid=n);break;case 21:-1===i.id3Pid&&(i.id3Pid=n);break;case 219:if(!s){Fs("H.264");break}case 27:-1===i.videoPid&&(i.videoPid=n,i.segmentVideoCodec="avc");break;case 3:case 4:r.mpeg||r.mp3?-1===i.audioPid&&(i.audioPid=n,i.segmentAudioCodec="mp3"):D.log("MPEG audio found, not supported in this browser");break;case 193:if(!s){Fs("AC-3");break}case 129:D.warn("AC-3 in M2TS support not included in build");break;case 6:if(-1===i.audioPid&&a>0){let r=e+5,s=a;for(;s>2;){if(106===t[r])D.warn("AC-3 in M2TS support not included in build");const e=t[r+1]+2;r+=e,s-=e}}break;case 194:case 135:D.warn("Unsupported EC-3 in M2TS found");break;case 36:D.warn("Unsupported HEVC in M2TS found")}e+=a+5}return i}function Fs(t){D.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Ms(t){let e,r,s,i,n,a=0;const o=t.data;if(!t||0===t.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=bt(o[0],o[1]),o.splice(1,1);e=o[0];if(1===(e[0]<<16)+(e[1]<<8)+e[2]){if(r=(e[4]<<8)+e[5],r&&r>t.size-6)return null;const l=e[7];192&l&&(i=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&l?(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2,i-n>54e5&&(D.warn(`${Math.round((i-n)/9e4)}s delta between PTS and DTS, align them`),i=n)):n=i),s=e[8];let d=s+9;if(t.size<=d)return null;t.size-=d;const h=new Uint8Array(t.size);for(let t=0,r=o.length;t<r;t++){e=o[t];let r=e.byteLength;if(d){if(d>r){d-=r;continue}e=e.subarray(d),r-=d,d=0}h.set(e,a),a+=r}return r&&(r-=s+3),{data:h,pts:i,dts:n,len:r}}return null}class Os{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const Ns=Math.pow(2,32)-1;class Bs{static init(){let t;for(t in Bs.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},Bs.types)Bs.types.hasOwnProperty(t)&&(Bs.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const e=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);Bs.HDLR_TYPES={video:e,audio:r};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),i=new Uint8Array([0,0,0,0,0,0,0,0]);Bs.STTS=Bs.STSC=Bs.STCO=i,Bs.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Bs.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Bs.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Bs.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),a=new Uint8Array([97,118,99,49]),o=new Uint8Array([0,0,0,1]);Bs.FTYP=Bs.box(Bs.types.ftyp,n,o,n,a),Bs.DINF=Bs.box(Bs.types.dinf,Bs.box(Bs.types.dref,s))}static box(t,...e){let r=8,s=e.length;const i=s;for(;s--;)r+=e[s].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(t,4),s=0,r=8;s<i;s++)n.set(e[s],r),r+=e[s].byteLength;return n}static hdlr(t){return Bs.box(Bs.types.hdlr,Bs.HDLR_TYPES[t])}static mdat(t){return Bs.box(Bs.types.mdat,t)}static mdhd(t,e){e*=t;const r=Math.floor(e/(Ns+1)),s=Math.floor(e%(Ns+1));return Bs.box(Bs.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))}static mdia(t){return Bs.box(Bs.types.mdia,Bs.mdhd(t.timescale,t.duration),Bs.hdlr(t.type),Bs.minf(t))}static mfhd(t){return Bs.box(Bs.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Bs.box(Bs.types.minf,Bs.box(Bs.types.smhd,Bs.SMHD),Bs.DINF,Bs.stbl(t)):Bs.box(Bs.types.minf,Bs.box(Bs.types.vmhd,Bs.VMHD),Bs.DINF,Bs.stbl(t))}static moof(t,e,r){return Bs.box(Bs.types.moof,Bs.mfhd(t),Bs.traf(r,e))}static moov(t){let e=t.length;const r=[];for(;e--;)r[e]=Bs.trak(t[e]);return Bs.box.apply(null,[Bs.types.moov,Bs.mvhd(t[0].timescale,t[0].duration)].concat(r).concat(Bs.mvex(t)))}static mvex(t){let e=t.length;const r=[];for(;e--;)r[e]=Bs.trex(t[e]);return Bs.box.apply(null,[Bs.types.mvex,...r])}static mvhd(t,e){e*=t;const r=Math.floor(e/(Ns+1)),s=Math.floor(e%(Ns+1)),i=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,r>>24,r>>16&255,r>>8&255,255&r,s>>24,s>>16&255,s>>8&255,255&s,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 Bs.box(Bs.types.mvhd,i)}static sdtp(t){const e=t.samples||[],r=new Uint8Array(4+e.length);let s,i;for(s=0;s<e.length;s++)i=e[s].flags,r[s+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return Bs.box(Bs.types.sdtp,r)}static stbl(t){return Bs.box(Bs.types.stbl,Bs.stsd(t),Bs.box(Bs.types.stts,Bs.STTS),Bs.box(Bs.types.stsc,Bs.STSC),Bs.box(Bs.types.stsz,Bs.STSZ),Bs.box(Bs.types.stco,Bs.STCO))}static avc1(t){let e,r,s,i=[],n=[];for(e=0;e<t.sps.length;e++)r=t.sps[e],s=r.byteLength,i.push(s>>>8&255),i.push(255&s),i=i.concat(Array.prototype.slice.call(r));for(e=0;e<t.pps.length;e++)r=t.pps[e],s=r.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(r));const a=Bs.box(Bs.types.avcC,new Uint8Array([1,i[3],i[4],i[5],255,224|t.sps.length].concat(i).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return Bs.box(Bs.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Bs.box(Bs.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Bs.box(Bs.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))}static esds(t){const e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))}static audioStsd(t){const e=t.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Bs.box(Bs.types.mp4a,Bs.audioStsd(t),Bs.box(Bs.types.esds,Bs.esds(t)))}static mp3(t){return Bs.box(Bs.types[".mp3"],Bs.audioStsd(t))}static ac3(t){return Bs.box(Bs.types["ac-3"],Bs.audioStsd(t),Bs.box(Bs.types.dac3,t.config))}static stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?Bs.box(Bs.types.stsd,Bs.STSD,Bs.mp3(t)):"ac3"===t.segmentCodec?Bs.box(Bs.types.stsd,Bs.STSD,Bs.ac3(t)):Bs.box(Bs.types.stsd,Bs.STSD,Bs.mp4a(t)):Bs.box(Bs.types.stsd,Bs.STSD,Bs.avc1(t))}static tkhd(t){const e=t.id,r=t.duration*t.timescale,s=t.width,i=t.height,n=Math.floor(r/(Ns+1)),a=Math.floor(r%(Ns+1));return Bs.box(Bs.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,255&s,0,0,i>>8&255,255&i,0,0]))}static traf(t,e){const r=Bs.sdtp(t),s=t.id,i=Math.floor(e/(Ns+1)),n=Math.floor(e%(Ns+1));return Bs.box(Bs.types.traf,Bs.box(Bs.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),Bs.box(Bs.types.tfdt,new Uint8Array([1,0,0,0,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n])),Bs.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,Bs.box(Bs.types.trak,Bs.tkhd(t),Bs.mdia(t))}static trex(t){const e=t.id;return Bs.box(Bs.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const r=t.samples||[],s=r.length,i=12+16*s,n=new Uint8Array(i);let a,o,l,d,h,u;for(e+=8+i,n.set(["video"===t.type?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,255&s,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<s;a++)o=r[a],l=o.duration,d=o.size,h=o.flags,u=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,61440&h.degradPrio,15&h.degradPrio,u>>>24&255,u>>>16&255,u>>>8&255,255&u],12+16*a);return Bs.box(Bs.types.trun,n)}static initSegment(t){Bs.types||Bs.init();const e=Bs.moov(t);return bt(Bs.FTYP,e)}}Bs.types=void 0,Bs.HDLR_TYPES=void 0,Bs.STTS=void 0,Bs.STSC=void 0,Bs.STCO=void 0,Bs.STSZ=void 0,Bs.VMHD=void 0,Bs.SMHD=void 0,Bs.STSD=void 0,Bs.FTYP=void 0,Bs.DINF=void 0;function Us(t,e=!1){return function(t,e,r=1,s=!1){const i=t*e*r;return s?Math.round(i):i}(t,1e3,1/9e4,e)}let $s=null,Gs=null;class Hs{constructor(t,e,r,s=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=r,this.ISGenerated=!1,null===$s){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);$s=t?parseInt(t[1]):0}if(null===Gs){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Gs=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){D.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){D.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){D.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const r=t.reduce(((t,r)=>{const s=r.pts-t;return s<-4294967296?(e=!0,Vs(t,r.pts)):s>0?t:r.pts}),t[0].pts);return e&&D.debug("PTS rollover detected"),r}remux(t,e,r,s,i,n,a,o){let l,d,h,u,c,f,g=i,m=i;const p=t.pid>-1,v=e.pid>-1,y=e.samples.length,E=t.samples.length>0,T=a&&y>0||y>1;if((!p||E)&&(!v||T)||this.ISGenerated||a){if(this.ISGenerated){var S,L,R,A;const t=this.videoTrackConfig;!t||e.width===t.width&&e.height===t.height&&(null==(S=e.pixelRatio)?void 0:S[0])===(null==(L=t.pixelRatio)?void 0:L[0])&&(null==(R=e.pixelRatio)?void 0:R[1])===(null==(A=t.pixelRatio)?void 0:A[1])||this.resetInitSegment()}else h=this.generateIS(t,e,i,n);const r=this.isVideoContiguous;let s,a=-1;if(T&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!r&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){D.warn(`[mp4-remuxer]: Dropped ${a} out of ${y} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,m+=(e.samples[0].pts-t)/e.inputTimeScale,s=m}else-1===a&&(D.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),f=!1);if(this.ISGenerated){if(E&&T){const r=this.getVideoStartPts(e.samples),s=(Vs(t.samples[0].pts,r)-r)/e.inputTimeScale;g+=Math.max(0,s),m+=Math.max(0,-s)}if(E){if(t.samplerate||(D.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(t,e,i,n)),d=this.remuxAudio(t,g,this.isAudioContiguous,n,v||T||o===ne.AUDIO?m:void 0),T){const s=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(D.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(t,e,i,n)),l=this.remuxVideo(e,m,r,s)}}else T&&(l=this.remuxVideo(e,m,r,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(c=Ks(r,i,this._initPTS,this._initDTS)),s.samples.length&&(u=Ws(s,i,this._initPTS))),{audio:d,video:l,initSegment:h,independent:f,text:u,id3:c}}generateIS(t,e,r,s){const i=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let d,h,u,c=!l||s,f="audio/mp4";if(c&&(d=h=1/0),t.config&&i.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":a.mpeg?(f="audio/mpeg",t.codec=""):a.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}o.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&a.mpeg?new Uint8Array(0):Bs.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(u=t.inputTimeScale,l&&u===l.timescale?c=!1:d=h=i[0].pts-Math.round(u*r))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Bs.initSegment([e]),metadata:{width:e.width,height:e.height}},c)if(u=e.inputTimeScale,l&&u===l.timescale)c=!1;else{const t=this.getVideoStartPts(n),e=Math.round(u*r);h=Math.min(h,Vs(n[0].dts,t)-e),d=Math.min(d,t-e)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:d,timescale:u},this._initDTS={baseTime:h,timescale:u}):d=u=void 0,{tracks:o,initPTS:d,timescale:u}}remuxVideo(t,e,r,s){const i=t.inputTimeScale,n=t.samples,a=[],o=n.length,l=this._initPTS;let d,h,u=this.nextAvcDts,c=8,f=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!r||null===u){const t=e*i,s=n[0].pts-Vs(n[0].dts,n[0].pts);$s&&null!==u&&Math.abs(t-s-u)<15e3?r=!0:u=t-s}const y=l.baseTime*i/l.timescale;for(let t=0;t<o;t++){const e=n[t];e.pts=Vs(e.pts-y,u),e.dts=Vs(e.dts-y,u),e.dts<n[t>0?t-1:t].dts&&(v=!0)}v&&n.sort((function(t,e){const r=t.dts-e.dts,s=t.pts-e.pts;return r||s})),d=n[0].dts,h=n[n.length-1].dts;const L=h-d,R=L?Math.round(L/(o-1)):f||t.inputTimeScale/30;if(r){const t=d-u,r=t>R,s=t<-1;if((r||s)&&(r?D.warn(`AVC: ${Us(t,!0)} ms (${t}dts) hole between fragments detected at ${e.toFixed(3)}`):D.warn(`AVC: ${Us(-t,!0)} ms (${t}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!s||u>=n[0].pts||$s)){d=u;const e=n[0].pts-t;if(r)n[0].dts=d,n[0].pts=e;else for(let r=0;r<n.length&&!(n[r].dts>e);r++)n[r].dts-=t,n[r].pts-=t;D.log(`Video: Initial PTS/DTS adjusted: ${Us(e,!0)}/${Us(d,!0)}, delta: ${Us(t,!0)} ms`)}}d=Math.max(0,d);let A=0,b=0,_=d;for(let t=0;t<o;t++){const e=n[t],r=e.units,s=r.length;let i=0;for(let t=0;t<s;t++)i+=r[t].data.length;b+=i,A+=s,e.length=i,e.dts<_?(e.dts=_,_+=R/4|0||1):_=e.dts,g=Math.min(e.pts,g),p=Math.max(e.pts,p)}h=n[o-1].dts;const x=b+4*A+8;let k;try{k=new Uint8Array(x)}catch(t){return void this.observer.emit(E.ERROR,E.ERROR,{type:T.MUX_ERROR,details:S.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:x,reason:`fail allocating video mdat ${x}`})}const w=new DataView(k.buffer);w.setUint32(0,x),k.set(Bs.types.mdat,4);let I=!1,C=Number.POSITIVE_INFINITY,P=Number.POSITIVE_INFINITY,F=Number.NEGATIVE_INFINITY,M=Number.NEGATIVE_INFINITY;for(let t=0;t<o;t++){const e=n[t],r=e.units;let l,d=0;for(let t=0,e=r.length;t<e;t++){const e=r[t],s=e.data,i=e.data.byteLength;w.setUint32(c,i),c+=4,k.set(s,c),c+=i,d+=4+i}if(t<o-1)f=n[t+1].dts-e.dts,l=n[t+1].pts-e.pts;else{const r=this.config,a=t>0?e.dts-n[t-1].dts:R;if(l=t>0?e.pts-n[t-1].pts:R,r.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(r.maxBufferHole*i),n=(s?g+s*i:this.nextAudioPts)-e.pts;n>t?(f=n-a,f<0?f=a:I=!0,D.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=a}else f=a}const h=Math.round(e.pts-e.dts);C=Math.min(C,f),F=Math.max(F,f),P=Math.min(P,l),M=Math.max(M,l),a.push(new Ys(e.key,f,d,h))}if(a.length)if($s){if($s<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Gs&&M-P<F-C&&R/F<.025&&0===a[0].cts){D.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=d;for(let e=0,r=a.length;e<r;e++){const s=t+a[e].duration,i=t+a[e].cts;if(e<r-1){const t=s+a[e+1].cts;a[e].duration=t-i}else a[e].duration=e?a[e-1].duration:R;a[e].cts=0,t=s}}f=I||!f?R:f,this.nextAvcDts=u=h+f,this.videoSampleDuration=f,this.isVideoContiguous=!0;const O={data1:Bs.moof(t.sequenceNumber++,d,m({},t,{samples:a})),data2:k,startPTS:g/i,endPTS:(p+f)/i,startDTS:d/i,endDTS:u/i,type:"video",hasAudio:!1,hasVideo:!0,nb:a.length,dropped:t.dropped};return t.samples=[],t.dropped=0,O}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,r,s,i){const n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),o=this.getSamplesPerFrame(t),l=o*a,d=this._initPTS,h="mp3"===t.segmentCodec&&this.typeSupported.mpeg,u=[],c=void 0!==i;let f=t.samples,g=h?0:8,p=this.nextAudioPts||-1;const v=e*n,y=d.baseTime*n/d.timescale;if(this.isAudioContiguous=r=r||f.length&&p>0&&(s&&Math.abs(v-p)<9e3||Math.abs(Vs(f[0].pts-y,v)-p)<20*l),f.forEach((function(t){t.pts=Vs(t.pts-y,v)})),!r||p<0){if(f=f.filter((t=>t.pts>=0)),!f.length)return;p=0===i?0:s&&!c?Math.max(0,v):f[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let r=0,s=p;r<f.length;r++){const i=f[r],a=i.pts,o=a-s,d=Math.abs(1e3*o/n);if(o<=-e*l&&c)0===r&&(D.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/n)} ms.`),this.nextAudioPts=p=s=a);else if(o>=e*l&&d<1e4&&c){let e=Math.round(o/l);s=a-e*l,s<0&&(e--,s+=l),0===r&&(this.nextAudioPts=p=s),D.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(s/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){const e=Math.max(s,0);let n=Os.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);n||(D.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=i.unit.subarray()),f.splice(r,0,{unit:n,pts:e}),s+=l,r++}}i.pts=s,s+=l}}let L,R=null,A=null,b=0,_=f.length;for(;_--;)b+=f[_].unit.byteLength;for(let e=0,s=f.length;e<s;e++){const s=f[e],i=s.unit;let n=s.pts;if(null!==A){u[e-1].duration=Math.round((n-A)/a)}else{if(r&&"aac"===t.segmentCodec&&(n=p),R=n,!(b>0))return;b+=g;try{L=new Uint8Array(b)}catch(t){return void this.observer.emit(E.ERROR,E.ERROR,{type:T.MUX_ERROR,details:S.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:b,reason:`fail allocating audio mdat ${b}`})}if(!h){new DataView(L.buffer).setUint32(0,b),L.set(Bs.types.mdat,4)}}L.set(i,g);const l=i.byteLength;g+=l,u.push(new Ys(!0,o,l,0)),A=n}const x=u.length;if(!x)return;const k=u[u.length-1];this.nextAudioPts=p=A+a*k.duration;const w=h?new Uint8Array(0):Bs.moof(t.sequenceNumber++,R/a,m({},t,{samples:u}));t.samples=[];const I=R/n,C=p/n,P={data1:w,data2:L,startPTS:I,endPTS:C,startDTS:I,endDTS:C,type:"audio",hasAudio:!0,hasVideo:!1,nb:x};return this.isAudioContiguous=!0,P}remuxEmptyAudio(t,e,r,s){const i=t.inputTimeScale,n=i/(t.samplerate?t.samplerate:i),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,d=(null!==a?a:s.startDTS*i)+l,h=s.endDTS*i+l,u=1024*n,c=Math.ceil((h-d)/u),f=Os.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(D.warn("[mp4-remuxer]: remux empty Audio"),!f)return void D.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const g=[];for(let t=0;t<c;t++){const e=d+t*u;g.push({unit:f,pts:e,dts:e})}return t.samples=g,this.remuxAudio(t,e,r,!1)}}function Vs(t,e){let r;if(null===e)return t;for(r=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=r;return t}function Ks(t,e,r,s){const i=t.samples.length;if(!i)return;const n=t.inputTimeScale;for(let a=0;a<i;a++){const i=t.samples[a];i.pts=Vs(i.pts-r.baseTime*n/r.timescale,e*n)/n,i.dts=Vs(i.dts-s.baseTime*n/s.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Ws(t,e,r){const s=t.samples.length;if(!s)return;const i=t.inputTimeScale;for(let n=0;n<s;n++){const s=t.samples[n];s.pts=Vs(s.pts-r.baseTime*i/r.timescale,e*i)/i}t.samples.sort(((t,e)=>t.pts-e.pts));const n=t.samples;return t.samples=[],{samples:n}}class Ys{constructor(t,e,r,s){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=r,this.cts=s,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function js(t,e){const r=null==t?void 0:t.codec;if(r&&r.length>4)return r;if(e===P){if("ec-3"===r||"ac-3"===r||"alac"===r)return r;if("fLaC"===r||"Opus"===r){return $t(r,!1)}const t="mp4a.40.5";return D.info(`Parsed audio codec "${r}" or audio object type not handled. Using "${t}"`),t}return D.warn(`Unhandled video codec "${r}"`),"hvc1"===r||"hev1"===r?"hvc1.1.6.L120.90":"av01"===r?"av01.0.04M.08":"avc1.42e01e"}const qs="undefined"!=typeof self?self:void 0;let zs;try{zs=self.performance.now.bind(self.performance)}catch(t){D.debug("Unable to use Performance API on this environment"),zs=null==qs?void 0:qs.Date.now}const Xs=[{demux:class{constructor(t,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}resetTimeStamp(){}resetInitSegment(t,e,r,s){const i=this.videoTrack=ss("video",1),n=this.audioTrack=ss("audio",1),a=this.txtTrack=ss("text",1);if(this.id3Track=ss("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=yt(t);if(o.video){const{id:t,timescale:e,codec:r}=o.video;i.id=t,i.timescale=a.timescale=e,i.codec=r}if(o.audio){const{id:t,timescale:e,codec:r}=o.audio;n.id=t,n.timescale=e,n.codec=r}a.id=dt.text,i.sampleDuration=0,i.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let r=0;r<e;){const s=ct(t,r);if(s>8&&109===t[r+4]&&111===t[r+5]&&111===t[r+6]&&102===t[r+7])return!0;r=s>1?r+s:e}return!1}(t)}demux(t,e){this.timeOffset=e;let r=t;const s=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=bt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},r=pt(t,["moof"]);if(r.length<2)return e.remainder=t,e;const s=r[r.length-1];return e.valid=H(t,0,s.byteOffset-8),e.remainder=H(t,s.byteOffset-8),e}(r);this.remainderData=e.remainder,s.samples=e.valid||new Uint8Array}else s.samples=r;const n=this.extractID3Track(s,e);return i.samples=Dt(e,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,r=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(e,this.timeOffset);return r.samples=Dt(t,e),{videoTrack:e,audioTrack:ss(),id3Track:s,textTrack:ss()}}extractID3Track(t,e){const r=this.id3Track;if(t.samples.length){const s=pt(t.samples,["emsg"]);s&&s.forEach((t=>{const s=function(t){const e=t[0];let r="",s="",i=0,n=0,a=0,o=0,l=0,d=0;if(0===e){for(;"\0"!==ht(t.subarray(d,d+1));)r+=ht(t.subarray(d,d+1)),d+=1;for(r+=ht(t.subarray(d,d+1)),d+=1;"\0"!==ht(t.subarray(d,d+1));)s+=ht(t.subarray(d,d+1)),d+=1;s+=ht(t.subarray(d,d+1)),d+=1,i=ct(t,12),n=ct(t,16),o=ct(t,20),l=ct(t,24),d=28}else if(1===e){d+=4,i=ct(t,d),d+=4;const e=ct(t,d);d+=4;const n=ct(t,d);for(d+=4,a=2**32*e+n,v(a)||(a=Number.MAX_SAFE_INTEGER,D.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=ct(t,d),d+=4,l=ct(t,d),d+=4;"\0"!==ht(t.subarray(d,d+1));)r+=ht(t.subarray(d,d+1)),d+=1;for(r+=ht(t.subarray(d,d+1)),d+=1;"\0"!==ht(t.subarray(d,d+1));)s+=ht(t.subarray(d,d+1)),d+=1;s+=ht(t.subarray(d,d+1)),d+=1}return{schemeIdUri:r,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(d,t.byteLength)}}(t);if(As.test(s.schemeIdUri)){const t=p(s.presentationTime)?s.presentationTime/s.timeScale:e+s.presentationTimeDelta/s.timeScale;let i=4294967295===s.eventDuration?Number.POSITIVE_INFINITY:s.eventDuration/s.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const n=s.payload;r.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:ue.emsg,duration:i})}}))}return r}demuxSampleAes(t,e,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){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}destroy(){}resetTimeStamp(t){this.initPTS=t,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(t,e,r,s){this.audioCodec=e,this.videoCodec=r,this.generateInitSegment(Rt(t,s)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:r}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const s=this.initData=yt(t);s.audio&&(e=js(s.audio,P)),s.video&&(r=js(s.video,F));const i={};s.audio&&s.video?i.audiovideo={container:"video/mp4",codec:e+","+r,initSegment:t,id:"main"}:s.audio?i.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:s.video?i.video={container:"video/mp4",codec:r,initSegment:t,id:"main"}:D.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=i}remux(t,e,r,s,i,n){var a,o;let{initPTS:l,lastEndTime:d}=this;const h={audio:void 0,video:void 0,text:s,id3:r,initSegment:void 0};p(d)||(d=this.lastEndTime=i||0);const u=e.samples;if(null==u||!u.length)return h;const c={initPTS:void 0,timescale:1};let f=this.initData;if(null!=(a=f)&&a.length||(this.generateInitSegment(u),f=this.initData),null==(o=f)||!o.length)return D.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);const g=function(t,e){let r=0,s=0,i=0;const n=pt(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=pt(a,["tfhd"])[0],l=e[ct(o,4)];if(!l)continue;const d=l.default,h=ct(o,0)|(null==d?void 0:d.flags);let u=null==d?void 0:d.duration;8&h&&(u=ct(o,2&h?12:8));const c=l.timescale||9e4,f=pt(a,["trun"]);for(let t=0;t<f.length;t++)r=At(f[t]),!r&&u&&(r=u*ct(f[t],4)),l.type===F?s+=r/c:l.type===P&&(i+=r/c)}if(0===s&&0===i){let e=1/0,r=0,s=0;const i=pt(t,["sidx"]);for(let t=0;t<i.length;t++){const n=vt(i[t]);if(null!=n&&n.references){e=Math.min(e,n.earliestPresentationTime/n.timescale);const t=n.references.reduce(((t,e)=>t+e.info.duration||0),0);r=Math.max(r,t+n.earliestPresentationTime/n.timescale),s=r-e}}if(s&&p(s))return s}return s||i}(u,f),m=function(t,e){return pt(e,["moof","traf"]).reduce(((e,r)=>{const s=pt(r,["tfdt"])[0],i=s[0],n=pt(r,["tfhd"]).reduce(((e,r)=>{const n=ct(r,4),a=t[n];if(a){let t=ct(s,4);if(1===i){if(t===ot)return D.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=ot+1,t+=ct(s,8)}const r=t/(a.timescale||9e4);if(p(r)&&(null===e||r<e))return r}return e}),null);return null!==n&&p(n)&&(null===e||n<e)?n:e}),null)}(f,u),v=null===m?i:m;(function(t,e,r,s){if(null===t)return!0;const i=Math.max(s,1),n=e-t.baseTime/t.timescale;return Math.abs(n-r)>i}(l,v,i,g)||c.timescale!==l.timescale&&n)&&(c.initPTS=v-i,l&&1===l.timescale&&D.warn("Adjusting initPTS by "+(c.initPTS-l.baseTime)),this.initPTS=l={baseTime:c.initPTS,timescale:1});const y=t?v-l.baseTime/l.timescale:d,E=y+g;!function(t,e,r){pt(e,["moof","traf"]).forEach((e=>{pt(e,["tfhd"]).forEach((s=>{const i=ct(s,4),n=t[i];if(!n)return;const a=n.timescale||9e4;pt(e,["tfdt"]).forEach((t=>{const e=t[0],s=r*a;if(s){let r=ct(t,4);if(0===e)r-=s,r=Math.max(r,0),mt(t,4,r);else{r*=Math.pow(2,32),r+=ct(t,8),r-=s,r=Math.max(r,0);const e=Math.floor(r/(ot+1)),i=Math.floor(r%(ot+1));mt(t,4,e),mt(t,8,i)}}}))}))}))}(f,u,l.baseTime/l.timescale),g>0?this.lastEndTime=E:(D.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const T=!!f.audio,S=!!f.video;let L="";T&&(L+="audio"),S&&(L+="video");const R={data1:u,startPTS:y,startDTS:y,endPTS:E,endDTS:E,type:L,hasAudio:T,hasVideo:S,nb:1,dropped:0};return h.audio="audio"===R.type?R:void 0,h.video="audio"!==R.type?R:void 0,h.initSegment=c,h.id3=Ks(r,i,l,l),s.samples.length&&(h.text=Ws(s,i,l)),h}}},{demux:ws,remux:Hs},{demux:class extends is{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,r,s){super.resetInitSegment(t,e,r,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=W(t,0);let r=(null==e?void 0:e.length)||0;if(Rs(t,r))return!1;for(let e=t.length;r<e;r++)if(hs(t,r))return D.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&as(t,e)&&ls(t,e)<=t.length-e}(t,e)}appendFrame(t,e,r){us(t,this.observer,e,r,t.manifestCodec);const s=fs(t,e,r,this.basePTS,this.frameIndex);if(s&&0===s.missing)return s}},remux:Hs},{demux:class extends is{resetInitSegment(t,e,r,s){super.resetInitSegment(t,e,r,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=W(t,0);let r=(null==e?void 0:e.length)||0;if(e&&11===t[r]&&119===t[r+1]&&void 0!==q(e)&&((t,e)=>{let r=0,s=5;e+=s;const i=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=t[e];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,i[0]=(a[0]&n[0])>>l,r=r?r<<o|i[0]:i[0],e+=1,s-=o}return r})(t,r)<=16)return!1;for(let e=t.length;r<e;r++)if(Rs(t,r))return D.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return Ss(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,r){if(null!==this.basePTS)return Es(t,e,r,this.basePTS,this.frameIndex)}},remux:Hs}];class Qs{constructor(t,e,r,s,i){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=r,this.vendor=s,this.id=i}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,r,s){const i=r.transmuxing;i.executeStart=zs();let n=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;s&&(this.currentTransmuxState=s);const{contiguous:l,discontinuity:d,trackSwitch:h,accurateTimeOffset:u,timeOffset:c,initSegmentChange:f}=s||a,{audioCodec:g,videoCodec:m,defaultInitPts:p,duration:v,initSegmentData:y}=o,L=function(t,e){let r=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(r=e);return r}(n,e);if(L&&"AES-128"===L.method){const t=this.getDecrypter();if(!t.isSync())return this.decryptionPromise=t.webCryptoDecrypt(n,L.key.buffer,L.iv.buffer).then((t=>{const e=this.push(t,null,r);return this.decryptionPromise=null,e})),this.decryptionPromise;{let e=t.softwareDecrypt(n,L.key.buffer,L.iv.buffer);if(r.part>-1&&(e=t.flush()),!e)return i.executeEnd=zs(),Js(r);n=new Uint8Array(e)}}const R=this.needsProbing(d,h);if(R){const t=this.configureTransmuxer(n);if(t)return D.warn(`[transmuxer] ${t.message}`),this.observer.emit(E.ERROR,E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),i.executeEnd=zs(),Js(r)}(d||h||f||R)&&this.resetInitSegment(y,g,m,v,e),(d||f||R)&&this.resetInitialTimestamp(p),l||this.resetContiguity();const A=this.transmux(n,L,c,u,r),b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,i.executeEnd=zs(),A}flush(t){const e=t.transmuxing;e.executeStart=zs();const{decrypter:r,currentTransmuxState:s,decryptionPromise:i}=this;if(i)return i.then((()=>this.flush(t)));const n=[],{timeOffset:a}=s;if(r){const e=r.flush();e&&n.push(this.push(e,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return e.executeEnd=zs(),[Js(t)];const d=o.flush(a);return Zs(d)?d.then((e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,d,t),n)}flushRemux(t,e,r){const{audioTrack:s,videoTrack:i,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;D.log(`[transmuxer.ts]: Flushed fragment ${r.sn}${r.part>-1?" p: "+r.part:""} of level ${r.level}`);const d=this.remuxer.remux(s,i,n,a,l,o,!0,this.id);t.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=zs()}resetInitialTimestamp(t){const{demuxer:e,remuxer:r}=this;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,r,s,i){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,r,s),a.resetInitSegment(t,e,r,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,r,s,i){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,r,s,i):this.transmuxUnencrypted(t,r,s,i),n}transmuxUnencrypted(t,e,r,s){const{audioTrack:i,videoTrack:n,id3Track:a,textTrack:o}=this.demuxer.demux(t,e,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,n,a,o,e,r,!1,this.id),chunkMeta:s}}transmuxSampleAes(t,e,r,s,i){return this.demuxer.demuxSampleAes(t,e,r).then((t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,r,s,!1,this.id),chunkMeta:i})))}configureTransmuxer(t){const{config:e,observer:r,typeSupported:s,vendor:i}=this;let n;for(let e=0,r=Xs.length;e<r;e++){var a;if(null!=(a=Xs[e].demux)&&a.probe(t)){n=Xs[e];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,d=n.remux,h=n.demux;l&&l instanceof d||(this.remuxer=new d(r,e,s,i)),o&&o instanceof h||(this.demuxer=new h(r,e,s),this.probe=h.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Gr(this.config)),t}}const Js=t=>({remuxResult:{},chunkMeta:t});function Zs(t){return"then"in t&&t.then instanceof Function}class ti{constructor(t,e,r,s,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=r,this.duration=s,this.defaultInitPts=i||null}}class ei{constructor(t,e,r,s,i,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=r,this.trackSwitch=s,this.timeOffset=i,this.initSegmentChange=n}}var ri={exports:{}};!function(t){var e=Object.prototype.hasOwnProperty,r="~";function s(){}function i(t,e,r){this.fn=t,this.context=e,this.once=r||!1}function n(t,e,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new i(s,n||t,a),l=r?r+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new s:delete t._events[e]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(r=!1)),o.prototype.eventNames=function(){var t,s,i=[];if(0===this._eventsCount)return i;for(s in t=this._events)e.call(t,s)&&i.push(r?s.slice(1):s);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(t)):i},o.prototype.listeners=function(t){var e=r?r+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var i=0,n=s.length,a=new Array(n);i<n;i++)a[i]=s[i].fn;return a},o.prototype.listenerCount=function(t){var e=r?r+t:t,s=this._events[e];return s?s.fn?1:s.length:0},o.prototype.emit=function(t,e,s,i,n,a){var o=r?r+t:t;if(!this._events[o])return!1;var l,d,h=this._events[o],u=arguments.length;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),u){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,s),!0;case 4:return h.fn.call(h.context,e,s,i),!0;case 5:return h.fn.call(h.context,e,s,i,n),!0;case 6:return h.fn.call(h.context,e,s,i,n,a),!0}for(d=1,l=new Array(u-1);d<u;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var c,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(t,h[d].fn,void 0,!0),u){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,e);break;case 3:h[d].fn.call(h[d].context,e,s);break;case 4:h[d].fn.call(h[d].context,e,s,i);break;default:if(!l)for(c=1,l=new Array(u-1);c<u;c++)l[c-1]=arguments[c];h[d].fn.apply(h[d].context,l)}}return!0},o.prototype.on=function(t,e,r){return n(this,t,e,r,!1)},o.prototype.once=function(t,e,r){return n(this,t,e,r,!0)},o.prototype.removeListener=function(t,e,s,i){var n=r?r+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||i&&!o.once||s&&o.context!==s||a(this,n);else{for(var l=0,d=[],h=o.length;l<h;l++)(o[l].fn!==e||i&&!o[l].once||s&&o[l].context!==s)&&d.push(o[l]);d.length?this._events[n]=1===d.length?d[0]:d:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=r?r+t:t,this._events[e]&&a(this,e)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,t.exports=o}(ri);var si=s(ri.exports);class ii{constructor(t,e,r,s){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const i=t.config;this.hls=t,this.id=e,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=r,this.onFlush=s;const n=(t,e)=>{(e=e||{}).frag=this.frag,e.id=this.id,t===E.ERROR&&(this.error=e.error),this.hls.trigger(t,e)};this.observer=new si,this.observer.on(E.FRAG_DECRYPTED,n),this.observer.on(E.ERROR,n);const a=It(i.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1},l=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(i.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{i.workerPath?(D.log(`loading Web Worker ${i.workerPath} for "${e}"`),this.workerContext=function(t){const e=new self.URL(t,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}(i.workerPath)):(D.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(t);return{worker:new self.Worker(e),objectURL:e}}()),this.onwmsg=t=>this.onWorkerMessage(t);const{worker:t}=this.workerContext;t.addEventListener("message",this.onwmsg),t.onerror=t=>{const r=new Error(`${t.message} (${t.filename}:${t.lineno})`);i.enableWorker=!1,D.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(E.ERROR,{type:T.OTHER_ERROR,details:S.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:r})},t.postMessage({cmd:"init",typeSupported:o,vendor:l,id:e,config:JSON.stringify(i)})}catch(t){D.warn(`Error setting up "${e}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new Qs(this.observer,o,i,l,e)}return}}this.transmuxer=new Qs(this.observer,o,i,l,e)}resetWorker(){if(this.workerContext){const{worker:t,objectURL:e}=this.workerContext;e&&self.URL.revokeObjectURL(e),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(t,e,r,s,i,n,a,o,l,d){var h,u;l.transmuxing.start=self.performance.now();const{transmuxer:c}=this,f=n?n.start:i.start,g=i.decryptdata,m=this.frag,p=!(m&&i.cc===m.cc),v=!(m&&l.level===m.level),y=m?l.sn-m.sn:-1,E=this.part?l.part-this.part.index:-1,T=0===y&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),S=!v&&(1===y||0===y&&(1===E||T&&E<=0)),L=self.performance.now();(v||y||0===i.stats.parsing.start)&&(i.stats.parsing.start=L),!n||!E&&S||(n.stats.parsing.start=L);const R=!(m&&(null==(h=i.initSegment)?void 0:h.url)===(null==(u=m.initSegment)?void 0:u.url)),A=new ei(p,S,o,v,f,R);if(!S||p||R){D.log(`[transmuxer-interface, ${i.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${p}\n trackSwitch: ${v}\n contiguous: ${S}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${R}`);const t=new ti(r,s,e,a,d);this.configureTransmuxer(t)}if(this.frag=i,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:g,chunkMeta:l,state:A},t instanceof ArrayBuffer?[t]:[]);else if(c){const e=c.push(t,g,l,A);Zs(e)?(c.async=!0,e.then((t=>{this.handleTransmuxComplete(t)})).catch((t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}))):(c.async=!1,this.handleTransmuxComplete(e))}}flush(t){t.transmuxing.start=self.performance.now();const{transmuxer:e}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(e){let r=e.flush(t);Zs(r)||e.async?(Zs(r)||(r=Promise.resolve(r)),r.then((e=>{this.handleFlushResult(e,t)})).catch((e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}))):this.handleFlushResult(r,t)}}transmuxerError(t,e,r){this.hls&&(this.error=t,this.hls.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.FRAG_PARSING_ERROR,chunkMeta:e,fatal:!1,error:t,err:t,reason:r}))}handleFlushResult(t,e){t.forEach((t=>{this.handleTransmuxComplete(t)})),this.onFlush(e)}onWorkerMessage(t){const e=t.data,r=this.hls;switch(e.event){case"init":{var s;const t=null==(s=this.workerContext)?void 0:s.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":D[e.data.logType]&&D[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,r.trigger(e.event,e.data)}}configureTransmuxer(t){const{transmuxer:e}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class ni{constructor(t,e,r,s){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=r,this.hls=s}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:r,media:s,stalled:i}=this;if(null===s)return;const{currentTime:n,seeking:a}=s,o=this.seeking&&!a,l=!this.seeking&&a;if(this.seeking=a,n!==t){if(this.moved=!0,a||(this.nudgeRetry=0),null!==i){if(this.stallReported){const t=self.performance.now()-i;D.warn(`playback not stuck anymore @${n}, after ${Math.round(t)}ms`),this.stallReported=!1}this.stalled=null}return}if(l||o)return void(this.stalled=null);if(s.paused&&!a||s.ended||0===s.playbackRate||!Xe.getBuffered(s).length)return void(this.nudgeRetry=0);const d=Xe.bufferInfo(s,n,0),h=d.nextStart||0;if(a){const t=d.len>2,r=!h||e&&e.start<=n||h-n>2&&!this.fragmentTracker.getPartialFragment(n);if(t||r)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var u;if(!(d.len>0)&&!h)return;const t=Math.max(h,d.start||0)-n,e=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,r=(null==e||null==(u=e.details)?void 0:u.live)?2*e.details.targetduration:2,i=this.fragmentTracker.getPartialFragment(n);if(t>0&&(t<=r||i))return void(s.paused||this._trySkipBufferHole(i))}const c=self.performance.now();if(null===i)return void(this.stalled=c);const f=c-i;if(!a&&f>=250&&(this._reportStall(d),!this.media))return;const g=Xe.bufferInfo(s,n,r.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(t,e){const{config:r,fragmentTracker:s,media:i}=this;if(null===i)return;const n=i.currentTime,a=s.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(t.len>r.maxBufferHole||t.nextStart&&t.nextStart-n<r.maxBufferHole)&&e>1e3*r.highBufferWatchdogPeriod&&(D.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:r,stallReported:s}=this;if(!s&&r){this.stallReported=!0;const s=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${JSON.stringify(t)})`);D.warn(s.message),e.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:r,media:s}=this;if(null===s)return 0;const i=s.currentTime,n=Xe.bufferInfo(s,i,0),a=i<n.start?n.start:n.nextStart;if(a){const o=n.len<=e.maxBufferHole,l=n.len>0&&n.len<1&&s.readyState<3,d=a-i;if(d>0&&(o||l)){if(d>e.maxBufferHole){const{fragmentTracker:e}=this;let r=!1;if(0===i){const t=e.getAppendedFrag(0,ne.MAIN);t&&a<t.end&&(r=!0)}if(!r){const r=t||e.getAppendedFrag(i,ne.MAIN);if(r){let t=!1,s=r.end;for(;s<a;){const r=e.getPartialFragment(s);if(!r){t=!0;break}s+=r.duration}if(t)return 0}}}const n=Math.max(a+.05,i+.1);if(D.warn(`skipping hole, adjusting currentTime from ${i} to ${n}`),this.moved=!0,this.stalled=null,s.currentTime=n,t&&!t.gap){const e=new Error(`fragment loaded with buffer holes, seeking from ${i} to ${n}`);r.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:e,reason:e.message,frag:t})}return n}}return 0}_tryNudgeBuffer(){const{config:t,hls:e,media:r,nudgeRetry:s}=this;if(null===r)return;const i=r.currentTime;if(this.nudgeRetry++,s<t.nudgeMaxRetry){const n=i+(s+1)*t.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${i} to ${n}`);D.warn(a.message),r.currentTime=n,e.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const r=new Error(`Playhead still not moving while enough data buffered @${i} after ${t.nudgeMaxRetry} nudges`);D.error(r.message),e.trigger(E.ERROR,{type:T.MEDIA_ERROR,details:S.BUFFER_STALLED_ERROR,error:r,fatal:!0})}}}class ai extends Zr{constructor(t,e,r){super(t,e,r,"[stream-controller]",ne.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(E.MANIFEST_LOADING,this.onManifestLoading,this),t.on(E.MANIFEST_PARSED,this.onManifestParsed,this),t.on(E.LEVEL_LOADING,this.onLevelLoading,this),t.on(E.LEVEL_LOADED,this.onLevelLoaded,this),t.on(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(E.ERROR,this.onError,this),t.on(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(E.BUFFER_CREATED,this.onBufferCreated,this),t.on(E.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(E.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(E.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(E.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(E.MANIFEST_LOADING,this.onManifestLoading,this),t.off(E.MANIFEST_PARSED,this.onManifestParsed,this),t.off(E.LEVEL_LOADED,this.onLevelLoaded,this),t.off(E.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(E.ERROR,this.onError,this),t.off(E.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(E.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(E.BUFFER_CREATED,this.onBufferCreated,this),t.off(E.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(E.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(E.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(t){if(this.levels){const{lastCurrentTime:e,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=r.startLevel;-1===t&&(r.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=r.firstAutoLevel),r.nextLoadLevel=t,this.level=r.loadLevel,this.loadedmetadata=!1}e>0&&-1===t&&(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e),this.state=Kr,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Vr}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Jr:{const{levels:t,level:e}=this,r=null==t?void 0:t[e],s=null==r?void 0:r.details;if(s&&(!s.live||this.levelLastLoaded===r)){if(this.waitForCdnTuneIn(s))break;this.state=Kr;break}if(this.hls.nextLoadLevel!==this.level){this.state=Kr;break}break}case jr:{var t;const e=self.performance.now(),r=this.retryDate;if(!r||e>=r||null!=(t=this.media)&&t.seeking){const{levels:t,level:e}=this,r=null==t?void 0:t[e];this.resetStartWhenNotLoaded(r||null),this.state=Kr}}}this.state===Kr&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:r,media:s}=this;if(null===e||!s&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const i=t.nextLoadLevel;if(null==r||!r[i])return;const n=r[i],a=this.getMainFwdBufferInfo();if(null===a)return;const o=this.getLevelDetails();if(o&&this._streamEnded(a,o)){const t={};return this.altAudio&&(t.type="video"),this.hls.trigger(E.BUFFER_EOS,t),void(this.state=Xr)}t.loadLevel!==i&&-1===t.manualLevel&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=t.nextLoadLevel=i;const l=n.details;if(!l||this.state===Jr||l.live&&this.levelLastLoaded!==n)return this.level=i,void(this.state=Jr);const d=a.len,h=this.getMaxBufferLength(n.maxBitrate);if(d>=h)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let c=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&c&&"initSegment"!==c.sn&&this.fragmentTracker.getState(c)!==Lr){var f;const t=(null!=(f=this.backtrackFragment)?f:c).sn-l.startSN,e=l.fragments[t-1];e&&c.cc===e.cc&&(c=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(c&&this.isLoopLoading(c,u)){if(!c.gap){const t=this.audioOnly&&!this.altAudio?P:F,e=(t===F?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,ne.MAIN)}c=this.getNextFragmentLoopLoading(c,l,a,ne.MAIN,h)}c&&(!c.initSegment||c.initSegment.data||this.bitrateTest||(c=c.initSegment),this.loadFragment(c,n,u))}loadFragment(t,e,r){const s=this.fragmentTracker.getState(t);this.fragCurrent=t,s===Er||s===Sr?"initSegment"===t.sn?this._loadInitSegment(t,e):this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):(this.startFragRequested=!0,super.loadFragment(t,e,r)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,ne.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:t,media:e}=this;if(null!=e&&e.readyState){let r;const s=this.getAppendedFrag(e.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const i=this.getLevelDetails();if(null!=i&&i.live){const t=this.getMainFwdBufferInfo();if(!t||t.len<2*i.targetduration)return}if(!e.paused&&t){const e=t[this.hls.nextLoadLevel],s=this.fragLastKbps;r=s&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*s)+1:0}else r=0;const n=this.getBufferedFrag(e.currentTime+r);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,r=t.duration,s=Math.max(n.end,e+Math.min(Math.max(r-this.config.maxFragLookUpTolerance,r*(this.couldBacktrack?.5:.125)),r*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(s,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Wr:case Yr:case jr:case qr:case zr:this.state=Kr}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const r=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),r.addEventListener("playing",this.onvplaying),r.addEventListener("seeked",this.onvseeked),this.gapController=new ni(this.config,r,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:t}=this;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const t=this.media,e=t?t.currentTime:null;p(e)&&this.log(`Media seeked to ${e.toFixed(3)}`);const r=this.getMainFwdBufferInfo();null!==r&&0!==r.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${r?r.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(E.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(t,e){let r=!1,s=!1;e.levels.forEach((t=>{const e=t.audioCodec;e&&(r=r||-1!==e.indexOf("mp4a.40.2"),s=s||-1!==e.indexOf("mp4a.40.5"))})),this.audioCodecSwitch=r&&s&&!function(){var t;const e=ts();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:r}=this;if(!r||this.state!==Kr)return;const s=r[e.level];(!s.details||s.details.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(s.details))&&(this.state=Jr)}onLevelLoaded(t,e){var r;const{levels:s}=this,i=e.level,n=e.details,a=n.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${i}`);this.log(`Level ${i} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${a}`);const o=s[i],l=this.fragCurrent;!l||this.state!==Yr&&this.state!==jr||l.level!==e.level&&l.loader&&this.abortCurrentFrag();let d=0;if(n.live||null!=(r=o.details)&&r.live){var h;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;d=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(E.LEVEL_UPDATED,{details:n,level:i}),this.state===Jr){if(this.waitForCdnTuneIn(n))return;this.state=Kr}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,d),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:r,part:s,payload:i}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);const a=n[r.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),void this.fragmentTracker.removeFragment(r);const l=a.videoCodec,d=o.PTSKnown||!o.live,h=null==(e=r.initSegment)?void 0:e.data,u=this._getAudioCodec(a),c=this.transmuxer=this.transmuxer||new ii(this.hls,ne.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=s?s.index:-1,g=-1!==f,m=new Pr(r.level,r.sn,r.stats.chunkCount,i.byteLength,f,g),p=this.initPTS[r.cc];c.push(i,h,u,l,r,s,o.totalduration,d,m,p)}onAudioTrackSwitching(t,e){const r=this.altAudio;if(!!!e.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const t=this.hls;r&&(t.trigger(E.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(E.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const r=e.id,s=!!this.hls.audioTracks[r].url;if(s){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=s,this.tick()}onBufferCreated(t,e){const r=e.tracks;let s,i,n=!1;for(const t in r){const e=r[t];if("main"===e.id){if(i=t,s=e,"video"===t){const e=r[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:r,part:s}=e;if(r&&r.type!==ne.MAIN)return;if(this.fragContextChanged(r))return this.warn(`Fragment ${r.sn}${s?" p: "+s.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===zr&&(this.state=Kr));const i=s?s.stats:r.stats;this.fragLastKbps=Math.round(8*i.total/(i.buffering.end-i.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,s)}onError(t,e){var r;if(e.fatal)this.state=Qr;else switch(e.details){case S.FRAG_GAP:case S.FRAG_PARSING_ERROR:case S.FRAG_DECRYPT_ERROR:case S.FRAG_LOAD_ERROR:case S.FRAG_LOAD_TIMEOUT:case S.KEY_LOAD_ERROR:case S.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ne.MAIN,e);break;case S.LEVEL_LOAD_ERROR:case S.LEVEL_LOAD_TIMEOUT:case S.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Jr||(null==(r=e.context)?void 0:r.type)!==re||(this.state=Kr);break;case S.BUFFER_APPEND_ERROR:case S.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;if(e.details===S.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case S.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}checkBuffer(){const{media:t,gapController:e}=this;if(t&&e&&t.readyState){if(this.loadedmetadata||!Xe.getBuffered(t).length){const t=this.state!==Kr?this.fragCurrent:null;e.poll(this.lastCurrentTime,t)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=Kr,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==P||this.audioOnly&&!this.altAudio){const t=(e===F?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(t,e,ne.MAIN),this.tick()}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let r=this.startPosition;if(r>=0&&e<r){if(t.seeking)return void this.log(`could not seek to ${r}, already seeking at ${e}`);const s=Xe.getBuffered(t),i=(s.length?s.start(0):0)-r;i>0&&(i<this.config.maxBufferHole||i<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${i} to match buffer start`),r+=i,this.startPosition=r),this.log(`seek to target start position ${r} from current time ${e}`),t.currentTime=r}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then((r=>{const{hls:s}=this;if(!r||this.fragContextChanged(t))return;e.fragmentError=0,this.state=Kr,this.startFragRequested=!1,this.bitrateTest=!1;const i=t.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),s.trigger(E.FRAG_LOADED,r),t.bitrateTest=!1}))}_handleTransmuxComplete(t){var e;const r="main",{hls:s}=this,{remuxResult:i,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:l,level:d}=a,{video:h,text:u,id3:c,initSegment:f}=i,{details:g}=d,m=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=qr,f){if(null!=f&&f.tracks){const t=o.initSegment||o;this._bufferInitSegment(d,f.tracks,t,n),s.trigger(E.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:r,tracks:f.tracks})}const t=f.initPTS,e=f.timescale;p(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:e},s.trigger(E.INIT_PTS_FOUND,{frag:o,id:r,initPTS:t,timescale:e}))}if(h&&g&&"initSegment"!==o.sn){const t=g.fragments[o.sn-1-g.startSN],e=o.sn===g.startSN,r=!t||o.cc>t.cc;if(!1!==i.independent){const{startPTS:t,endPTS:s,startDTS:i,endDTS:a}=h;if(l)l.elementaryStreams[h.type]={startPTS:t,endPTS:s,startDTS:i,endDTS:a};else if(h.firstKeyFrame&&h.independent&&1===n.id&&!r&&(this.couldBacktrack=!0),h.dropped&&h.independent){const i=this.getMainFwdBufferInfo(),n=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,l=h.firstKeyFramePTS?h.firstKeyFramePTS:t;if(!e&&n<l-this.config.maxBufferHole&&!r)return void this.backtrack(o);r&&(o.gap=!0),o.setElementaryStreamInfo(h.type,o.start,s,o.start,a,!0)}else e&&t>2&&(o.gap=!0);o.setElementaryStreamInfo(h.type,t,s,i,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,l,n,e||r)}else{if(!e&&!r)return void this.backtrack(o);o.gap=!0}}if(m){const{startPTS:t,endPTS:e,startDTS:r,endDTS:s}=m;l&&(l.elementaryStreams[P]={startPTS:t,endPTS:e,startDTS:r,endDTS:s}),o.setElementaryStreamInfo(P,t,e,r,s),this.bufferFragmentData(m,o,l,n)}if(g&&null!=c&&null!=(e=c.samples)&&e.length){const t={id:r,frag:o,details:g,samples:c.samples};s.trigger(E.FRAG_PARSING_METADATA,t)}if(g&&u){const t={id:r,frag:o,details:g,samples:u.samples};s.trigger(E.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,r,s){if(this.state!==qr)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:i,video:n,audiovideo:a}=e;if(i){let e=t.audioCodec;const r=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(e&&(e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==i.metadata.channelCount&&-1===r.indexOf("firefox")&&(e="mp4a.40.5")),e&&-1!==e.indexOf("mp4a.40.5")&&-1!==r.indexOf("android")&&"audio/mpeg"!==i.container&&(e="mp4a.40.2",this.log(`Android: force audio codec to ${e}`)),t.audioCodec&&t.audioCodec!==e&&this.log(`Swapping manifest audio codec "${t.audioCodec}" for "${e}"`),i.levelCodec=e,i.id="main",this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${e||""}/${t.audioCodec||""}/${i.codec}]`)}n&&(n.levelCodec=t.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${n.codec}]`)),a&&this.log(`Init audiovideo buffer, container:${a.container}, codecs[level/parsed]=[${t.codecs}/${a.codec}]`),this.hls.trigger(E.BUFFER_CODECS,e),Object.keys(e).forEach((t=>{const i=e[t].initSegment;null!=i&&i.byteLength&&this.hls.trigger(E.BUFFER_APPENDING,{type:t,data:i,frag:r,part:null,chunkMeta:s,parent:r.type})})),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,ne.MAIN)}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=Kr}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const r=t.currentTime;if(Xe.isBuffered(t,r)?e=this.getAppendedFrag(r):Xe.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,r=e.level;t&&e.sn===t.sn&&t.level===r||(this.fragPlaying=e,this.hls.trigger(E.FRAG_CHANGED,{frag:e}),t&&t.level===r||this.hls.trigger(E.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){const t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}get currentProgramDateTime(){const t=this.media;if(t){const e=t.currentTime,r=this.currentFrag;if(r&&p(e)&&p(r.programDateTime)){const t=r.programDateTime+1e3*(e-r.start);return new Date(t)}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class oi{static get version(){return"1.5.7"}static isMSESupported(){return es()}static isSupported(){return rs()}static getMediaSource(){return It()}static get Events(){return E}static get ErrorTypes(){return T}static get ErrorDetails(){return S}static get DefaultConfig(){return oi.defaultConfig?oi.defaultConfig:fr}static set DefaultConfig(t){oi.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new si,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,function(t,e){if("object"==typeof console&&!0===t||"object"==typeof t){b(t,"debug","log","info","warn","error");try{A.log(`Debug logs enabled for "${e}" in hls.js version 1.5.7`)}catch(t){A=R}}else A=R}(t.debug||!1,"Hls instance");const e=this.config=function(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=gr(t),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((t=>{const i=`${"level"===t?"playlist":t}LoadPolicy`,n=void 0===e[i],a=[];s.forEach((s=>{const o=`${t}Loading${s}`,l=e[o];if(void 0!==l&&n){a.push(o);const t=r[i].default;switch(e[i]={default:t},s){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}})),a.length&&D.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${i}": ${JSON.stringify(e[i])}`)})),c(c({},r),e)}(oi.DefaultConfig,t);this.userConfig=t,e.progressive&&mr(e);const{abrController:r,bufferController:s,capLevelController:i,errorController:n,fpsController:a}=e,o=new n(this),l=this.abrController=new r(this),d=this.bufferController=new s(this),h=this.capLevelController=new i(this),u=new a(this),f=new le(this),g=new pe(this),m=e.contentSteeringController,p=m?new m(this):null,v=this.levelController=new vr(this,p),y=new Rr(this),T=new Ir(this.config),S=this.streamController=new ai(this,y,T);h.setStreamController(S),u.setStreamController(S);const L=[f,v,S];p&&L.splice(1,0,p),this.networkControllers=L;const _=[l,d,h,u,g,y];this.audioTrackController=this.createController(e.audioTrackController,L);const x=e.audioStreamController;x&&L.push(new x(this,y,T)),this.subtitleTrackController=this.createController(e.subtitleTrackController,L);const k=e.subtitleStreamController;k&&L.push(new k(this,y,T)),this.createController(e.timelineController,_),T.emeController=this.emeController=this.createController(e.emeController,_),this.cmcdController=this.createController(e.cmcdController,_),this.latencyController=this.createController(ve,_),this.coreComponents=_,L.push(o);const w=o.onErrorOut;"function"==typeof w&&this.on(E.ERROR,w,o)}createController(t,e){if(t){const r=new t(this);return e&&e.push(r),r}return null}on(t,e,r=this){this._emitter.on(t,e,r)}once(t,e,r=this){this._emitter.once(t,e,r)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,r=this,s){this._emitter.off(t,e,r,s)}listeners(t){return this._emitter.listeners(t)}emit(t,e,r){return this._emitter.emit(t,e,r)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(D.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const r=t===E.ERROR;this.trigger(E.ERROR,{type:T.OTHER_ERROR,details:S.INTERNAL_EXCEPTION,fatal:r,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){D.log("destroy"),this.trigger(E.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((t=>t.destroy())),this.networkControllers.length=0,this.coreComponents.forEach((t=>t.destroy())),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){D.log("attachMedia"),this._media=t,this.trigger(E.MEDIA_ATTACHING,{media:t})}detachMedia(){D.log("detachMedia"),this.trigger(E.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,r=this.url,s=this.url=h.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,D.log(`loadSource:${s}`),e&&r&&(r!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(E.MANIFEST_LOADING,{url:t})}startLoad(t=-1){D.log(`startLoad(${t})`),this.started=!0,this.networkControllers.forEach((e=>{e.startLoad(t)}))}stopLoad(){D.log("stopLoad"),this.started=!1,this.networkControllers.forEach((t=>{t.stopLoad()}))}resumeBuffering(){this.started&&this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.startLoad(-1)}))}pauseBuffering(){this.networkControllers.forEach((t=>{"fragmentLoader"in t&&t.stopLoad()}))}swapAudioCodec(){D.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){D.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t){this.levelController.removeLevel(t)}get levels(){const t=this.levelController.levels;return t||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){D.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){D.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){D.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){D.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){D.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(D.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return ye.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const r=t.length;for(let s=0;s<r;s++)if(t[s].maxBitrate>=e)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:r}=this;let s;if(s=-1===e&&null!=t&&t.length?t.length-1:e,r)for(let e=s;e--;){const s=t[e].attrs["HDCP-LEVEL"];if(s&&s<=r)return e}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(t){var e;return null==(e=this.audioTrackController)?void 0:e.setAudioOption(t)}setSubtitleOption(t){var e;return null==(e=this.subtitleTrackController)||e.setSubtitleOption(t),null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}oi.defaultConfig=void 0;var li=$,di=$,hi=$,ui=$}};
//# sourceMappingURL=4768.461587f3e57e00e6.js.map