@flowplayer/player 3.29.0 → 3.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/core.js +1 -1
- package/default.js +1 -1
- package/embed.js +2 -2
- package/index.d.ts +4 -4
- package/package.json +2 -2
- package/plugins/ads.d.ts +4 -4
- package/plugins/ads.js +2 -2
- package/plugins/airplay.d.ts +4 -4
- package/plugins/airplay.js +1 -1
- package/plugins/analytics.d.ts +4 -4
- package/plugins/analytics.js +1 -1
- package/plugins/asel.d.ts +4 -4
- package/plugins/asel.js +1 -1
- package/plugins/audio.d.ts +4 -4
- package/plugins/audio.js +1 -1
- package/plugins/chapters.d.ts +4 -4
- package/plugins/chapters.js +1 -1
- package/plugins/chromecast.d.ts +4 -4
- package/plugins/chromecast.js +1 -1
- package/plugins/comscore.d.ts +4 -4
- package/plugins/comscore.js +1 -1
- package/plugins/consent.d.ts +4 -4
- package/plugins/consent.js +1 -1
- package/plugins/context-menu.d.ts +4 -4
- package/plugins/context-menu.js +1 -1
- package/plugins/cuepoints.d.ts +4 -4
- package/plugins/cuepoints.js +1 -1
- package/plugins/dash.d.ts +4 -4
- package/plugins/dash.js +2 -5
- package/plugins/drm.d.ts +4 -4
- package/plugins/drm.js +1 -1
- package/plugins/endscreen.d.ts +4 -4
- package/plugins/endscreen.js +1 -1
- package/plugins/fas.d.ts +4 -4
- package/plugins/fas.js +1 -1
- package/plugins/float-on-scroll.d.ts +4 -4
- package/plugins/float-on-scroll.js +1 -1
- package/plugins/ga4.d.ts +4 -4
- package/plugins/ga4.js +1 -1
- package/plugins/gemius.d.ts +4 -4
- package/plugins/gemius.js +1 -1
- package/plugins/google-analytics.d.ts +4 -4
- package/plugins/google-analytics.js +1 -1
- package/plugins/hls.d.ts +4 -4
- package/plugins/hls.js +1 -1
- package/plugins/id3.d.ts +4 -4
- package/plugins/id3.js +1 -1
- package/plugins/iframe.d.ts +4 -4
- package/plugins/iframe.js +1 -1
- package/plugins/keyboard.d.ts +4 -4
- package/plugins/keyboard.js +1 -1
- package/plugins/media-session.d.ts +4 -4
- package/plugins/media-session.js +1 -1
- package/plugins/message.d.ts +4 -4
- package/plugins/message.js +1 -1
- package/plugins/ovp.d.ts +10 -4
- package/plugins/ovp.js +1 -1
- package/plugins/playlist.d.ts +4 -4
- package/plugins/playlist.js +1 -1
- package/plugins/preview.d.ts +4 -4
- package/plugins/preview.js +1 -1
- package/plugins/qsel.d.ts +4 -4
- package/plugins/qsel.js +1 -1
- package/plugins/qul.d.ts +4 -4
- package/plugins/qul.js +1 -1
- package/plugins/rts.d.ts +4 -4
- package/plugins/rts.js +7 -7
- package/plugins/share.d.ts +4 -4
- package/plugins/share.js +1 -1
- package/plugins/speed.d.ts +4 -4
- package/plugins/speed.js +1 -1
- package/plugins/ssai.d.ts +4 -4
- package/plugins/ssai.js +2 -2
- package/plugins/subtitles.d.ts +4 -4
- package/plugins/subtitles.js +1 -1
- package/plugins/thumbnails.d.ts +4 -4
- package/plugins/thumbnails.js +1 -1
- package/plugins/tizen.d.ts +4 -4
- package/plugins/tizen.js +1 -1
- package/plugins/vtsel.d.ts +4 -4
- package/plugins/vtsel.js +1 -1
- package/plugins/webos.d.ts +4 -4
- package/plugins/webos.js +1 -1
- package/util/loader.d.ts +4 -4
package/plugins/hls.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):((t="undefined"!=typeof globalThis?globalThis:t||self).flowplayer=t.flowplayer||{},t.flowplayer.hls=e())}(this,(function(){"use strict";function t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var e={exports:{}};!function(t,e){var s,r,i,n,a;s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,a={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var i=a.parseURL(t);if(!i)throw new Error("Error trying to parse base URL.");return i.path=a.normalizePath(i.path),a.buildURLFromParts(i)}var n=a.parseURL(e);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return s.alwaysNormalize?(n.path=a.normalizePath(n.path),a.buildURLFromParts(n)):e;var o=a.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=r.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(h.netLoc=o.netLoc,"/"!==n.path[0]))if(n.path){var d=o.path,c=d.substring(0,d.lastIndexOf("/")+1)+n.path;h.path=a.normalizePath(c)}else h.path=o.path,n.params||(h.params=o.params,n.query||(h.query=o.query));return null===h.path&&(h.path=s.alwaysNormalize?a.normalizePath(n.path):n.path),a.buildURLFromParts(h)},parseURL:function(t){var e=s.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(i,"");t.length!==(t=t.replace(n,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=a}(e);var s=e.exports;function r(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),s.push.apply(s,r)}return s}function i(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?r(Object(s),!0).forEach((function(e){a(t,e,s[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):r(Object(s)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))}))}return t}function n(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var r=s.call(t,e||"default");if("object"!=typeof r)return r;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 a(t,e,s){return(e=n(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function o(){return(o=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t}).apply(this,arguments)}const l=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},h=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=d},d=Number.MAX_SAFE_INTEGER||9007199254740991;let c=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}({}),u=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}({}),f=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 g=function(){},m={trace:g,debug:g,log:g,warn:g,info:g,error:g};let p=m;function y(t,...e){e.forEach((function(e){p[e]=t[e]?t[e].bind(t):function(t){const e=self.console[t];return e?e.bind(self.console,`[${t}] >`):g}(e)}))}const v=p,E=/^(\d+)x(\d+)$/,T=/(.+?)=(".*?"|.*?)(?:,|$)/g;class AttrList{constructor(t){"string"==typeof t&&(t=AttrList.parseAttrList(t)),o(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 s=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)s[t]=parseInt(e.slice(2*t,2*t+2),16);return s}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 s=this[t];return s?parseFloat(s):e}enumeratedString(t){return this[t]}bool(t){return"YES"===this[t]}decimalResolution(t){const e=E.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const s={};for(T.lastIndex=0;null!==(e=T.exec(t));){let t=e[2];0===t.indexOf('"')&&t.lastIndexOf('"')===t.length-1&&(t=t.slice(1,-1));s[e[1].trim()]=t}return s}}function S(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}class DateRange{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const s=e.attr;for(const e in s)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==s[e]){v.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=o(new AttrList({}),s,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"]);l(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(l(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&&l(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class LoadStats{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 L="audio",A="video",R="audiovideo";class BaseSegment{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[L]:null,[A]:null,[R]:null},this.baseurl=t}setByteRange(t,e){const s=t.split("@",2);let r;r=1===s.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[r,parseInt(s[0])+r]}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=s.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class Fragment extends BaseSegment{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 LoadStats,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(!l(this.programDateTime))return null;const t=l(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,s,r,i,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,i)):a[t]={startPTS:e,endPTS:s,startDTS:r,endDTS:i,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[L]=null,t[A]=null,t[R]=null}}class Part extends BaseSegment{constructor(t,e,s,r,i){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new LoadStats,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=r;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 LevelDetails{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,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&s>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&&l(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}}function b(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function k(t){const e=t.split(":");let s=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),r=t[t.length-1].split(",");if(2===r.length){const e="base64"===r[0],i=r[1];e?(t.splice(-1,1),s=b(i)):s=function(t){const e=D(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(i)}}return s}function D(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}const C="undefined"!=typeof self?self:void 0;var w={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},P="org.w3.clearkey",I="com.apple.streamingkeydelivery",_="com.microsoft.playready",M="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function x(t){switch(t){case I:return w.FAIRPLAY;case _:return w.PLAYREADY;case M:return w.WIDEVINE;case P:return w.CLEARKEY}}var F="edef8ba979d64acea3c827dcd51d21ed";function O(t){switch(t){case w.FAIRPLAY:return I;case w.PLAYREADY:return _;case w.WIDEVINE:return M;case w.CLEARKEY:return P}}function N(t){const{drmSystems:e,widevineLicenseUrl:s}=t,r=e?[w.FAIRPLAY,w.WIDEVINE,w.PLAYREADY,w.CLEARKEY].filter(t=>!!e[t]):[];return!r[w.WIDEVINE]&&s&&r.push(w.WIDEVINE),r}const U=null!=C&&null!=(B=C.navigator)&&B.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var B;function $(t,e,s){return Uint8Array.prototype.slice?t.slice(e,s):new Uint8Array(Array.prototype.slice.call(t,e,s))}const G=(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,H=(t,e)=>{const s=e;let r=0;for(;G(t,e);){r+=10;r+=V(t,e+6),K(t,e+10)&&(r+=10),e+=r}if(r>0)return t.subarray(s,s+r)},V=(t,e)=>{let s=0;return s=(127&t[e])<<21,s|=(127&t[e+1])<<14,s|=(127&t[e+2])<<7,s|=127&t[e+3],s},Y=(t,e)=>G(t,e)&&V(t,e+6)+10<=t.length-e,W=t=>{const e=X(t);for(let t=0;t<e.length;t++){const s=e[t];if(j(s))return tt(s)}},j=t=>t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,q=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=V(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}},X=t=>{let e=0;const s=[];for(;G(t,e);){const r=V(t,e+6);e+=10;const i=e+r;for(;e+8<i;){const r=q(t.subarray(e)),i=z(r);i&&s.push(i),e+=r.size+10}K(t,e)&&(e+=10)}return s},z=t=>"PRIV"===t.type?Q(t):"W"===t.type[0]?Z(t):J(t),Q=t=>{if(t.size<2)return;const e=et(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}},J=t=>{if(t.size<2)return;if("TXXX"===t.type){let e=1;const s=et(t.data.subarray(e),!0);e+=s.length+1;const r=et(t.data.subarray(e));return{key:t.type,info:s,data:r}}const e=et(t.data.subarray(1));return{key:t.type,data:e}},Z=t=>{if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=et(t.data.subarray(e),!0);e+=s.length+1;const r=et(t.data.subarray(e));return{key:t.type,info:s,data:r}}const e=et(t.data);return{key:t.type,data:e}},tt=t=>{if(8===t.data.byteLength){const e=new Uint8Array(t.data),s=1&e[3];let r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,s&&(r+=47721858.84),Math.round(r)}},et=(t,e=!1)=>{const s=rt();if(s){const r=s.decode(t);if(e){const t=r.indexOf("\0");return-1!==t?r.substring(0,t):r}return r.replace(/\0/g,"")}const r=t.length;let i,n,a,o="",l=0;for(;l<r;){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)<<0)}}return o};let st;function rt(){if(!navigator.userAgent.includes("PlayStation 4"))return st||void 0===self.TextDecoder||(st=new self.TextDecoder("utf-8")),st}const it=function(t){let e="";for(let s=0;s<t.length;s++){let r=t[s].toString(16);r.length<2&&(r="0"+r),e+=r}return e},nt=Math.pow(2,32)-1,at=[].push,ot={video:1,audio:2,id3:3,text:4};function lt(t){return String.fromCharCode.apply(null,t)}function ht(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function dt(t,e){const s=ut(t,e);return s<0?4294967296+s:s}function ct(t,e){let s=dt(t,e);return s*=Math.pow(2,32),s+=dt(t,e+4),s}function ut(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function ft(t,e,s){t[e]=s>>24,t[e+1]=s>>16&255,t[e+2]=s>>8&255,t[e+3]=255&s}function gt(t,e){const s=[];if(!e.length)return s;const r=t.byteLength;for(let i=0;i<r;){const n=dt(t,i),a=n>1?i+n:r;if(lt(t.subarray(i+4,i+8))===e[0])if(1===e.length)s.push(t.subarray(i+8,a));else{const r=gt(t.subarray(i+8,a),e.slice(1));r.length&&at.apply(s,r)}i=a}return s}function mt(t){const e=[],s=t[0];let r=8;const i=dt(t,r);r+=4;let n=0,a=0;0===s?(n=dt(t,r),a=dt(t,r+4),r+=8):(n=ct(t,r),a=ct(t,r+8),r+=16),r+=2;let o=t.length+a;const l=ht(t,r);r+=2;for(let s=0;s<l;s++){let s=r;const n=dt(t,s);s+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return v.warn("SIDX has hierarchical references (not supported)"),null;const l=dt(t,s);s+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/i,start:o,end:o+a-1}}),o+=a,s+=4,r=s}return{earliestPresentationTime:n,timescale:i,version:s,referencesCount:l,references:e}}function pt(t){const e=[],s=gt(t,["moov","trak"]);for(let t=0;t<s.length;t++){const r=s[t],n=gt(r,["tkhd"])[0];if(n){let t=n[0];const s=dt(n,0===t?12:20),a=gt(r,["mdia","mdhd"])[0];if(a){t=a[0];const n=dt(a,0===t?12:20),o=gt(r,["mdia","hdlr"])[0];if(o){const t=lt(o.subarray(8,12)),a={soun:L,vide:A}[t];if(a){const t=yt(gt(r,["mdia","minf","stbl","stsd"])[0]);e[s]={timescale:n,type:a},e[a]=i({timescale:n,id:s},t)}}}}}return gt(t,["moov","mvex","trex"]).forEach(t=>{const s=dt(t,4),r=e[s];r&&(r.default={duration:dt(t,12),flags:dt(t,20)})}),e}function yt(t){const e=t.subarray(8),s=e.subarray(86),r=lt(e.subarray(4,8));let i=r;const n="enca"===r||"encv"===r;if(n){const t=gt(e,[r])[0];gt(t.subarray("enca"===r?28:78),["sinf"]).forEach(t=>{const e=gt(t,["schm"])[0];if(e){const s=lt(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=gt(t,["frma"])[0];e&&(i=lt(e))}}})}switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const t=gt(s,["avcC"])[0];i+="."+Et(t[1])+Et(t[2])+Et(t[3]);break}case"mp4a":{const t=gt(e,[r])[0],s=gt(t.subarray(28),["esds"])[0];if(s&&s.length>12){let t=4;if(3!==s[t++])break;t=vt(s,t),t+=2;const e=s[t++];if(128&e&&(t+=2),64&e&&(t+=s[t++]),4!==s[t++])break;t=vt(s,t);const r=s[t++];if(64!==r)break;if(i+="."+Et(r),t+=12,5!==s[t++])break;t=vt(s,t);const n=s[t++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&s[t])>>5)),i+="."+a}break}case"hvc1":case"hev1":{const t=gt(s,["hvcC"])[0],e=t[1],r=["","A","B","C"][e>>6],n=31&e,a=dt(t,2),o=(32&e)>>5?"H":"L",l=t[12],h=t.subarray(6,12);i+="."+r+n,i+="."+a.toString(16).toUpperCase(),i+="."+o+l;let d="";for(let t=h.length;t--;){const e=h[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}i+=d;break}case"dvh1":case"dvhe":{const t=gt(s,["dvcC"])[0],e=t[2]>>1&127,r=t[2]<<5&32|t[3]>>3&31;i+="."+Tt(e)+"."+Tt(r);break}case"vp09":{const t=gt(s,["vpcC"])[0],e=t[4],r=t[5],n=t[6]>>4&15;i+="."+Tt(e)+"."+Tt(r)+"."+Tt(n);break}case"av01":{const t=gt(s,["av1C"])[0],e=t[1]>>>5,r=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,h=(16&t[2])>>4,d=(8&t[2])>>3,c=(4&t[2])>>2,u=3&t[2],f=1,g=1,m=1,p=0;i+="."+e+"."+Tt(r)+n+"."+Tt(l)+"."+h+"."+d+c+u+"."+Tt(f)+"."+Tt(g)+"."+Tt(m)+"."+p;break}}return{codec:i,encrypted:n}}function vt(t,e){const s=e+5;for(;128&t[e++]&&e<s;);return e}function Et(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Tt(t){return(t<10?"0":"")+t}function St(t){const e=gt(t,["schm"])[0];if(e){const s=lt(e.subarray(4,8));if("cbcs"===s||"cenc"===s)return gt(t,["schi","tenc"])[0]}return v.error("[eme] missing 'schm' box"),null}function Lt(t){const e=dt(t,0);let s=8;1&e&&(s+=4),4&e&&(s+=4);let r=0;const i=dt(t,4);for(let n=0;n<i;n++){if(256&e){r+=dt(t,s),s+=4}512&e&&(s+=4),1024&e&&(s+=4),2048&e&&(s+=4)}return r}function At(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}function Rt(t,e){const s=[],r=e.samples,i=e.timescale,n=e.id;let a=!1;return gt(r,["moof"]).map(o=>{const l=o.byteOffset-8;gt(o,["traf"]).map(o=>{const h=gt(o,["tfdt"]).map(t=>{const e=t[0];let s=dt(t,4);return 1===e&&(s*=Math.pow(2,32),s+=dt(t,8)),s/i})[0];return void 0!==h&&(t=h),gt(o,["tfhd"]).map(h=>{const d=dt(h,4),c=16777215&dt(h,0);let u=0;const f=0!=(16&c);let g=0;const m=0!=(32&c);let p=8;d===n&&(0!=(1&c)&&(p+=8),0!=(2&c)&&(p+=4),0!=(8&c)&&(u=dt(h,p),p+=4),f&&(g=dt(h,p),p+=4),m&&(p+=4),"video"===e.type&&(a=function(t){if(!t)return!1;const e=t.indexOf("."),s=e<0?t:t.substring(0,e);return"hvc1"===s||"hev1"===s||"dvh1"===s||"dvhe"===s}(e.codec)),gt(o,["trun"]).map(n=>{const o=n[0],h=16777215&dt(n,0),d=0!=(1&h);let c=0;const f=0!=(4&h),m=0!=(256&h);let p=0;const y=0!=(512&h);let v=0;const E=0!=(1024&h),T=0!=(2048&h);let S=0;const L=dt(n,4);let R=8;d&&(c=dt(n,R),R+=4),f&&(R+=4);let b=c+l;for(let l=0;l<L;l++){if(m?(p=dt(n,R),R+=4):p=u,y?(v=dt(n,R),R+=4):v=g,E&&(R+=4),T&&(S=0===o?dt(n,R):ut(n,R),R+=4),e.type===A){let e=0;for(;e<v;){const n=dt(r,b);if(b+=4,bt(a,r[b])){kt(r.subarray(b,b+n),a?2:1,t+S/i,s)}b+=n,e+=n+4}}t+=p/i}}))})})}),s}function bt(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function kt(t,e,s,r){const i=Dt(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){v.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===i[e++]){const t=ht(i,e);if(e+=2,49===t){const t=dt(i,e);if(e+=4,1195456820===t){const t=i[e++];if(3===t){const n=i[e++],o=31&n,l=64&n,h=l?2+3*o:0,d=new Uint8Array(h);if(l){d[0]=n;for(let t=1;t<h;t++)d[t]=i[e++]}r.push({type:t,payloadType:a,pts:s,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let s=0;s<16;s++){const r=i[e++].toString(16);t.push(1==r.length?"0"+r:r),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=i[e++];r.push({payloadType:a,pts:s,uuid:t.join(""),userData:et(l),userDataBytes:l})}}}function Dt(t){const e=t.byteLength,s=[];let r=1;for(;r<e-2;)0===t[r]&&0===t[r+1]&&3===t[r+2]?(s.push(r+2),r+=2):r++;if(0===s.length)return t;const i=e-s.length,n=new Uint8Array(i);let a=0;for(r=0;r<i;a++,r++)a===s[0]&&(a++,s.shift()),n[r]=t[a];return n}function Ct(t,e,s){if(16!==t.byteLength)throw new RangeError("Invalid system id");let r,i,n;if(e){r=1,i=new Uint8Array(16*e.length);for(let t=0;t<e.length;t++){const s=e[t];if(16!==s.byteLength)throw new RangeError("Invalid key");i.set(s,16*t)}}else r=0,i=new Uint8Array;r>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return s&&s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(t,...e){const s=e.length;let r=8,i=s;for(;i--;)r+=e[i].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(t,4),i=0,r=8;i<s;i++)n.set(e[i],r),r+=e[i].byteLength;return n}([112,115,115,104],new Uint8Array([r,0,0,0]),t,n,i,a,s||new Uint8Array)}let wt={};class LevelKey{static clearKeyUriToKeyIdMap(){wt={}}constructor(t,e,s,r=[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=s,this.keyFormatVersions=r,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;switch(this.keyFormat){case I:case M:case _:case P:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(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||v.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 s=12;s<16;s++)e[s]=t>>8*(15-s)&255;return e}(t);return new LevelKey(this.method,this.uri,"identity",this.keyFormatVersions,e)}const e=k(this.uri);if(e)switch(this.keyFormat){case M:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case _:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Ct(t,null,e);const s=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(s)),i=r.substring(r.indexOf("<"),r.length),n=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(n){const t=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(t){const e=b(t).subarray(0,16);!function(t){const e=function(t,e,s){const r=t[e];t[e]=t[s],t[s]=r};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(e),this.keyId=e}}break}default:{let t=e.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t=wt[this.uri];if(!t){const e=Object.keys(wt).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),wt[this.uri]=t}this.keyId=t}return this}}const Pt=/\{\$([a-zA-Z0-9-_]+)\}/g;function It(t){return Pt.test(t)}function _t(t,e,s){if(null!==t.variableList||t.hasVariableRefs)for(let r=s.length;r--;){const i=s[r],n=e[i];n&&(e[i]=Mt(t,n))}}function Mt(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(Pt,e=>{const r=e.substring(2,e.length-1),i=null==s?void 0:s[r];return void 0===i?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),e):i})}return e}function xt(t,e,s){let r,i,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){r=e.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${s}"`);i=t.get(r)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: "+e.message))}}else r=e.NAME,i=e.VALUE;r in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=i||""}function Ft(t,e,s){const r=e.IMPORT;if(s&&r in s){let e=t.variableList;e||(t.variableList=e={}),e[r]=s[r]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}function Ot(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const Nt={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 Ut(t,e,s=!0){return!t.split(",").some(t=>!Bt(t,e,s))}function Bt(t,e,s=!0){var r;const i=Ot(s);return null!=(r=null==i?void 0:i.isTypeSupported($t(t,e)))&&r}function $t(t,e){return`${e}/mp4;codecs="${t}"`}function Gt(t){if(t){const e=t.substring(0,4);return Nt.video[e]}return 2}function Kt(t){return t.split(",").reduce((t,e)=>{const s=Nt.video[e];return s?(2*s+t)/(t?3:2):(Nt.audio[e]+t)/(t?2:1)},0)}const Ht={};const Vt=/flac|opus/i;function Yt(t,e=!0){return t.replace(Vt,t=>function(t,e=!0){if(Ht[t])return Ht[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let r=0;r<s.length;r++)if(Bt(s[r],"audio",e))return Ht[t]=s[r],s[r];return t}(t.toLowerCase(),e))}function Wt(t,e){return t&&"mp4a"!==t?t:e?e.split(",")[0]:e}const jt=/#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,qt=/#EXT-X-MEDIA:(.*)/g,Xt=/^#EXT(?:INF|-X-TARGETDURATION):/m,zt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Qt=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 M3U8Parser{static findGroup(t,e){for(let s=0;s<t.length;s++){const r=t[s];if(r.id===e)return r}}static resolve(t,e){return s.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Xt.test(t)}static parseMasterPlaylist(t,e){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:It(t)},r=[];let i;for(jt.lastIndex=0;null!=(i=jt.exec(t));)if(i[1]){var n;const t=new AttrList(i[1]);_t(s,t,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=Mt(s,i[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:M3U8Parser.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),te(t.CODECS,o),null!=(n=o.unknownCodecs)&&n.length||r.push(o),s.levels.push(o)}else if(i[3]){const t=i[3],r=i[4];switch(t){case"SESSION-DATA":{const t=new AttrList(r);_t(s,t,["DATA-ID","LANGUAGE","VALUE","URI"]);const e=t["DATA-ID"];e&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[e]=t);break}case"SESSION-KEY":{const t=Jt(r,e,s);t.encrypted&&t.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(t)):v.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":{const t=new AttrList(r);_t(s,t,["NAME","VALUE","QUERYPARAM"]),xt(s,t,e)}break;case"CONTENT-STEERING":{const t=new AttrList(r);_t(s,t,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:M3U8Parser.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=Zt(r)}}const a=r.length>0&&r.length<s.levels.length;return s.levels=a?r:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,s){let r;const i={},n=s.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(qt.lastIndex=0;null!==(r=qt.exec(t));){const t=new AttrList(r[1]),n=t.TYPE;if(n){const r=a[n],l=i[n]||[];i[n]=l,_t(s,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const h=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],c=t.CHANNELS,u=t.CHARACTERISTICS,f=t["INSTREAM-ID"],g={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||h||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:h,url:t.URI?M3U8Parser.resolve(t.URI,e):""};if(d&&(g.assocLang=d),c&&(g.channels=c),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=r&&r.length){const t=M3U8Parser.findGroup(r,g.groupId)||r[0];ee(g,t,"audioCodec"),ee(g,t,"textCodec")}l.push(g)}}return i}static parseLevelPlaylist(t,e,s,r,i,n){const a=new LevelDetails(e),h=a.fragments;let d,c,u,f=null,g=0,m=0,p=0,y=0,E=null,T=new Fragment(r,e),S=-1,L=!1,A=null;for(zt.lastIndex=0,a.m3u8=t,a.hasVariableRefs=It(t);null!==(d=zt.exec(t));){L&&(L=!1,T=new Fragment(r,e),T.start=p,T.sn=g,T.cc=y,T.level=s,f&&(T.initSegment=f,T.rawProgramDateTime=f.rawProgramDateTime,f.rawProgramDateTime=null,A&&(T.setByteRange(A),A=null)));const t=d[1];if(t){T.duration=parseFloat(t);const e=(" "+d[2]).slice(1);T.title=e||null,T.tagList.push(e?["INF",t,e]:["INF",t])}else if(d[3]){if(l(T.duration)){T.start=p,u&&ie(T,u,a),T.sn=g,T.level=s,T.cc=y,h.push(T);const t=(" "+d[3]).slice(1);T.relurl=Mt(a,t),se(T,E),E=T,p+=T.duration,g++,m=0,L=!0}}else if(d[4]){const t=(" "+d[4]).slice(1);E?T.setByteRange(t,E):T.setByteRange(t)}else if(d[5])T.rawProgramDateTime=(" "+d[5]).slice(1),T.tagList.push(["PROGRAM-DATE-TIME",T.rawProgramDateTime]),-1===S&&(S=h.length);else{if(d=d[0].match(Qt),!d){v.warn("No matches on slow regex match for level playlist!");continue}for(c=1;c<d.length&&void 0===d[c];c++);const t=(" "+d[c]).slice(1),i=(" "+d[c+1]).slice(1),p=d[c+2]?(" "+d[c+2]).slice(1):"";switch(t){case"PLAYLIST-TYPE":a.type=i.toUpperCase();break;case"MEDIA-SEQUENCE":g=a.startSN=parseInt(i);break;case"SKIP":{const t=new AttrList(i);_t(a,t,["RECENTLY-REMOVED-DATERANGES"]);const e=t.decimalInteger("SKIPPED-SEGMENTS");if(l(e)){a.skippedSegments=e;for(let t=e;t--;)h.unshift(null);g+=e}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(a.recentlyRemovedDateranges=s.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":break;case"ENDLIST":a.live=!1;break;case"#":(i||p)&&T.tagList.push(p?[i,p]:[i]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([t]);break;case"BITRATE":T.tagList.push([t,i]);break;case"DATERANGE":{const t=new AttrList(i);_t(a,t,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),_t(a,t,t.clientAttrs);const e=new DateRange(t,a.dateRanges[t.ID]);e.isValid||a.skippedSegments?a.dateRanges[e.id]=e:v.warn(`Ignoring invalid DATERANGE tag: "${i}"`),T.tagList.push(["EXT-X-DATERANGE",i]);break}case"DEFINE":{const t=new AttrList(i);_t(a,t,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in t?Ft(a,t,n):xt(a,t,e)}break;case"DISCONTINUITY-SEQUENCE":y=parseInt(i);break;case"KEY":{const t=Jt(i,e,a);if(t.isSupported()){if("NONE"===t.method){u=void 0;break}u||(u={}),u[t.keyFormat]&&(u=o({},u)),u[t.keyFormat]=t}else v.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${i}"`);break}case"START":a.startTimeOffset=Zt(i);break;case"MAP":{const t=new AttrList(i);if(_t(a,t,["BYTERANGE","URI"]),T.duration){const i=new Fragment(r,e);re(i,t,s,u),f=i,T.initSegment=f,f.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=f.rawProgramDateTime)}else{const e=T.byteRangeEndOffset;if(e){const t=T.byteRangeStartOffset;A=`${e-t}@${t}`}else A=null;re(T,t,s,u),f=T,L=!0}break}case"SERVER-CONTROL":{const t=new AttrList(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 AttrList(i);a.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=a.partList;t||(t=a.partList=[]);const s=m>0?t[t.length-1]:void 0,r=m++,n=new AttrList(i);_t(a,n,["BYTERANGE","URI"]);const o=new Part(n,T,e,r,s);t.push(o),T.duration+=o.duration;break}case"PRELOAD-HINT":{const t=new AttrList(i);_t(a,t,["URI"]),a.preloadHint=t;break}case"RENDITION-REPORT":{const t=new AttrList(i);_t(a,t,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(t);break}default:v.warn("line parsed but not handled: "+d)}}}E&&!E.relurl?(h.pop(),p-=E.duration,a.partList&&(a.fragmentHint=E)):a.partList&&(se(T,E),T.cc=y,a.fragmentHint=T,u&&ie(T,u,a));const R=h.length,b=h[0],k=h[R-1];if(p+=a.skippedSegments*a.targetduration,p>0&&R&&k){a.averagetargetduration=p/R;const t=k.sn;a.endSN="initSegment"!==t?t:0,a.live||(k.endList=!0),b&&(a.startCC=b.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(p+=a.fragmentHint.duration),a.totalduration=p,a.endCC=y,S>0&&function(t,e){let s=t[e];for(let r=e;r--;){const e=t[r];if(!e)return;e.programDateTime=s.programDateTime-1e3*e.duration,s=e}}(h,S),a}}function Jt(t,e,s){var r,i;const n=new AttrList(t);_t(s,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(i=n.KEYFORMAT)?i:"identity";o&&n.IV&&!l&&v.error("Invalid IV: "+n.IV);const c=o?M3U8Parser.resolve(o,e):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new LevelKey(a,c,d,u,l)}function Zt(t){const e=new AttrList(t).decimalFloatingPoint("TIME-OFFSET");return l(e)?e:null}function te(t,e){let s=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text"].forEach(t=>{const r=s.filter(e=>function(t,e){const s=Nt[e];return!!s&&!!s[t.slice(0,4)]}(e,t));r.length&&(e[t+"Codec"]=r.join(","),s=s.filter(t=>-1===r.indexOf(t)))}),e.unknownCodecs=s}function ee(t,e,s){const r=e[s];r&&(t[s]=r)}function se(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),l(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function re(t,e,s,r){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",r&&(t.levelkeys=r),t.initSegment=null}function ie(t,e,s){t.levelkeys=e;const{encryptedFragments:r}=s;r.length&&r[r.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||r.push(t)}var ne="manifest",ae="level",oe="audioTrack",le="subtitleTrack",he="main",de="audio",ce="subtitle";function ue(t){const{type:e}=t;switch(e){case oe:return de;case le:return ce;default:return he}}function fe(t,e){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=e.url),s}class PlaylistLoader{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(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.LEVEL_LOADING,this.onLevelLoading,this),t.on(c.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(c.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.LEVEL_LOADING,this.onLevelLoading,this),t.off(c.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(c.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,r=e.loader,i=new(s||r)(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:s}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ne,url:s,deliveryDirectives:null})}onLevelLoading(t,e){const{id:s,level:r,pathwayId:i,url:n,deliveryDirectives:a}=e;this.load({id:s,level:r,pathwayId:i,responseType:"text",type:ae,url:n,deliveryDirectives:a})}onAudioTrackLoading(t,e){const{id:s,groupId:r,url:i,deliveryDirectives:n}=e;this.load({id:s,groupId:r,level:null,responseType:"text",type:oe,url:i,deliveryDirectives:n})}onSubtitleTrackLoading(t,e){const{id:s,groupId:r,url:i,deliveryDirectives:n}=e;this.load({id:s,groupId:r,level:null,responseType:"text",type:le,url:i,deliveryDirectives:n})}load(t){var e;const s=this.hls.config;let r,i=this.getInternalLoader(t);if(i){const e=i.context;if(e&&e.url===t.url&&e.level===t.level)return void v.trace("[playlist-loader]: playlist request ongoing");v.log("[playlist-loader]: aborting previous loader for type: "+t.type),i.abort()}if(r=t.type===ne?s.manifestLoadPolicy.default:o({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(t),l(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===ae&&null!==t.level?e=this.hls.levels[t.level].details:t.type===oe&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===le&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,s=e.targetduration;if(t&&s){const e=1e3*Math.max(3*t,.8*s);r=o({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},h={onSuccess:(t,e,s,r)=>{const i=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(t,e,s,r||null,i):this.handleMasterPlaylist(t,e,s,r)):this.handleManifestParsingError(t,s,new Error("no EXTM3U delimiter"),r||null,e)},onError:(t,e,s,r)=>{this.handleNetworkError(e,s,!1,t,r)},onTimeout:(t,e,s)=>{this.handleNetworkError(e,s,!0,void 0,t)}};i.load(t,a,h)}handleMasterPlaylist(t,e,s,r){const i=this.hls,n=t.data,a=fe(t,s),o=M3U8Parser.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,s,o.playlistParsingError,r,e);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:u,startTimeOffset:f,variableList:g}=o;this.variableList=g;const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":y}=M3U8Parser.parseMasterPlaylistMedia(n,a,o);if(m.length){m.some(t=>!t.url)||!h[0].audioCodec||h[0].attrs.AUDIO||(v.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new AttrList({}),bitrate:0,url:""}))}i.trigger(c.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:p,captions:y,contentSteering:l,url:a,stats:e,networkDetails:r,sessionData:d,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,e,s,r,i){const n=this.hls,{id:a,level:o,type:h}=s,d=fe(t,s),u=l(o)?o:l(a)?a:0,f=ue(s),g=M3U8Parser.parseLevelPlaylist(t.data,d,u,f,0,this.variableList);if(h===ne){const t={attrs:new AttrList({}),bitrate:0,details:g,name:"",url:d};n.trigger(c.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:d,stats:e,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=g,this.handlePlaylistLoaded(g,t,e,s,r,i)}handleManifestParsingError(t,e,s,r,i){this.hls.trigger(c.ERROR,{type:u.NETWORK_ERROR,details:f.MANIFEST_PARSING_ERROR,fatal:e.type===ne,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:r,stats:i})}handleNetworkError(t,e,s=!1,r,n){let a=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${t.type}`;t.type===ae?a+=`: ${t.level} id: ${t.id}`:t.type!==oe&&t.type!==le||(a+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(a);v.warn("[playlist-loader]: "+a);let l=f.UNKNOWN,h=!1;const d=this.getInternalLoader(t);switch(t.type){case ne:l=s?f.MANIFEST_LOAD_TIMEOUT:f.MANIFEST_LOAD_ERROR,h=!0;break;case ae:l=s?f.LEVEL_LOAD_TIMEOUT:f.LEVEL_LOAD_ERROR,h=!1;break;case oe:l=s?f.AUDIO_TRACK_LOAD_TIMEOUT:f.AUDIO_TRACK_LOAD_ERROR,h=!1;break;case le:l=s?f.SUBTITLE_TRACK_LOAD_TIMEOUT:f.SUBTITLE_LOAD_ERROR,h=!1}d&&this.resetInternalLoader(t.type);const g={type:u.NETWORK_ERROR,details:l,fatal:h,url:t.url,loader:d,context:t,error:o,networkDetails:e,stats:n};if(r){const s=(null==e?void 0:e.url)||t.url;g.response=i({url:s,data:void 0},r)}this.hls.trigger(c.ERROR,g)}handlePlaylistLoaded(t,e,s,r,i,n){const a=this.hls,{type:o,level:l,id:h,groupId:d,deliveryDirectives:g}=r,m=fe(e,r),p=ue(r),y="number"==typeof r.level&&p===he?l:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void a.trigger(c.ERROR,{type:u.NETWORK_ERROR,details:f.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:t,reason:t.message,response:e,context:r,level:y,parent:p,networkDetails:i,stats:s})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const v=t.playlistParsingError;if(v)a.trigger(c.ERROR,{type:u.NETWORK_ERROR,details:f.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:e,context:r,level:y,parent:p,networkDetails:i,stats:s});else switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case ne:case ae:a.trigger(c.LEVEL_LOADED,{details:t,level:y||0,id:h||0,stats:s,networkDetails:i,deliveryDirectives:g});break;case oe:a.trigger(c.AUDIO_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:s,networkDetails:i,deliveryDirectives:g});break;case le:a.trigger(c.SUBTITLE_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:s,networkDetails:i,deliveryDirectives:g})}}}function ge(t,e){let s;try{s=new Event("addtrack")}catch(t){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,e.dispatchEvent(s)}function me(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error("addCue is failed for: "+e)}catch(s){v.debug("[texttrack-utils]: "+s);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,t.addCue(s)}catch(t){v.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+t)}}"disabled"===s&&(t.mode=s)}function pe(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)}function ye(t,e,s,r){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&t.cues.length>0){const i=function(t,e,s){const r=[],i=function(t,e){if(e<t[0].startTime)return 0;const s=t.length-1;if(e>t[s].endTime)return-1;let r=0,i=s;for(;r<=i;){const n=Math.floor((i+r)/2);if(e<t[n].startTime)i=n-1;else{if(!(e>t[n].startTime&&r<s))return n;r=n+1}}return t[r].startTime-e<e-t[i].startTime?r: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<=s)r.push(i);else if(i.startTime>s)return r}return r}(t.cues,e,s);for(let e=0;e<i.length;e++)r&&!r(i[e])||t.removeCue(i[e])}"disabled"===i&&(t.mode=i)}function ve(t){const e=[];for(let s=0;s<t.length;s++){const r=t[s];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||e.push(t[s])}return e}var Ee="org.id3",Te="com.apple.quicktime.HLS",Se="https://aomedia.org/emsg/ID3";function Le(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Ae(t,e,s,r,n){let a=new t(e,s,"");try{a.value=r,n&&(a.type=n)}catch(o){a=new t(e,s,JSON.stringify(n?i({type:n},r):r))}return a}const Re=(()=>{const t=Le();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function be(t,e){return t.getTime()/1e3-e}class ID3TrackController{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(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(c.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(c.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(pe(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 s=t[e];if("metadata"===s.kind&&"id3"===s.label)return ge(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:r}}}=this;if(!s&&!r)return;const{samples:i}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Le();if(n)for(let t=0;t<i.length;t++){const e=i[t].type;if(e===Se&&!s||!r)continue;const a=X(i[t].data);if(a){const s=i[t].pts;let r=s+i[t].duration;r>Re&&(r=Re);r-s<=0&&(r=s+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!j(i)){this.updateId3CueEnds(s,e);const t=Ae(n,s,r,i,e);t&&this.id3Track.addCue(t)}}}}}updateId3CueEnds(t,e){var s;const r=null==(s=this.id3Track)?void 0:s.cues;if(r)for(let s=r.length;s--;){const i=r[s];i.type===e&&i.startTime<t&&i.endTime===Re&&(i.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:s,type:r}){const{id3Track:i,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(i&&(a||o)){let t;t="audio"===r?t=>t.type===Ee&&o:"video"===r?t=>t.type===Se&&a:t=>t.type===Ee&&o||t.type===Se&&a,ye(i,e,s,t)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:s,id3Track:r}=this,{dateRanges:i}=e,n=Object.keys(i);if(r){const t=Object.keys(s).filter(t=>!n.includes(t));for(let e=t.length;e--;){const i=t[e];Object.keys(s[i].cues).forEach(t=>{r.removeCue(s[i].cues[t])}),delete s[i]}}const a=e.fragments[e.fragments.length-1];if(0===n.length||!l(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,h=Le();for(let t=0;t<n.length;t++){const e=n[t],r=i[e],a=be(r.startDate,o),l=s[e],u=(null==l?void 0:l.cues)||{};let f=(null==l?void 0:l.durationKnown)||!1,g=Re;const m=r.endDate;if(m)g=be(m,o),f=!0;else if(r.endOnNext&&!f){const t=n.reduce((t,e)=>{if(e!==r.id){const s=i[e];if(s.class===r.class&&s.startDate>r.startDate&&(!t||r.startDate<t.startDate))return s}return t},null);t&&(g=be(t.startDate,o),f=!0)}const p=Object.keys(r.attr);for(let t=0;t<p.length;t++){const s=p[t];if("ID"===(c=s)||"CLASS"===c||"START-DATE"===c||"DURATION"===c||"END-DATE"===c||"END-ON-NEXT"===c)continue;const i=u[s];if(i)f&&!l.durationKnown&&(i.endTime=g);else if(h){let t=r.attr[s];S(s)&&(d=t,t=Uint8Array.from(d.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer);const i=Ae(h,a,g,{key:s,data:t},Te);i&&(i.id=e,this.id3Track.addCue(i),u[s]=i)}}s[e]={cues:u,dateRange:r,durationKnown:f}}var d,c}}class LatencyController{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:s,targetduration:r}=t,{liveSyncDuration:i,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||e;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==i?i:n*r);const h=r;return l+Math.min(1*this.stallCount,h)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,s=this.levelDetails;if(null===t||null===e||null===s)return null;const r=s.edge,i=t-e-this.edgeStalled,n=r-s.totalduration,a=r-(this.config.lowLatencyMode&&s.partTarget||s.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 s=t.buffered.length;return(s?t.buffered.end(s-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(c.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(c.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(c.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(c.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(c.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(c.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(c.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 s;e.details===f.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(s=this.levelDetails)&&s.live&&v.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 s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:i}=this.config;if(!r||1===i||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,i)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;t.playbackRate=Math.min(e,Math.max(1,s))}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 ke=["NONE","TYPE-0","TYPE-1",null];const De=["SDR","PQ","HLG"];var Ce="",we="YES",Pe="v2";function Ie(t){const{canSkipUntil:e,canSkipDateRanges:s,age:r}=t;return e&&r<e/2?s?Pe:we:Ce}class HlsUrlParameters{constructor(t,e,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=s}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 Level{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 _e(this._audioGroups,t)}hasSubtitleGroup(t){return _e(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 _e(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Me(t,e){const s=e.startPTS;if(l(s)){let r,i=0;e.sn>t.sn?(i=s-t.start,r=t):(i=t.start-s,r=e),r.duration!==i&&(r.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 xe(t,e,s,r,i,n){r-s<=0&&(v.warn("Fragment should have a positive duration",e),r=s+e.duration,n=i+e.duration);let a=s,o=r;const h=e.startPTS,d=e.endPTS;if(l(h)){const t=Math.abs(h-s);l(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,a=Math.max(s,h),s=Math.min(s,h),i=Math.min(i,e.startDTS),o=Math.min(r,d),r=Math.max(r,d),n=Math.max(n,e.endDTS)}const c=s-e.start;0!==e.start&&(e.start=s),e.duration=r-e.start,e.startPTS=s,e.maxStartPTS=a,e.startDTS=i,e.endPTS=r,e.minEndPTS=o,e.endDTS=n;const u=e.sn;if(!t||u<t.startSN||u>t.endSN)return 0;let f;const g=u-t.startSN,m=t.fragments;for(m[g]=e,f=g;f>0;f--)Me(m[f],m[f-1]);for(f=g;f<m.length-1;f++)Me(m[f],m[f+1]);return t.fragmentHint&&Me(m[m.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,c}function Fe(t,e){let s=null;const r=t.fragments;for(let t=r.length-1;t>=0;t--){const e=r[t].initSegment;if(e){s=e;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let i,n=0;if(function(t,e,s){const r=e.skippedSegments,i=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(r?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];r&&!n&&t<r&&(n=e.fragments[t]=i),i&&n&&s(i,n)}}(t,e,(t,r)=>{t.relurl&&(n=t.cc-r.cc),l(t.startPTS)&&l(t.endPTS)&&(r.start=r.startPTS=t.startPTS,r.startDTS=t.startDTS,r.maxStartPTS=t.maxStartPTS,r.endPTS=t.endPTS,r.endDTS=t.endDTS,r.minEndPTS=t.minEndPTS,r.duration=t.endPTS-t.startPTS,r.duration&&(i=r),e.PTSKnown=e.alignedSliding=!0),r.elementaryStreams=t.elementaryStreams,r.loader=t.loader,r.stats=t.stats,t.initSegment&&(r.initSegment=t.initSegment,s=t.initSegment)}),s){(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)})}if(e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(t=>!t),e.deltaUpdateFailed){v.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,s){const r=o({},t);s&&s.forEach(t=>{delete r[t]});return Object.keys(e).forEach(t=>{const s=new DateRange(e[t].attr,r[t]);s.isValid?r[t]=s:v.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[t].attr)}"`)}),r}(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(n){v.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,s){if(t&&e){let r=0;for(let i=0,n=t.length;i<=n;i++){const n=t[i],a=e[i+r];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):r--}}}(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats}),i?xe(e,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):Oe(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const h=e.advancedDateTime;if(e.advanced&&h){const t=e.edge;e.driftStart||(e.driftStartTime=h,e.driftStart=t),e.driftEndTime=h,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function Oe(t,e){const s=e.startSN+e.skippedSegments-t.startSN,r=t.fragments;s<0||s>=r.length||Ne(e,r[s].start)}function Ne(t,e){if(e){const s=t.fragments;for(let r=t.skippedSegments;r<s.length;r++)s[r].start+=e;t.fragmentHint&&(t.fragmentHint.start+=e)}}function Ue(t,e,s){var r;return null!=t&&t.details?Be(null==(r=t.details)?void 0:r.partList,e,s):null}function Be(t,e,s){if(t)for(let r=t.length;r--;){const i=t[r];if(i.index===s&&i.fragment.sn===e)return i}return null}function $e(t){t.forEach((t,e)=>{const{details:s}=t;null!=s&&s.fragments&&s.fragments.forEach(t=>{t.level=e})})}function Ge(t){switch(t.details){case f.FRAG_LOAD_TIMEOUT:case f.KEY_LOAD_TIMEOUT:case f.LEVEL_LOAD_TIMEOUT:case f.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ke(t,e){const s=Ge(e);return t.default[(s?"timeout":"error")+"Retry"]}function He(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function Ve(t){return i(i({},t),{errorRetry:null,timeoutRetry:null})}function Ye(t,e,s,r){if(!t)return!1;const i=null==r?void 0:r.code,n=e<t.maxNumRetry&&(function(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}(i)||!!s);return t.shouldRetry?t.shouldRetry(t,e,s,r,n):n}const We=function(t,e){let s=0,r=t.length-1,i=null,n=null;for(;s<=r;){i=(s+r)/2|0,n=t[i];const a=e(n);if(a>0)s=i+1;else{if(!(a<0))return n;r=i-1}}return null};function je(t,e,s=0,r=0){let i=null;if(t){i=e[t.sn-e[0].sn+1]||null;const r=t.endDTS-s;r>0&&r<15e-7&&(s+=15e-7)}else 0===s&&0===e[0].start&&(i=e[0]);if(i&&(!t||t.level===i.level)&&0===qe(s,r,i))return i;const n=We(e,qe.bind(null,s,r));return!n||n===t&&i?i:n}function qe(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const r=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-r<=t?1:s.start-r>t&&s.start?-1:0}function Xe(t,e,s){const r=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-r>t}var ze=0,Qe=2,Je=3,Ze=5,ts=0,es=1,ss=2;class BasePlaylistController{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=v.log.bind(v,e+":"),this.warn=v.warn.bind(v,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,s){const r=null==e?void 0:e.renditionReports;if(r){let i=-1;for(let s=0;s<r.length;s++){const n=r[s];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){v.warn("Could not construct new URL for Rendition Report: "+t),a=n.URI||""}if(a===t){i=s;break}a===t.substring(0,a.length)&&(i=s)}if(-1!==i){const t=r[i],n=parseInt(t["LAST-MSN"])||(null==e?void 0:e.lastPartSn);let a=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);a>=0&&t>e.partTarget&&(a+=1)}const o=s&&Ie(s);return new HlsUrlParameters(n,a>=0?a:void 0,o)}}}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,s){const{details:r,stats:i}=e,n=self.performance.now(),a=i.loading.first?Math.max(0,n-i.loading.first):0;if(r.advancedDateTime=Date.now()-a,r.live||null!=s&&s.live){if(r.reloaded(s),s&&this.log(`live playlist ${t} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),s&&r.fragments.length>0&&Fe(s,r),!this.canLoad||!r.live)return;let a,o=void 0,l=void 0;if(r.canBlockReload&&r.endSN&&r.advanced){const t=this.hls.config.lowLatencyMode,i=r.lastPartSn,n=r.endSN,h=r.lastPartIndex,d=i===n,c=t?0:h;-1!==h?(o=d?n+1:i,l=d?c:h+1):o=n+1;const u=r.age,f=u+r.ageHeader;let g=Math.min(f-r.partTarget,1.5*r.targetduration);if(g>0){if(s&&g>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${g} with playlist age: ${r.age}`),g=0;else{const t=Math.floor(g/r.targetduration);if(o+=t,void 0!==l){l+=Math.round(g%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${g} skip sn ${t} to part ${l}`)}r.tuneInGoal=g}if(a=this.getDeliveryDirectives(r,e.deliveryDirectives,o,l),t||!d)return void this.loadPlaylist(a)}else(r.canBlockReload||r.canSkipUntil)&&(a=this.getDeliveryDirectives(r,e.deliveryDirectives,o,l));const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,c=function(t,e=1/0){let s=1e3*t.targetduration;if(t.updated){const r=t.fragments,i=4;if(r.length&&s*i>e){const t=1e3*r[r.length-1].duration;t<s&&(s=t)}}else s/=2;return Math.round(s)}(r,1e3*(r.edge-d));r.updated&&n>this.requestScheduled+c&&(this.requestScheduled=i.loading.start),void 0!==o&&r.canBlockReload?this.requestScheduled=i.loading.first+c-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+c<n?this.requestScheduled=n:this.requestScheduled-n<=0&&(this.requestScheduled+=c);let u=this.requestScheduled-n;u=Math.max(0,u),this.log(`reload live playlist ${t} in ${Math.round(u)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(a),u)}else this.clearTimer()}getDeliveryDirectives(t,e,s,r){let i=Ie(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,r=e.part,i=Ce),new HlsUrlParameters(s,r,i)}checkRetry(t){const e=t.details,s=Ge(t),r=t.errorAction,{action:i,retryCount:n=0,retryConfig:a}=r||{},o=!!r&&!!a&&(i===Ze||!r.resolved&&i===Qe);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(s&&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=He(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,r.resolved=!0}return o}}class EWMA{constructor(t,e=0,s=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_=s}sample(t,e){const s=Math.pow(this.alpha_,t);this.estimate_=e*(1-s)+s*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 EwmaBandWidthEstimator{constructor(t,e,s,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new EWMA(t),this.fast_=new EWMA(e),this.defaultTTFB_=r,this.ttfb_=new EWMA(t)}update(t,e){const{slow_:s,fast_:r,ttfb_:i}=this;s.halfLife!==t&&(this.slow_=new EWMA(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.fast_=new EWMA(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new EWMA(t,i.getEstimate(),i.getTotalWeight()))}sample(t,e){const s=(t=Math.max(t,this.minDelayMs_))/1e3,r=8*e/s;this.fast_.sample(s,r),this.slow_.sample(s,r)}sampleTTFB(t){const e=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(s,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(){}}const rs={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},is={};function ns(t,e,s,r,i,n){const a=t.audioCodec?t.audioGroups:null,o=null==n?void 0:n.audioCodec,h=null==n?void 0:n.channels,d=h?parseInt(h):o?1/0:2;let c=null;if(null!=a&&a.length)try{c=1===a.length&&a[0]?e.groups[a[0]].channels:a.reduce((t,s)=>{if(s){const r=e.groups[s];if(!r)throw new Error(`Audio track group ${s} not found`);Object.keys(r.channels).forEach(e=>{t[e]=(t[e]||0)+r.channels[e]})}return t},{2:0})}catch(t){return!0}return void 0!==t.videoCodec&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(i,8e6))||!!c&&l(d)&&Object.keys(c).some(t=>parseInt(t)>d)}function as(t,e,s){const r=t.videoCodec,n=t.audioCodec;if(!r||!n||!s)return Promise.resolve(rs);const a={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},o=t.videoRange;"SDR"!==o&&(a.transferFunction=o.toLowerCase());const h=r.split(",").map(t=>({type:"media-source",video:i(i({},a),{},{contentType:$t(t,"video")})}));return n&&t.audioGroups&&t.audioGroups.forEach(t=>{var s;t&&(null==(s=e.groups[t])||s.tracks.forEach(e=>{if(e.groupId===t){const t=e.channels||"",s=parseFloat(t);l(s)&&s>2&&h.push.apply(h,n.split(",").map(t=>({type:"media-source",audio:{contentType:$t(t,"audio"),channels:""+s}})))}}))}),Promise.all(h.map(t=>{const e=function(t){const{audio:e,video:s}=t,r=s||e;if(r){const t=r.contentType.split('"')[1];if(s)return`r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${t}_${Math.ceil(s.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${t}`}return""}(t);return is[e]||(is[e]=s.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:h,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:h,decodingInfoResults:[],error:t}))}function os(t,e){let s=!1,r=[];return t&&(s="SDR"!==t,r=[t]),e&&(r=e.allowedVideoRanges||De.slice(0),s=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}(),r=s?r.filter(t=>"SDR"!==t):["SDR"]),{preferHDR:s,allowedVideoRanges:r}}function ls(t,e){v.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function hs(t,e,s){if("attrs"in t){const s=e.indexOf(t);if(-1!==s)return s}for(let r=0;r<e.length;r++){if(ds(t,e[r],s))return r}return-1}function ds(t,e,s){const{groupId:r,name:i,lang:n,assocLang:a,characteristics:o,default:l}=t,h=t.forced;return(void 0===r||e.groupId===r)&&(void 0===i||e.name===i)&&(void 0===n||e.lang===n)&&(void 0===n||e.assocLang===a)&&(void 0===l||e.default===l)&&(void 0===h||e.forced===h)&&(void 0===o||function(t,e=""){const s=t.split(","),r=e.split(",");return s.length===r.length&&!s.some(t=>-1===r.indexOf(t))}(o,e.characteristics))&&(void 0===s||s(t,e))}function cs(t,e){const{audioCodec:s,channels:r}=t;return!(void 0!==s&&(e.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==r&&r!==(e.channels||"2"))}function us(t,e,s){for(let r=e;r;r--)if(s(t[r]))return r;for(let r=e+1;r<t.length;r++)if(s(t[r]))return r;return-1}var fs="NOT_LOADED",gs="APPENDING",ms="PARTIAL",ps="OK";class FragmentTracker{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(c.BUFFER_APPENDED,this.onBufferAppended,this),t.on(c.FRAG_BUFFERED,this.onFragBuffered,this),t.on(c.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(c.BUFFER_APPENDED,this.onBufferAppended,this),t.off(c.FRAG_BUFFERED,this.onFragBuffered,this),t.off(c.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const s=this.activePartLists[e];if(s)for(let e=s.length;e--;){const r=s[e];if(!r)break;const i=r.end;if(r.start<=t&&null!==i&&t<=i)return r}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:s}=this,r=Object.keys(s);for(let i=r.length;i--;){const n=s[r[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,s,r){this.timeRanges&&(this.timeRanges[t]=e);const i=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(r=>{const n=this.fragments[r];if(!n)return;if(i>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===s&&this.removeFragment(n.body));const a=n.range[t];a&&a.time.some(t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(n.body),s})})}detectPartialFragments(t){const e=this.timeRanges,{frag:s,part:r}=t;if(!e||"initSegment"===s.sn)return;const i=vs(s),n=this.fragments[i];if(!n||n.buffered&&s.gap)return;const a=!s.relurl;if(Object.keys(e).forEach(t=>{const i=s.elementaryStreams[t];if(!i)return;const o=e[t],l=a||!0===i.partial;n.range[t]=this.getBufferedTimes(s,r,l,o)}),n.loaded=null,Object.keys(n.range).length){n.buffered=!0;(n.body.endList=s.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),ys(n)||this.removeParts(s.sn-1,s.type)}else this.removeFragment(n.body)}removeParts(t,e){const s=this.activePartLists[e];s&&(this.activePartLists[e]=s.filter(e=>e.fragment.sn>=t))}fragBuffered(t,e){const s=vs(t);let r=this.fragments[s];!r&&e&&(r=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(t,e,s,r){const i={time:[],partial:s},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<r.length;t++){const e=r.start(t)-this.bufferPadding,s=r.end(t)+this.bufferPadding;if(l>=e&&o<=s){i.time.push({startPTS:Math.max(n,r.start(t)),endPTS:Math.min(a,r.end(t))});break}if(n<s&&a>e){const e=Math.max(n,r.start(t)),s=Math.min(a,r.end(t));s>e&&(i.partial=!0,i.time.push({startPTS:e,endPTS:s}))}else if(a<=e)break}return i}getPartialFragment(t){let e,s,r,i=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const h=o[l];h&&ys(h)&&(s=h.body.start-a,r=h.body.end+a,t>=s&&t<=r&&(e=Math.min(t-s,r-t),n<=e&&(i=h.body,n=e)))}),i}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||ys(e))}getState(t){const e=vs(t),s=this.fragments[e];return s?s.buffered?ys(s)?ms:ps:gs:fs}isTimeBuffered(t,e,s){let r,i;for(let n=0;n<s.length;n++){if(r=s.start(n)-this.bufferPadding,i=s.end(n)+this.bufferPadding,t>=r&&e<=i)return!0;if(e<=r)return!1}return!1}onFragLoaded(t,e){const{frag:s,part:r}=e;if("initSegment"===s.sn||s.bitrateTest)return;const i=r?null:e,n=vs(s);this.fragments[n]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:r,timeRanges:i}=e;if("initSegment"===s.sn)return;const n=s.type;if(r){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(r)}this.timeRanges=i,Object.keys(i).forEach(t=>{const e=i[t];this.detectEvictedFragments(t,e,n,r)})}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=vs(t);return!!this.fragments[e]}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,s,r,i){r&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||r&&!o.gap||o.start<e&&o.end>t&&(a.buffered||i)&&this.removeFragment(o)})}removeFragment(t){const e=vs(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const e=t.sn;this.activePartLists[t.type]=s.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 ys(t){var e,s,r;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(s=t.range.audio)?void 0:s.partial)||(null==(r=t.range.audiovideo)?void 0:r.partial))}function vs(t){return`${t.type}_${t.level}_${t.sn}`}const Es={length:0,start:()=>0,end:()=>0};class BufferHelper{static isBuffered(t,e){try{if(t){const s=BufferHelper.getBuffered(t);for(let t=0;t<s.length;t++)if(e>=s.start(t)&&e<=s.end(t))return!0}}catch(t){}return!1}static bufferInfo(t,e,s){try{if(t){const r=BufferHelper.getBuffered(t),i=[];let n;for(n=0;n<r.length;n++)i.push({start:r.start(n),end:r.end(n)});return this.bufferedInfo(i,e,s)}}catch(t){}return{len:0,start:e,end:e,nextStart:void 0}}static bufferedInfo(t,e,s){e=Math.max(0,e),t.sort((function(t,e){const s=t.start-e.start;return s||e.end-t.end}));let r=[];if(s)for(let e=0;e<t.length;e++){const i=r.length;if(i){const n=r[i-1].end;t[e].start-n<s?t[e].end>n&&(r[i-1].end=t[e].end):r.push(t[e])}else r.push(t[e])}else r=t;let i,n=0,a=e,o=e;for(let t=0;t<r.length;t++){const l=r[t].start,h=r[t].end;if(e+s>=l&&e<h)a=l,o=h,n=o-e;else if(e+s<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 v.log("failed to get media.buffered",t),Es}}}class ChunkMetadata{constructor(t,e,s,r=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=s,this.size=r,this.part=i,this.partial=n}}function Ts(t,e){for(let r=0,i=t.length;r<i;r++){var s;if((null==(s=t[r])?void 0:s.cc)===e)return t[r]}return null}function Ss(t,e){if(t){const s=t.start+e;t.start=t.startPTS=s,t.endPTS=s+t.duration}}function Ls(t,e){const s=e.fragments;for(let e=0,r=s.length;e<r;e++)Ss(s[e],t);e.fragmentHint&&Ss(e.fragmentHint,t),e.alignedSliding=!0}function As(t,e,s){e&&(!function(t,e,s){if(function(t,e,s){return!(!e||!(s.endCC>s.startCC||t&&t.cc<s.startCC))}(t,s,e)){const t=function(t,e){const s=t.fragments,r=e.fragments;if(!r.length||!s.length)return void v.log("No fragments to align");const i=Ts(s,r[0].cc);if(i&&(!i||i.startPTS))return i;v.log("No frag in previous level to align on")}(s,e);t&&l(t.start)&&(v.log("Adjusting PTS using last level due to CC increase within current level "+e.url),Ls(t.start,e))}}(t,s,e),!s.alignedSliding&&e&&Rs(s,e),s.alignedSliding||!e||s.skippedSegments||Oe(e,s))}function Rs(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,r=e.fragments;if(!s.length||!r.length)return;let i,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(i=Ts(r,a),n=Ts(s,a)),i&&n||(i=r[Math.floor(r.length/2)],n=Ts(s,i.cc)||s[Math.floor(s.length/2)]);const o=i.programDateTime,l=n.programDateTime;if(!o||!l)return;Ls((l-o)/1e3-(n.start-i.start),t)}const bs=Math.pow(2,17);class FragmentLoader{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 s=t.url;if(!s)return Promise.reject(new LoadError({type:u.NETWORK_ERROR,details:f.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void l(Ds(t));t.gap=!1}const h=this.loader=t.loader=n?new n(r):new a(r),d=ks(t),c=Ve(r.fragLoadPolicy.default),g={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:bs};t.stats=h.stats,h.load(d,g,{onSuccess:(e,s,r,i)=>{this.resetLoader(t,h);let n=e.data;r.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),o({frag:t,part:null,payload:n,networkDetails:i})},onError:(e,r,n,a)=>{this.resetLoader(t,h),l(new LoadError({type:u.NETWORK_ERROR,details:f.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:i({url:s,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:n,stats:a}))},onAbort:(e,s,r)=>{this.resetLoader(t,h),l(new LoadError({type:u.NETWORK_ERROR,details:f.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:r,stats:e}))},onTimeout:(e,s,r)=>{this.resetLoader(t,h),l(new LoadError({type:u.NETWORK_ERROR,details:f.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:r,stats:e}))},onProgress:(s,r,i,n)=>{e&&e({frag:t,part:null,payload:i,networkDetails:n})}})})}loadPart(t,e,s){this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void l(Ds(t,e));const h=this.loader=t.loader=n?new n(r):new a(r),d=ks(t,e),c=Ve(r.fragLoadPolicy.default),g={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:bs};e.stats=h.stats,h.load(d,g,{onSuccess:(r,i,n,a)=>{this.resetLoader(t,h),this.updateStatsFromPart(t,e);const l={frag:t,part:e,payload:r.data,networkDetails:a};s(l),o(l)},onError:(s,r,n,a)=>{this.resetLoader(t,h),l(new LoadError({type:u.NETWORK_ERROR,details:f.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:i({url:d.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:n,stats:a}))},onAbort:(s,r,i)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,h),l(new LoadError({type:u.NETWORK_ERROR,details:f.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:i,stats:s}))},onTimeout:(s,r,i)=>{this.resetLoader(t,h),l(new LoadError({type:u.NETWORK_ERROR,details:f.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:i,stats:s}))}})})}updateStatsFromPart(t,e){const s=t.stats,r=e.stats,i=r.total;if(s.loaded+=r.loaded,i){const r=Math.round(t.duration/e.duration),n=Math.min(Math.round(s.loaded/i),r),a=(r-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=r.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 ks(t,e=null){const s=e||t,r={frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},i=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(l(i)&&l(n)){var a;let e=i,s=n;if("initSegment"===t.sn&&"AES-128"===(null==(a=t.decryptdata)?void 0:a.method)){const t=n-i;t%16&&(s=n+(16-t%16)),0!==i&&(r.resetIV=!0,e=i-16)}r.rangeStart=e,r.rangeEnd=s}return r}function Ds(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),r={type:u.MEDIA_ERROR,details:f.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(r.part=e),(e||t).stats.aborted=!0,new LoadError(r)}class LoadError extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class AESCrypto{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 FastAESKey{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 AESDecryptor{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),s=new Uint32Array(4);for(let t=0;t<4;t++)s[t]=e.getUint32(4*t);return s}initTable(){const t=this.sBox,e=this.invSBox,s=this.subMix,r=s[0],i=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,t[f]=s,e[s]=f;const o=u[f],m=u[o],p=u[m];let y=257*u[s]^16843008*s;r[f]=y<<24|y>>>8,i[f]=y<<16|y>>>16,n[f]=y<<8|y>>>24,a[f]=y,y=16843009*p^65537*m^257*o^16843008*f,l[s]=y<<24|y>>>8,h[s]=y<<16|y>>>16,d[s]=y<<8|y>>>24,c[s]=y,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,r=0;for(;r<e.length&&s;)s=e[r]===this.key[r],r++;if(s)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),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let y,v;for(a=0;a<n;a++)a<i?y=l[a]=e[a]:(v=y,a%i==0?(v=v<<8|v>>>24,v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v],v^=c[a/i|0]<<24):i>6&&a%i==4&&(v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v]),l[a]=y=(l[a-i]^v)>>>0);for(o=0;o<n;o++)a=n-o,v=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?v:f[d[v>>>24]]^g[d[v>>>16&255]]^m[d[v>>>8&255]]^p[d[255&v]],h[o]=h[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,s){const r=this.keySize+6,i=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(t),y=new Int32Array(p.length);let v,E,T,S,L,A,R,b,k,D,C,w,P,I;const _=this.networkToHostOrderSwap;for(;e<p.length;){for(k=_(p[e]),D=_(p[e+1]),C=_(p[e+2]),w=_(p[e+3]),L=k^i[0],A=w^i[1],R=C^i[2],b=D^i[3],P=4,I=1;I<r;I++)v=o[L>>>24]^l[A>>16&255]^h[R>>8&255]^d[255&b]^i[P],E=o[A>>>24]^l[R>>16&255]^h[b>>8&255]^d[255&L]^i[P+1],T=o[R>>>24]^l[b>>16&255]^h[L>>8&255]^d[255&A]^i[P+2],S=o[b>>>24]^l[L>>16&255]^h[A>>8&255]^d[255&R]^i[P+3],L=v,A=E,R=T,b=S,P+=4;v=n[L>>>24]<<24^n[A>>16&255]<<16^n[R>>8&255]<<8^n[255&b]^i[P],E=n[A>>>24]<<24^n[R>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^i[P+1],T=n[R>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&A]^i[P+2],S=n[b>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[255&R]^i[P+3],y[e]=_(v^u),y[e+1]=_(S^f),y[e+2]=_(T^g),y[e+3]=_(E^m),u=k,f=D,g=C,m=w,e+=4}return y.buffer}}class Decrypter{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 s=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,s=e&&new DataView(t.buffer).getUint8(e-1);return s?$(t,0,e-s):t}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,s){return this.useSoftware?new Promise((r,i)=>{this.softwareDecrypt(new Uint8Array(t),e,s);const n=this.flush();n?r(n.buffer):i(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,s)}softwareDecrypt(t,e,s){const{currentIV:r,currentResult:i,remainderData:n}=this;this.logOnce("JS AES decrypt"),n&&(t=At(n,t),this.remainderData=null);const a=this.getValidChunk(t);if(!a.length)return null;r&&(s=r);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new AESDecryptor),o.expandKey(e);const l=i;return this.currentResult=o.decrypt(a.buffer,0,s),this.currentIV=$(a,-16).buffer,l||null}webCryptoDecrypt(t,e,s){const r=this.subtle;return this.key===e&&this.fastAesKey||(this.key=e,this.fastAesKey=new FastAESKey(r,e)),this.fastAesKey.expandKey().then(e=>{if(!r)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new AESCrypto(r,new Uint8Array(s)).decrypt(t.buffer,e)}).catch(r=>(v.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,s)))}onWebCryptoError(t,e,s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s);const r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%16;return s!==t.length&&(e=$(t,0,s),this.remainderData=$(t,s)),e}logOnce(t){this.logEnabled&&(v.log("[decrypter]: "+t),this.logEnabled=!1)}}const Cs=function(t){let e="";const s=t.length;for(let r=0;r<s;r++)e+=`[${t.start(r).toFixed(3)}-${t.end(r).toFixed(3)}]`;return e},ws="STOPPED",Ps="IDLE",Is="KEY_LOADING",_s="FRAG_LOADING",Ms="FRAG_LOADING_WAITING_RETRY",xs="WAITING_TRACK",Fs="PARSING",Os="PARSED",Ns="ENDED",Us="ERROR",Bs="WAITING_INIT_PTS",$s="WAITING_LEVEL";class BaseStreamController extends class TaskLoop{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(){}}{constructor(t,e,s,r,i){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=ws,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=r,this.log=v.log.bind(v,r+":"),this.warn=v.warn.bind(v,r+":"),this.hls=t,this.fragmentLoader=new FragmentLoader(t.config),this.keyLoader=s,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Decrypter(t.config),t.on(c.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=ws}_streamEnded(t,e){if(e.live||t.nextStart||!t.end||!this.media)return!1;const s=e.partList;if(null!=s&&s.length){const t=s[s.length-1];return BufferHelper.isBuffered(this.media,t.start+t.duration/2)}const r=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(r)}getLevelDetails(){var t;if(this.levels&&null!==this.levelLastLoaded)return null==(t=this.levelLastLoaded)?void 0:t.details}onMediaAttached(t,e){const s=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),s.addEventListener("seeking",this.onvseeking),s.addEventListener("ended",this.onvended);const r=this.config;this.levels&&r.autoStartLoad&&this.state===ws&&this.startLoad(r.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:s,mediaBuffer:r,state:i}=this,n=s?s.currentTime:0,a=BufferHelper.bufferInfo(r||s,n,t.maxBufferHole);if(this.log(`media seeking to ${l(n)?n.toFixed(3):n}, state: ${i}`),this.state===Ns)this.resetLoadingState();else if(e){const s=t.maxFragLookUpTolerance,r=e.start-s,i=e.start+e.duration+s;if(!a.len||i<a.start||r>a.end){const t=n>i;(n<r||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)}}s&&(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(c.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=ws,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,s){this._loadFragForPlayback(t,e,s)}_loadFragForPlayback(t,e,s){this._doFragLoad(t,e,s,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 s=this.state;this.fragContextChanged(t)?(s===_s||!this.fragCurrent&&s===Fs)&&(this.fragmentTracker.removeFragment(t),this.state=Ps):("payload"in e&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(c.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(e=>{this.state!==ws&&this.state!==Us&&(this.warn(e),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===gs){const e=t.type,r=this.getFwdBufferInfo(this.mediaBuffer,e),i=Math.max(t.duration,r?r.len:this.config.maxBufferLength);this.reduceMaxBufferLength(i)&&s.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===ms&&s.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,s=null){if(!(t-e))return;const r={startOffset:t,endOffset:e,type:s};this.hls.trigger(c.BUFFER_FLUSHING,r)}_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:s}=this,{payload:r}=e,i=t.decryptdata;if(r&&r.byteLength>0&&null!=i&&i.key&&i.iv&&"AES-128"===i.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer).catch(e=>{throw s.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(r=>{const i=self.performance.now();return s.trigger(c.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:n,tdecrypt:i}}),e.payload=r,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(e=>{this.state!==ws&&this.state!==Us&&(this.warn(e),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const s=t.frag.stats;this.state=Ps,t.frag.data=new Uint8Array(t.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.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 s,r,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===he?"level":"track"} ${t.level} (frag:[${(null!=(s=t.startPTS)?s:NaN).toFixed(3)}-${(null!=(r=t.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?Cs(BufferHelper.getBuffered(a)):"(detached)"})`),"initSegment"!==t.sn){var o;if(t.type!==ce){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=Ps)}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=Ps,a&&(!this.loadedmetadata&&t.type==he&&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:s,part:r,partsLoaded:i}=t,n=!i||0===i.length||i.some(t=>!t),a=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount+1,0,r?r.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,s=null,r){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=Is,this.fragCurrent=t,a=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(c.KEY_LOADED,t),this.state===Is&&(this.state=Ps),t}),this.hls.trigger(c.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),s=Math.max(t.start,s||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){const i=n.partList;if(i&&r){s>t.end&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(i,t,s);if(o>-1){const l=i[o];let h;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(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=_s,h=a?a.then(s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,l,e,r)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,l,e,r).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(c.FRAG_LOADING,{frag:t,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(i,s))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(s.toFixed(3))}`),l(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=_s;const o=this.config.progressive;let h;return h=o&&a?a.then(e=>!e||this.fragContextChanged(null==e?void 0:e.frag)?null:this.fragmentLoader.load(t,r)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,o?r:void 0),a]).then(([t])=>(!o&&t&&r&&r(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(c.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,e,s,r){return new Promise((i,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,h=e=>{this.fragmentLoader.loadPart(t,e,r).then(r=>{o[e.index]=r;const n=r.part;this.hls.trigger(c.FRAG_LOADED,r);const a=Ue(s,t.sn,e.index+1)||Be(l,t.sn,e.index+1);if(!a)return i({frag:t,part:n,partsLoaded:o});h(a)}).catch(n)};h(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===f.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(c.ERROR,e)}else this.hls.trigger(c.ERROR,{type:u.OTHER_ERROR,details:f.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==Fs)return void(this.fragCurrent||this.state===ws||this.state===Us||(this.state=Ps));const{frag:s,part:r,level:i}=e,n=self.performance.now();s.stats.parsing.end=n,r&&(r.stats.parsing.end=n),this.updateLevelTiming(s,r,i,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:r,sn:i,part:n}=t;if(null==e||!e[r])return this.warn(`Levels object was unset while buffering fragment ${i} of level ${r}. The current chunk will not be buffered.`),null;const a=e[r],o=n>-1?Ue(a,i,n):null,l=o?o.fragment:function(t,e,s){if(null==t||!t.details)return null;const r=t.details;let i=r.fragments[e-r.startSN];return i||(i=r.fragmentHint,i&&i.sn===e?i:e<r.startSN&&s&&s.sn===e?s:null)}(a,i,s);return l?(s&&s!==l&&(l.stats=s.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(t,e,s,r,i){var n;if(!t||this.state!==Fs)return;const{data1:a,data2:o}=t;let l=a;if(a&&o&&(l=At(a,o)),null==(n=l)||!n.length)return;const h={type:t.type,frag:e,part:s,chunkMeta:r,parent:e.type,data:l};if(this.hls.trigger(c.BUFFER_APPENDING,h),t.dropped&&t.independent&&!s){if(i)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!BufferHelper.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const s=e.currentTime,r=BufferHelper.bufferInfo(e,s,0),i=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*i),a=Math.max(Math.min(t.start-n,r.end-n),s+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){const s=this.getLoadPosition();return l(s)?this.getFwdBufferInfoAtPos(t,s,e):null}getFwdBufferInfoAtPos(t,e,s){const{config:{maxBufferHole:r}}=this,i=BufferHelper.bufferInfo(t,e,r);if(0===i.len&&void 0!==i.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,s);if(n&&i.nextStart<n.end)return BufferHelper.bufferInfo(t,e,Math.max(i.nextStart,r))}return i}getMaxBufferLength(t){const{config:e}=this;let s;return s=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(s,e.maxMaxBufferLength)}reduceMaxBufferLength(t){const e=this.config,s=t||e.maxBufferLength;return e.maxMaxBufferLength>=s&&(e.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${e.maxMaxBufferLength}s`),!0)}getAppendedFrag(t,e=he){const s=this.fragmentTracker.getAppendedFrag(t,he);return s&&"fragment"in s?s.fragment:s}getNextFragment(t,e){const s=e.fragments,r=s.length;if(!r)return null;const{config:i}=this,n=s[0].start;let a;if(e.live){const o=i.initialLiveManifestSize;if(r<o)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${o})`),null;(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n)&&(a=this.getInitialLiveFragment(e,s),this.startPosition=this.nextLoadPosition=a?this.hls.liveSyncPosition||a.start:t)}else t<=n&&(a=s[0]);if(!a){const s=i.lowLatencyMode?e.partEnd:e.fragmentEnd;a=this.getFragmentAtPosition(t,s,e)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(t,e){const s=this.fragmentTracker.getState(t);return(s===ps||s===ms&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,s,r,i){const n=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(null===a)return a;if(t=a,n&&t&&!t.gap&&s.nextStart){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,r);if(null!==e&&s.len+e.len>=i)return this.log(`buffer full after gaps in "${r}" 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,s){let r=-1,i=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,r>-1&&s<o.start)break;const l=o.loaded;l?r=-1:(i||o.independent||n)&&o.fragment===e&&(r=a),i=l}return r}loadedEndOfParts(t,e){const s=t[t.length-1];return s&&e>s.start&&s.loaded}getInitialLiveFragment(t,e){const s=this.fragPrevious;let r=null;if(s){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+s.programDateTime),r=function(t,e,s){if(null===e||!Array.isArray(t)||!t.length||!l(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;s=s||0;for(let r=0;r<t.length;++r){const i=t[r];if(Xe(e,s,i))return i}return null}(e,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const i=s.sn+1;if(i>=t.startSN&&i<=t.endSN){const n=e[i-t.startSN];s.cc===n.cc&&(r=n,this.log("Live playlist, switching playlist, load frag with next SN: "+r.sn))}r||(r=function(t,e){return We(t,t=>t.cc<e?1:t.cc>e?-1:0)}(e,s.cc),r&&this.log("Live playlist, switching playlist, load frag with same CC: "+r.sn))}}else{const e=this.hls.liveSyncPosition;null!==e&&(r=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r}getFragmentAtPosition(t,e,s){const{config:r}=this;let{fragPrevious:i}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,l=r.maxFragLookUpTolerance,h=s.partList,d=!!(r.lowLatencyMode&&null!=h&&h.length&&o);let c;if(d&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),t<e){c=je(i,n,t,t>e-l?0:l)}else c=n[n.length-1];if(c){const t=c.sn-s.startSN,e=this.fragmentTracker.getState(c);if((e===ps||e===ms&&c.gap)&&(i=c),i&&c.sn===i.sn&&(!d||h[0].fragment.sn>c.sn)){if(i&&c.level===i.level){const e=n[t+1];c=c.sn<a&&this.fragmentTracker.getState(e)!==ps?e:null}}}return c}synchronizeToLiveEdge(t){const{config:e,media:s}=this;if(!s)return;const r=this.hls.liveSyncPosition,i=s.currentTime,n=t.fragments[0].start,a=t.edge,o=i>=n-e.maxFragLookUpTolerance&&i<=a;if(null!==r&&s.duration>r&&(i<r||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!o&&s.readyState<4||i<a-n)&&(this.loadedmetadata||(this.nextLoadPosition=r),s.readyState&&(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),s.currentTime=r))}}alignPlaylists(t,e,s){const r=t.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const i=t.fragments[0].start,n=!e,a=t.alignedSliding&&l(i);if(n||!a&&!i){const{fragPrevious:i}=this;As(i,s,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: ${r}`),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 s=this.startPosition;if(s<e&&(s=-1),-1===s||-1===this.lastCurrentTime){const r=null!==this.startTimeOffset,i=r?this.startTimeOffset:t.startTimeOffset;null!==i&&l(i)?(s=e+i,i<0&&(s+=t.totalduration),s=Math.min(Math.max(e,s),e+t.totalduration),this.log(`Start time offset ${i} found in ${r?"multivariant":"media"} playlist, adjust startPosition to ${s}`),this.startPosition=s):t.live?s=this.hls.liveSyncPosition||e:this.startPosition=s=0,this.lastCurrentTime=s}this.nextLoadPosition=s}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===Ms)||(this.state=Ps)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const s=e.frag;if(!s||s.type!==t||!this.levels)return;var r;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const i=e.details===f.FRAG_GAP;i&&this.fragmentTracker.fragBuffered(s,!0);const n=e.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===Ze&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const r=He(l,o);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=Ms}else if(l&&n){if(this.resetFragmentErrors(t),!(o<l.maxNumRetry))return void v.warn(`${e.details} reached or exceeded max retry (${o})`);i||a===Je||(n.resolved=!0)}else(null==n?void 0:n.action)===Qe?this.state=$s:this.state=Us;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===Fs||this.state===Os){const e=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,e),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len);const i=!r;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===de&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==ws&&(this.state=Ps)}afterBufferFlushed(t,e,s){if(!t)return;const r=BufferHelper.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,s),this.state===Ns&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Ps}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,s,r){var i;const n=s.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=r?0:xe(n,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(c.LEVEL_PTS_UPDATED,{details:n,level:s,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===s.fragmentError&&(s.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(e.message),this.hls.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Os,this.hls.trigger(c.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}}class ChunkCache{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let s;return t.length?(s=1===t.length?t[0]:function(t,e){const s=new Uint8Array(e);let r=0;for(let e=0;e<t.length;e++){const i=t[e];s.set(i,r),r+=i.length}return s}(t,e),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function Gs(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class BaseAudioDemuxer{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,s,r){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,s){}demux(t,e){this.cachedData&&(t=At(this.cachedData,t),this.cachedData=null);let s,r=H(t,0),i=r?r.length:0;const n=this._audioTrack,a=this._id3Track,o=r?W(r):void 0,h=t.length;for((null===this.basePTS||0===this.frameIndex&&l(o))&&(this.basePTS=Ks(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Ee,duration:Number.POSITIVE_INFINITY});i<h;){if(this.canParse(t,i)){const e=this.appendFrame(n,t,i);e?(this.frameIndex++,this.lastPTS=e.sample.pts,i+=e.length,s=i):i=h}else Y(t,i)?(r=H(t,i),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Ee,duration:Number.POSITIVE_INFINITY}),i+=r.length,s=i):i++;if(i===h&&s!==h){const e=$(t,s);this.cachedData?this.cachedData=At(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:Gs(),id3Track:a,textTrack:Gs()}}demuxSampleAes(t,e,s){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:Gs(),id3Track:this._id3Track,textTrack:Gs()}}destroy(){}}const Ks=(t,e,s)=>{if(l(t))return 90*t;return 9e4*e+(s?9e4*s.baseTime/s.timescale:0)};function Hs(t,e){return 255===t[e]&&240==(246&t[e+1])}function Vs(t,e){return 1&t[e+1]?7:9}function Ys(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Ws(t,e){return e+1<t.length&&Hs(t,e)}function js(t,e){if(Ws(t,e)){const s=Vs(t,e);if(e+s>=t.length)return!1;const r=Ys(t,e);if(r<=s)return!1;const i=e+r;return i===t.length||Ws(t,i)}return!1}function qs(t,e,s,r,i){if(!t.samplerate){const n=function(t,e,s,r){let i,n,a,o;const l=navigator.userAgent.toLowerCase(),h=r,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=1+((192&e[s+2])>>>6);const g=(60&e[s+2])>>>2;if(!(g>d.length-1))return a=(1&e[s+2])<<2,a|=(192&e[s+3])>>>6,v.log(`manifest codec:${r}, ADTS type:${i}, samplingIndex:${g}`),/firefox/i.test(l)?g>=6?(i=5,o=new Array(4),n=g-3):(i=2,o=new Array(2),n=g):-1!==l.indexOf("android")?(i=2,o=new Array(2),n=g):(i=5,o=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&g>=6?n=g-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(g>=6&&1===a||/vivaldi/i.test(l))||!r&&1===a)&&(i=2,o=new Array(2)),n=g)),o[0]=i<<3,o[0]|=(14&g)>>1,o[1]|=(1&g)<<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:d[g],channelCount:a,codec:"mp4a.40."+i,manifestCodec:h};{const e=new Error("invalid ADTS sampling index:"+g);t.emit(c.ERROR,c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}}(e,s,r,i);if(!n)return;t.config=n.config,t.samplerate=n.samplerate,t.channelCount=n.channelCount,t.codec=n.codec,t.manifestCodec=n.manifestCodec,v.log(`parsed codec:${t.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function Xs(t){return 9216e4/t}function zs(t,e,s,r,i){const n=r+i*Xs(t.samplerate),a=function(t,e){const s=Vs(t,e);if(e+s<=t.length){const r=Ys(t,e)-s;if(r>0)return{headerLength:s,frameLength:r}}}(e,s);let o;if(a){const{frameLength:r,headerLength:i}=a,l=i+r,h=Math.max(0,s+l-e.length);h?(o=new Uint8Array(l-i),o.set(e.subarray(s+i,e.length),0)):o=e.subarray(s+i,s+l);const d={unit:o,pts:n};return h||t.samples.push(d),{sample:d,length:l,missing:h}}const l=e.length-s;o=new Uint8Array(l),o.set(e.subarray(s,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let Qs=null;const Js=[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],Zs=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],tr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],er=[0,1,1,4];function sr(t,e,s,r,i){if(s+24>e.length)return;const n=rr(e,s);if(n&&s+n.frameLength<=e.length){const a=r+i*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(s,s+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 rr(t,e){const s=t[e+1]>>3&3,r=t[e+1]>>1&3,i=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==s&&0!==i&&15!==i&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Js[14*(3===s?3-r:3===r?3:4)+i-1],h=Zs[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=tr[s][r],u=er[r],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===Qs){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Qs=t?parseInt(t[1]):0}return!!Qs&&Qs<=87&&2===r&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function ir(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function nr(t,e){return e+1<t.length&&ir(t,e)}function ar(t,e){if(e+1<t.length&&ir(t,e)){const s=4,r=rr(t,e);let i=s;null!=r&&r.frameLength&&(i=r.frameLength);const n=e+i;return n===t.length||nr(t,n)}return!1}const or=/\/emsg[-/]ID3/i;const lr=(t,e)=>{let s=0,r=5;e+=r;const i=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=t[e];const o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,i[0]=(a[0]&n[0])>>l,s=s?s<<o|i[0]:i[0],e+=1,r-=o}return s};class AC3Demuxer extends BaseAudioDemuxer{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,s,r){super.resetInitSegment(t,e,s,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,s){const r=hr(t,e,s,this.basePTS,this.frameIndex);if(-1!==r){return{sample:t.samples[t.samples.length-1],length:r,missing:0}}}static probe(t){if(!t)return!1;const e=H(t,0);if(!e)return!1;const s=e.length;return 11===t[s]&&119===t[s+1]&&void 0!==W(e)&&lr(t,s)<16}}function hr(t,e,s,r,i){if(s+8>e.length)return-1;if(11!==e[s]||119!==e[s+1])return-1;const n=e[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>e.length)return-1;const h=e[s+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(e[s+6]<<8|e[s+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=e[s+5]>>3,g=7&e[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=r+i*(1536/a*9e4),y=e.subarray(s,s+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:y,pts:p}),l}class ExpGolomb{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,s=t.byteLength-e,r=new Uint8Array(4),i=Math.min(4,e);if(0===i)throw new Error("no bytes available");r.set(t.subarray(s,s+i)),this.word=new DataView(r.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 s=this.word>>>32-e;if(t>32&&v.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?s<<e|this.readBits(e):s}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(0!=(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,s=8,r=8;for(let i=0;i<t;i++)0!==r&&(e=this.readEG(),r=(s+e+256)%256),s=0===r?s:r}readSPS(){let t,e,s,r=0,i=0,n=0,a=0;const o=this.readUByte.bind(this),l=this.readBits.bind(this),h=this.readUEG.bind(this),d=this.readBoolean.bind(this),c=this.skipBits.bind(this),u=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);o();const m=o();if(l(5),c(3),o(),f(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){const t=h();if(3===t&&c(1),f(),f(),c(1),d())for(e=3!==t?8:12,s=0;s<e;s++)d()&&g(s<6?16:64)}f();const p=h();if(0===p)h();else if(1===p)for(c(1),u(),u(),t=h(),s=0;s<t;s++)u();f(),c(1);const y=h(),v=h(),E=l(1);0===E&&c(1),c(1),d()&&(r=h(),i=h(),n=h(),a=h());let T=[1,1];if(d()&&d()){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*(y+1)-2*r-2*i),height:(2-E)*(v+1)*16-(E?2:4)*(n+a),pixelRatio:T}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class AvcVideoParser extends class BaseVideoParser{constructor(){this.VideoSample=null}createVideoSample(t,e,s,r){return{key:t,frame:!1,pts:e,dts:s,units:[],debug:r,length:0}}getLastNalUnit(t){var e;let s,r=this.VideoSample;if(r&&0!==r.units.length||(r=t[t.length-1]),null!=(e=r)&&e.units){const t=r.units;s=t[t.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const s=e.samples,r=s.length;if(!r)return void e.dropped++;{const e=s[r-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}t.debug.length&&v.log(t.pts+"/"+t.dts+":"+t.debug)}}{parseAVCPES(t,e,s,r,i){const n=this.parseAVCNALu(t,s.data);let a,o=this.VideoSample,l=!1;s.data=null,o&&n.length&&!t.audFound&&(this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"")),n.forEach(r=>{var n;switch(r.type){case 1:{let e=!1;a=!0;const i=r.data;if(l&&i.length>4){const t=new ExpGolomb(i).readSliceType();2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=o)&&h.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.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,s.pts,s.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,kt(r.data,1,s.pts,e.samples);break;case 7:{var d,c;a=!0,l=!0;const e=r.data,s=new ExpGolomb(e).readSPS();if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(d=t.pixelRatio)?void 0:d[0])!==s.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e],t.duration=i;const r=e.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let e=r[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}break}case 8:a=!0,t.pps=[r.data];break;case 9:a=!0,t.audFound=!0,o&&this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+r.type+" ")}if(o&&a){o.units.push(r)}}),r&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)}parseAVCNALu(t,e){const s=e.byteLength;let r=t.naluState||0;const i=r,n=[];let a,o,l,h=0,d=-1,c=0;for(-1===r&&(d=0,c=31&e[0],r=0,h=1);h<s;)if(a=e[h++],r)if(1!==r)if(a)if(1===a){if(o=h-r-1,d>=0){const t={data:e.subarray(d,o),type:c};n.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(i&&h<=4-i&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-i)),o>0&&(s.data=At(s.data,e.subarray(0,o)),s.state=0))}h<s?(l=31&e[h],d=h,c=l,r=0):r=-1}else r=0;else r=3;else r=a?0:2;else r=a?0:1;if(d>=0&&r>=0){const t={data:e.subarray(d,s),type:c,state:r};n.push(t)}if(0===n.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=At(s.data,e))}return t.naluState=r,n}}class SampleAesDecrypter{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Decrypter(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,s){const r=t[e].unit;if(r.length<=16)return;const i=r.subarray(16,r.length-r.length%16),n=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(n).then(i=>{const n=new Uint8Array(i);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)})}decryptAacSamples(t,e,s){for(;;e++){if(e>=t.length)return void s();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,s=new Int8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)s.set(t.subarray(e,e+16),r);return s}getAvcDecryptedUnit(t,e){const s=new Uint8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)t.set(s.subarray(r,r+16),e);return t}decryptAvcSample(t,e,s,r,i){const n=Dt(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,s+1,r)})}decryptAvcSamples(t,e,s,r){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length)return void r();const i=t[e].units;for(;!(s>=i.length);s++){const n=i[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,s,r,n),this.decrypter.isSync())))return}}}}class TSDemuxer{constructor(t,e,s){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=s,this.videoParser=new AvcVideoParser}static probe(t){const e=TSDemuxer.syncOffset(t);return e>0&&v.warn("MPEG2-TS detected but first sync word found @ offset "+e),-1!==e}static syncOffset(t){const e=t.length;let s=Math.min(940,e-188)+1,r=0;for(;r<s;){let i=!1,n=-1,a=0;for(let o=r;o<e;o+=188){if(71!==t[o]||e-o!=188&&71!==t[o+188]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,t.length-188)+1)),i||(i=0===dr(t,o)),i&&a>1&&(0===n&&a>2||o+188>s))return n}r++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:ot[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,s,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=TSDemuxer.createTrack("video"),this._audioTrack=TSDemuxer.createTrack("audio",r),this._id3Track=TSDemuxer.createTrack("id3"),this._txtTrack=TSDemuxer.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,s=!1,r=!1){let i;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,g=a.pid,m=o.pid,p=a.pesData,y=o.pesData,E=null,T=this.pmtParsed,S=this._pmtId,L=t.length;if(this.remainderData&&(L=(t=At(this.remainderData,t)).length,this.remainderData=null),L<188&&!r)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const A=Math.max(0,TSDemuxer.syncOffset(t));L-=(L-A)%188,L<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,L,t.buffer.byteLength-L));let R=0;for(let e=A;e<L;e+=188)if(71===t[e]){const r=!!(64&t[e+1]),c=dr(t,e);let u;if((48&t[e+3])>>4>1){if(u=e+5+t[e+4],u===e+188)continue}else u=e+4;switch(c){case h:r&&(d&&(i=gr(d))&&this.videoParser.parseAVCPES(n,l,i,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(t.subarray(u,e+188)),d.size+=e+188-u);break;case g:if(r){if(p&&(i=gr(p)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,i);break;case"mp3":this.parseMPEGPES(a,i);break;case"ac3":this.parseAC3PES(a,i)}p={data:[],size:0}}p&&(p.data.push(t.subarray(u,e+188)),p.size+=e+188-u);break;case m:r&&(y&&(i=gr(y))&&this.parseID3PES(o,i),y={data:[],size:0}),y&&(y.data.push(t.subarray(u,e+188)),y.size+=e+188-u);break;case 0:r&&(u+=t[u]+1),S=this._pmtId=cr(t,u);break;case S:{r&&(u+=t[u]+1);const i=ur(t,u,this.typeSupported,s);h=i.videoPid,h>0&&(n.pid=h,n.segmentCodec=i.segmentVideoCodec),g=i.audioPid,g>0&&(a.pid=g,a.segmentCodec=i.segmentAudioCodec),m=i.id3Pid,m>0&&(o.pid=m),null===E||T||(v.warn(`MPEG-TS PMT found at ${e} after unknown PID '${E}'. Backtracking to sync byte @${A} to parse all TS packets.`),E=null,e=A-188),T=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=c}}else R++;if(R>0){const t=new Error(`Found ${R} TS packet/s that do not start with 0x47`);this.observer.emit(c.ERROR,c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message})}n.pesData=d,a.pesData=p,o.pesData=y;const b={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(b),b}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:s,id3Track:r,textTrack:i}=t,n=s.pesData,a=e.pesData,o=r.pesData;let l;if(n&&(l=gr(n))?(this.videoParser.parseAVCPES(s,i,l,!0,this._duration),s.pesData=null):s.pesData=n,a&&(l=gr(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&v.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=gr(o))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(t,e,s){const r=this.demux(t,s,!0,!this.config.progressive),i=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,e);return this.decrypt(r,i)}decrypt(t,e){return new Promise(s=>{const{audioTrack:r,videoTrack:i}=t;r.samples&&"aac"===r.segmentCodec?e.decryptAacSamples(r.samples,0,()=>{i.samples?e.decryptAvcSamples(i.samples,0,0,()=>{s(t)}):s(t)}):i.samples&&e.decryptAvcSamples(i.samples,0,0,()=>{s(t)})})}destroy(){this._duration=0}parseAACPES(t,e){let s=0;const r=this.aacOverFlow;let i,n,a,o=e.data;if(r){this.aacOverFlow=null;const e=r.missing,i=r.sample.unit.byteLength;if(-1===e)o=At(r.sample.unit,o);else{const n=i-e;r.sample.unit.set(o.subarray(0,e),n),t.samples.push(r.sample),s=r.missing}}for(i=s,n=o.length;i<n-1&&!Ws(o,i);i++);if(i!==s){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 s=new Error(t);if(v.warn("parsing error: "+t),this.observer.emit(c.ERROR,c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!1,levelRetry:e,error:s,reason:t}),!e)return}if(qs(t,this.observer,o,i,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!r)return void v.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Xs(t.samplerate);a=r.sample.pts+e}}let l,h=0;for(;i<n;){if(l=zs(t,o,i,a,h),i+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;i<n-1&&!Ws(o,i);i++);}}parseMPEGPES(t,e){const s=e.data,r=s.length;let i=0,n=0;const a=e.pts;if(void 0!==a)for(;n<r;)if(nr(s,n)){const e=sr(t,s,n,a,i);if(!e)break;n+=e.length,i++}else n++;else v.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const s=e.data,r=e.pts;if(void 0===r)return void v.warn("[tsdemuxer]: AC3 PES unknown PTS");const i=s.length;let n,a=0,o=0;for(;o<i&&(n=hr(t,s,o,r,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void v.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=o({},e,{type:this._videoTrack?Se:Ee,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function dr(t,e){return((31&t[e+1])<<8)+t[e+2]}function cr(t,e){return(31&t[e+10])<<8|t[e+11]}function ur(t,e,s,r){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=dr(t,e),a=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!r){fr("ADTS AAC");break}case 15:-1===i.audioPid&&(i.audioPid=n);break;case 21:-1===i.id3Pid&&(i.id3Pid=n);break;case 219:if(!r){fr("H.264");break}case 27:-1===i.videoPid&&(i.videoPid=n,i.segmentVideoCodec="avc");break;case 3:case 4:s.mpeg||s.mp3?-1===i.audioPid&&(i.audioPid=n,i.segmentAudioCodec="mp3"):v.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){fr("AC-3");break}case 129:s.ac3?-1===i.audioPid&&(i.audioPid=n,i.segmentAudioCodec="ac3"):v.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===i.audioPid&&a>0){let r=e+5,o=a;for(;o>2;){switch(t[r]){case 106:!0!==s.ac3?v.log("AC-3 audio found, not supported in this browser for now"):(i.audioPid=n,i.segmentAudioCodec="ac3")}const e=t[r+1]+2;r+=e,o-=e}}break;case 194:case 135:v.warn("Unsupported EC-3 in M2TS found");break;case 36:v.warn("Unsupported HEVC in M2TS found")}e+=a+5}return i}function fr(t){v.log(t+" with AES-128-CBC encryption found in unencrypted stream")}function gr(t){let e,s,r,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]=At(o[0],o[1]),o.splice(1,1);e=o[0];if(1===(e[0]<<16)+(e[1]<<8)+e[2]){if(s=(e[4]<<8)+e[5],s&&s>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&&(v.warn(Math.round((i-n)/9e4)+"s delta between PTS and DTS, align them"),i=n)):n=i),r=e[8];let h=r+9;if(t.size<=h)return null;t.size-=h;const d=new Uint8Array(t.size);for(let t=0,s=o.length;t<s;t++){e=o[t];let s=e.byteLength;if(h){if(h>s){h-=s;continue}e=e.subarray(h),s-=h,h=0}d.set(e,a),a+=s}return s&&(s-=r+3),{data:d,pts:i,dts:n,len:s}}return null}class AAC{static getSilentFrame(t,e){switch(t){case"mp4a.40.2":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]);break;default: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 mr=Math.pow(2,32)-1;class MP4{static init(){let t;for(t in MP4.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:[]},MP4.types)MP4.types.hasOwnProperty(t)&&(MP4.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]),s=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]);MP4.HDLR_TYPES={video:e,audio:s};const r=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]);MP4.STTS=MP4.STSC=MP4.STCO=i,MP4.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),MP4.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),MP4.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),MP4.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]);MP4.FTYP=MP4.box(MP4.types.ftyp,n,o,n,a),MP4.DINF=MP4.box(MP4.types.dinf,MP4.box(MP4.types.dref,r))}static box(t,...e){let s=8,r=e.length;const i=r;for(;r--;)s+=e[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),r=0,s=8;r<i;r++)n.set(e[r],s),s+=e[r].byteLength;return n}static hdlr(t){return MP4.box(MP4.types.hdlr,MP4.HDLR_TYPES[t])}static mdat(t){return MP4.box(MP4.types.mdat,t)}static mdhd(t,e){e*=t;const s=Math.floor(e/(mr+1)),r=Math.floor(e%(mr+1));return MP4.box(MP4.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,s>>24,s>>16&255,s>>8&255,255&s,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(t){return MP4.box(MP4.types.mdia,MP4.mdhd(t.timescale,t.duration),MP4.hdlr(t.type),MP4.minf(t))}static mfhd(t){return MP4.box(MP4.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?MP4.box(MP4.types.minf,MP4.box(MP4.types.smhd,MP4.SMHD),MP4.DINF,MP4.stbl(t)):MP4.box(MP4.types.minf,MP4.box(MP4.types.vmhd,MP4.VMHD),MP4.DINF,MP4.stbl(t))}static moof(t,e,s){return MP4.box(MP4.types.moof,MP4.mfhd(t),MP4.traf(s,e))}static moov(t){let e=t.length;const s=[];for(;e--;)s[e]=MP4.trak(t[e]);return MP4.box.apply(null,[MP4.types.moov,MP4.mvhd(t[0].timescale,t[0].duration)].concat(s).concat(MP4.mvex(t)))}static mvex(t){let e=t.length;const s=[];for(;e--;)s[e]=MP4.trex(t[e]);return MP4.box.apply(null,[MP4.types.mvex,...s])}static mvhd(t,e){e*=t;const s=Math.floor(e/(mr+1)),r=Math.floor(e%(mr+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,s>>24,s>>16&255,s>>8&255,255&s,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return MP4.box(MP4.types.mvhd,i)}static sdtp(t){const e=t.samples||[],s=new Uint8Array(4+e.length);let r,i;for(r=0;r<e.length;r++)i=e[r].flags,s[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return MP4.box(MP4.types.sdtp,s)}static stbl(t){return MP4.box(MP4.types.stbl,MP4.stsd(t),MP4.box(MP4.types.stts,MP4.STTS),MP4.box(MP4.types.stsc,MP4.STSC),MP4.box(MP4.types.stsz,MP4.STSZ),MP4.box(MP4.types.stco,MP4.STCO))}static avc1(t){let e,s,r,i=[],n=[];for(e=0;e<t.sps.length;e++)s=t.sps[e],r=s.byteLength,i.push(r>>>8&255),i.push(255&r),i=i.concat(Array.prototype.slice.call(s));for(e=0;e<t.pps.length;e++)s=t.pps[e],r=s.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(s));const a=MP4.box(MP4.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,h=t.pixelRatio[0],d=t.pixelRatio[1];return MP4.box(MP4.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,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(MP4.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(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 MP4.box(MP4.types.mp4a,MP4.audioStsd(t),MP4.box(MP4.types.esds,MP4.esds(t)))}static mp3(t){return MP4.box(MP4.types[".mp3"],MP4.audioStsd(t))}static ac3(t){return MP4.box(MP4.types["ac-3"],MP4.audioStsd(t),MP4.box(MP4.types.dac3,t.config))}static stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp3(t)):"ac3"===t.segmentCodec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.ac3(t)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp4a(t)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.avc1(t))}static tkhd(t){const e=t.id,s=t.duration*t.timescale,r=t.width,i=t.height,n=Math.floor(s/(mr+1)),a=Math.floor(s%(mr+1));return MP4.box(MP4.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,r>>8&255,255&r,0,0,i>>8&255,255&i,0,0]))}static traf(t,e){const s=MP4.sdtp(t),r=t.id,i=Math.floor(e/(mr+1)),n=Math.floor(e%(mr+1));return MP4.box(MP4.types.traf,MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),MP4.box(MP4.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])),MP4.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,MP4.box(MP4.types.trak,MP4.tkhd(t),MP4.mdia(t))}static trex(t){const e=t.id;return MP4.box(MP4.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 s=t.samples||[],r=s.length,i=12+16*r,n=new Uint8Array(i);let a,o,l,h,d,c;for(e+=8+i,n.set(["video"===t.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<r;a++)o=s[a],l=o.duration,h=o.size,d=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return MP4.box(MP4.types.trun,n)}static initSegment(t){MP4.types||MP4.init();const e=MP4.moov(t);return At(MP4.FTYP,e)}}MP4.types=void 0,MP4.HDLR_TYPES=void 0,MP4.STTS=void 0,MP4.STSC=void 0,MP4.STCO=void 0,MP4.STSZ=void 0,MP4.VMHD=void 0,MP4.SMHD=void 0,MP4.STSD=void 0,MP4.FTYP=void 0,MP4.DINF=void 0;function pr(t,e,s=1,r=!1){const i=t*e*s;return r?Math.round(i):i}function yr(t,e=!1){return pr(t,1e3,1/9e4,e)}let vr,Er=null,Tr=null;class MP4Remuxer{constructor(t,e,s,r=""){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=s,this.ISGenerated=!1,null===Er){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Er=t?parseInt(t[1]):0}if(null===Tr){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Tr=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){v.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){v.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){v.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const s=t.reduce((t,s)=>{const r=s.pts-t;return r<-4294967296?(e=!0,Sr(t,s.pts)):r>0?t:s.pts},t[0].pts);return e&&v.debug("PTS rollover detected"),s}remux(t,e,s,r,i,n,a,o){let l,h,d,c,u,f,g=i,m=i;const p=t.pid>-1,y=e.pid>-1,E=e.samples.length,T=t.samples.length>0,S=a&&E>0||E>1;if((!p||T)&&(!y||S)||this.ISGenerated||a){if(this.ISGenerated){var L,A,R,b;const t=this.videoTrackConfig;!t||e.width===t.width&&e.height===t.height&&(null==(L=e.pixelRatio)?void 0:L[0])===(null==(A=t.pixelRatio)?void 0:A[0])&&(null==(R=e.pixelRatio)?void 0:R[1])===(null==(b=t.pixelRatio)?void 0:b[1])||this.resetInitSegment()}else d=this.generateIS(t,e,i,n);const s=this.isVideoContiguous;let r,a=-1;if(S&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){v.warn(`[mp4-remuxer]: Dropped ${a} out of ${E} 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,r=m}else-1===a&&(v.warn(`[mp4-remuxer]: No keyframe found out of ${E} video samples`),f=!1);if(this.ISGenerated){if(T&&S){const s=this.getVideoStartPts(e.samples),r=(Sr(t.samples[0].pts,s)-s)/e.inputTimeScale;g+=Math.max(0,r),m+=Math.max(0,-r)}if(T){if(t.samplerate||(v.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,i,n)),h=this.remuxAudio(t,g,this.isAudioContiguous,n,y||S||o===de?m:void 0),S){const r=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(v.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,i,n)),l=this.remuxVideo(e,m,s,r)}}else S&&(l=this.remuxVideo(e,m,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=Lr(s,i,this._initPTS,this._initDTS)),r.samples.length&&(c=Ar(r,i,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:c,id3:u}}generateIS(t,e,s,r){const i=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,c,u=!l||r,f="audio/mp4";if(u&&(h=d=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):MP4.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(c=t.inputTimeScale,l&&c===l.timescale?u=!1:h=d=i[0].pts-Math.round(c*s))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:MP4.initSegment([e]),metadata:{width:e.width,height:e.height}},u)if(c=e.inputTimeScale,l&&c===l.timescale)u=!1;else{const t=this.getVideoStartPts(n),e=Math.round(c*s);d=Math.min(d,Sr(n[0].dts,t)-e),h=Math.min(h,t-e)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:c},this._initDTS={baseTime:d,timescale:c}):h=c=void 0,{tracks:o,initPTS:h,timescale:c}}remuxVideo(t,e,s,r){const i=t.inputTimeScale,n=t.samples,a=[],l=n.length,h=this._initPTS;let d,g,m=this.nextAvcDts,p=8,y=this.videoSampleDuration,E=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,S=!1;if(!s||null===m){const t=e*i,r=n[0].pts-Sr(n[0].dts,n[0].pts);Er&&null!==m&&Math.abs(t-r-m)<15e3?s=!0:m=t-r}const L=h.baseTime*i/h.timescale;for(let t=0;t<l;t++){const e=n[t];e.pts=Sr(e.pts-L,m),e.dts=Sr(e.dts-L,m),e.dts<n[t>0?t-1:t].dts&&(S=!0)}S&&n.sort((function(t,e){const s=t.dts-e.dts,r=t.pts-e.pts;return s||r})),d=n[0].dts,g=n[n.length-1].dts;const A=g-d,R=A?Math.round(A/(l-1)):y||t.inputTimeScale/30;if(s){const t=d-m,s=t>R,r=t<-1;if((s||r)&&(s?v.warn(`AVC: ${yr(t,!0)} ms (${t}dts) hole between fragments detected at ${e.toFixed(3)}`):v.warn(`AVC: ${yr(-t,!0)} ms (${t}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||m>=n[0].pts||Er)){d=m;const e=n[0].pts-t;if(s)n[0].dts=d,n[0].pts=e;else for(let s=0;s<n.length&&!(n[s].dts>e);s++)n[s].dts-=t,n[s].pts-=t;v.log(`Video: Initial PTS/DTS adjusted: ${yr(e,!0)}/${yr(d,!0)}, delta: ${yr(t,!0)} ms`)}}d=Math.max(0,d);let b=0,k=0,D=d;for(let t=0;t<l;t++){const e=n[t],s=e.units,r=s.length;let i=0;for(let t=0;t<r;t++)i+=s[t].data.length;k+=i,b+=r,e.length=i,e.dts<D?(e.dts=D,D+=R/4|0||1):D=e.dts,E=Math.min(e.pts,E),T=Math.max(e.pts,T)}g=n[l-1].dts;const C=k+4*b+8;let w;try{w=new Uint8Array(C)}catch(t){return void this.observer.emit(c.ERROR,c.ERROR,{type:u.MUX_ERROR,details:f.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:C,reason:"fail allocating video mdat "+C})}const P=new DataView(w.buffer);P.setUint32(0,C),w.set(MP4.types.mdat,4);let I=!1,_=Number.POSITIVE_INFINITY,M=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,F=Number.NEGATIVE_INFINITY;for(let t=0;t<l;t++){const e=n[t],s=e.units;let o,h=0;for(let t=0,e=s.length;t<e;t++){const e=s[t],r=e.data,i=e.data.byteLength;P.setUint32(p,i),p+=4,w.set(r,p),p+=i,h+=4+i}if(t<l-1)y=n[t+1].dts-e.dts,o=n[t+1].pts-e.pts;else{const s=this.config,a=t>0?e.dts-n[t-1].dts:R;if(o=t>0?e.pts-n[t-1].pts:R,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(s.maxBufferHole*i),n=(r?E+r*i:this.nextAudioPts)-e.pts;n>t?(y=n-a,y<0?y=a:I=!0,v.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${y/90} ms for the last video frame.`)):y=a}else y=a}const d=Math.round(e.pts-e.dts);_=Math.min(_,y),x=Math.max(x,y),M=Math.min(M,o),F=Math.max(F,o),a.push(new Mp4Sample(e.key,y,h,d))}if(a.length)if(Er){if(Er<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Tr&&F-M<x-_&&R/x<.025&&0===a[0].cts){v.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=d;for(let e=0,s=a.length;e<s;e++){const r=t+a[e].duration,i=t+a[e].cts;if(e<s-1){const t=r+a[e+1].cts;a[e].duration=t-i}else a[e].duration=e?a[e-1].duration:R;a[e].cts=0,t=r}}y=I||!y?R:y,this.nextAvcDts=m=g+y,this.videoSampleDuration=y,this.isVideoContiguous=!0;const O={data1:MP4.moof(t.sequenceNumber++,d,o({},t,{samples:a})),data2:w,startPTS:E/i,endPTS:(T+y)/i,startDTS:d/i,endDTS:m/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,s,r,i){const n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),l=this.getSamplesPerFrame(t),h=l*a,d=this._initPTS,g="mp3"===t.segmentCodec&&this.typeSupported.mpeg,m=[],p=void 0!==i;let y=t.samples,E=g?0:8,T=this.nextAudioPts||-1;const S=e*n,L=d.baseTime*n/d.timescale;if(this.isAudioContiguous=s=s||y.length&&T>0&&(r&&Math.abs(S-T)<9e3||Math.abs(Sr(y[0].pts-L,S)-T)<20*h),y.forEach((function(t){t.pts=Sr(t.pts-L,S)})),!s||T<0){if(y=y.filter(t=>t.pts>=0),!y.length)return;T=0===i?0:r&&!p?Math.max(0,S):y[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,r=T;s<y.length;s++){const i=y[s],a=i.pts,o=a-r,l=Math.abs(1e3*o/n);if(o<=-e*h&&p)0===s&&(v.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/n)} ms.`),this.nextAudioPts=T=r=a);else if(o>=e*h&&l<1e4&&p){let e=Math.round(o/h);r=a-e*h,r<0&&(e--,r+=h),0===s&&(this.nextAudioPts=T=r),v.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(r/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){const e=Math.max(r,0);let n=AAC.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);n||(v.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=i.unit.subarray()),y.splice(s,0,{unit:n,pts:e}),r+=h,s++}}i.pts=r,r+=h}}let A,R=null,b=null,k=0,D=y.length;for(;D--;)k+=y[D].unit.byteLength;for(let e=0,r=y.length;e<r;e++){const r=y[e],i=r.unit;let n=r.pts;if(null!==b){m[e-1].duration=Math.round((n-b)/a)}else{if(s&&"aac"===t.segmentCodec&&(n=T),R=n,!(k>0))return;k+=E;try{A=new Uint8Array(k)}catch(t){return void this.observer.emit(c.ERROR,c.ERROR,{type:u.MUX_ERROR,details:f.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:k,reason:"fail allocating audio mdat "+k})}if(!g){new DataView(A.buffer).setUint32(0,k),A.set(MP4.types.mdat,4)}}A.set(i,E);const o=i.byteLength;E+=o,m.push(new Mp4Sample(!0,l,o,0)),b=n}const C=m.length;if(!C)return;const w=m[m.length-1];this.nextAudioPts=T=b+a*w.duration;const P=g?new Uint8Array(0):MP4.moof(t.sequenceNumber++,R/a,o({},t,{samples:m}));t.samples=[];const I=R/n,_=T/n,M={data1:P,data2:A,startPTS:I,endPTS:_,startDTS:I,endDTS:_,type:"audio",hasAudio:!0,hasVideo:!1,nb:C};return this.isAudioContiguous=!0,M}remuxEmptyAudio(t,e,s,r){const i=t.inputTimeScale,n=i/(t.samplerate?t.samplerate:i),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:r.startDTS*i)+l,d=r.endDTS*i+l,c=1024*n,u=Math.ceil((d-h)/c),f=AAC.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(v.warn("[mp4-remuxer]: remux empty Audio"),!f)return void v.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<u;t++){const e=h+t*c;g.push({unit:f,pts:e,dts:e})}return t.samples=g,this.remuxAudio(t,e,s,!1)}}function Sr(t,e){let s;if(null===e)return t;for(s=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=s;return t}function Lr(t,e,s,r){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=Sr(i.pts-s.baseTime*n/s.timescale,e*n)/n,i.dts=Sr(i.dts-r.baseTime*n/r.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Ar(t,e,s){const r=t.samples.length;if(!r)return;const i=t.inputTimeScale;for(let n=0;n<r;n++){const r=t.samples[n];r.pts=Sr(r.pts-s.baseTime*i/s.timescale,e*i)/i}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}class Mp4Sample{constructor(t,e,s,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=s,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function Rr(t,e){const s=null==t?void 0:t.codec;if(s&&s.length>4)return s;if(e===L){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return Yt(s,!1)}const t="mp4a.40.5";return v.info(`Parsed audio codec "${s}" or audio object type not handled. Using "${t}"`),t}return v.warn(`Unhandled video codec "${s}"`),"hvc1"===s||"hev1"===s?"hvc1.1.6.L120.90":"av01"===s?"av01.0.04M.08":"avc1.42e01e"}try{vr=self.performance.now.bind(self.performance)}catch(t){v.debug("Unable to use Performance API on this environment"),vr=null==C?void 0:C.Date.now}const br=[{demux:class MP4Demuxer{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,s,r){const i=this.videoTrack=Gs("video",1),n=this.audioTrack=Gs("audio",1),a=this.txtTrack=Gs("text",1);if(this.id3Track=Gs("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=pt(t);if(o.video){const{id:t,timescale:e,codec:s}=o.video;i.id=t,i.timescale=a.timescale=e,i.codec=s}if(o.audio){const{id:t,timescale:e,codec:s}=o.audio;n.id=t,n.timescale=e,n.codec=s}a.id=ot.text,i.sampleDuration=0,i.duration=n.duration=r}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let s=0;s<e;){const r=dt(t,s);if(r>8&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7])return!0;s=r>1?s+r:e}return!1}(t)}demux(t,e){this.timeOffset=e;let s=t;const r=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=At(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=gt(t,["moof"]);if(s.length<2)return e.remainder=t,e;const r=s[s.length-1];return e.valid=$(t,0,r.byteOffset-8),e.remainder=$(t,r.byteOffset-8),e}(s);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=s;const n=this.extractID3Track(r,e);return i.samples=Rt(e,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,s=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(e,this.timeOffset);return s.samples=Rt(t,e),{videoTrack:e,audioTrack:Gs(),id3Track:r,textTrack:Gs()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const r=gt(t.samples,["emsg"]);r&&r.forEach(t=>{const r=function(t){const e=t[0];let s="",r="",i=0,n=0,a=0,o=0,l=0,d=0;if(0===e){for(;"\0"!==lt(t.subarray(d,d+1));)s+=lt(t.subarray(d,d+1)),d+=1;for(s+=lt(t.subarray(d,d+1)),d+=1;"\0"!==lt(t.subarray(d,d+1));)r+=lt(t.subarray(d,d+1)),d+=1;r+=lt(t.subarray(d,d+1)),d+=1,i=dt(t,12),n=dt(t,16),o=dt(t,20),l=dt(t,24),d=28}else if(1===e){d+=4,i=dt(t,d),d+=4;const e=dt(t,d);d+=4;const n=dt(t,d);for(d+=4,a=2**32*e+n,h(a)||(a=Number.MAX_SAFE_INTEGER,v.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=dt(t,d),d+=4,l=dt(t,d),d+=4;"\0"!==lt(t.subarray(d,d+1));)s+=lt(t.subarray(d,d+1)),d+=1;for(s+=lt(t.subarray(d,d+1)),d+=1;"\0"!==lt(t.subarray(d,d+1));)r+=lt(t.subarray(d,d+1)),d+=1;r+=lt(t.subarray(d,d+1)),d+=1}return{schemeIdUri:s,value:r,timeScale:i,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(d,t.byteLength)}}(t);if(or.test(r.schemeIdUri)){const t=l(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale;let i=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const n=r.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:Se,duration:i})}})}return s}demuxSampleAes(t,e,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class PassThroughRemuxer{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,s,r){this.audioCodec=e,this.videoCodec=s,this.generateInitSegment(function(t,e){if(!t||!e)return t;const s=e.keyId;if(s&&e.isCommonEncryption){gt(t,["moov","trak"]).forEach(t=>{const e=gt(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=gt(e,["enca"]);const i=r.length>0;i||(r=gt(e,["encv"])),r.forEach(t=>{gt(i?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const e=St(t);if(e){const t=e.subarray(8,24);t.some(t=>0!==t)||(v.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${it(t)} -> ${it(s)}`),e.set(s,8))}})})})}return t}(t,r)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const r=this.initData=pt(t);r.audio&&(e=Rr(r.audio,L)),r.video&&(s=Rr(r.video,A));const i={};r.audio&&r.video?i.audiovideo={container:"video/mp4",codec:e+","+s,initSegment:t,id:"main"}:r.audio?i.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:r.video?i.video={container:"video/mp4",codec:s,initSegment:t,id:"main"}:v.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=i}remux(t,e,s,r,i,n){var a,o;let{initPTS:h,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};l(d)||(d=this.lastEndTime=i||0);const u=e.samples;if(null==u||!u.length)return c;const f={initPTS:void 0,timescale:1};let g=this.initData;if(null!=(a=g)&&a.length||(this.generateInitSegment(u),g=this.initData),null==(o=g)||!o.length)return v.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=function(t,e){let s=0,r=0,i=0;const n=gt(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=gt(a,["tfhd"])[0],l=e[dt(o,4)];if(!l)continue;const h=l.default,d=dt(o,0)|(null==h?void 0:h.flags);let c=null==h?void 0:h.duration;8&d&&(c=dt(o,2&d?12:8));const u=l.timescale||9e4,f=gt(a,["trun"]);for(let t=0;t<f.length;t++){if(s=Lt(f[t]),!s&&c){s=c*dt(f[t],4)}l.type===A?r+=s/u:l.type===L&&(i+=s/u)}}if(0===r&&0===i){let e=1/0,s=0,r=0;const i=gt(t,["sidx"]);for(let t=0;t<i.length;t++){const n=mt(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);s=Math.max(s,t+n.earliestPresentationTime/n.timescale),r=s-e}}if(r&&l(r))return r}return r||i}(u,g),p=function(t,e){return gt(e,["moof","traf"]).reduce((e,s)=>{const r=gt(s,["tfdt"])[0],i=r[0],n=gt(s,["tfhd"]).reduce((e,s)=>{const n=dt(s,4),a=t[n];if(a){let t=dt(r,4);if(1===i){if(t===nt)return v.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=nt+1,t+=dt(r,8)}const s=t/(a.timescale||9e4);if(l(s)&&(null===e||s<e))return s}return e},null);return null!==n&&l(n)&&(null===e||n<e)?n:e},null)}(g,u),y=null===p?i:p;(function(t,e,s,r){if(null===t)return!0;const i=Math.max(r,1),n=e-t.baseTime/t.timescale;return Math.abs(n-s)>i}(h,y,i,m)||f.timescale!==h.timescale&&n)&&(f.initPTS=y-i,h&&1===h.timescale&&v.warn("Adjusting initPTS by "+(f.initPTS-h.baseTime)),this.initPTS=h={baseTime:f.initPTS,timescale:1});const E=t?y-h.baseTime/h.timescale:d,T=E+m;!function(t,e,s){gt(e,["moof","traf"]).forEach(e=>{gt(e,["tfhd"]).forEach(r=>{const i=dt(r,4),n=t[i];if(!n)return;const a=n.timescale||9e4;gt(e,["tfdt"]).forEach(t=>{const e=t[0],r=s*a;if(r){let s=dt(t,4);if(0===e)s-=r,s=Math.max(s,0),ft(t,4,s);else{s*=Math.pow(2,32),s+=dt(t,8),s-=r,s=Math.max(s,0);const e=Math.floor(s/(nt+1)),i=Math.floor(s%(nt+1));ft(t,4,e),ft(t,8,i)}}})})})}(g,u,h.baseTime/h.timescale),m>0?this.lastEndTime=T:(v.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const S=!!g.audio,R=!!g.video;let b="";S&&(b+="audio"),R&&(b+="video");const k={data1:u,startPTS:E,startDTS:E,endPTS:T,endDTS:T,type:b,hasAudio:S,hasVideo:R,nb:1,dropped:0};return c.audio="audio"===k.type?k:void 0,c.video="audio"!==k.type?k:void 0,c.initSegment=f,c.id3=Lr(s,i,h,h),r.samples.length&&(c.text=Ar(r,i,h)),c}}},{demux:TSDemuxer,remux:MP4Remuxer},{demux:class AACDemuxer extends BaseAudioDemuxer{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,s,r){super.resetInitSegment(t,e,s,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=H(t,0);let s=(null==e?void 0:e.length)||0;if(ar(t,s))return!1;for(let e=t.length;s<e;s++)if(js(t,s))return v.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)&&Hs(t,e)&&Ys(t,e)<=t.length-e}(t,e)}appendFrame(t,e,s){qs(t,this.observer,e,s,t.manifestCodec);const r=zs(t,e,s,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:MP4Remuxer},{demux:class MP3Demuxer extends BaseAudioDemuxer{resetInitSegment(t,e,s,r){super.resetInitSegment(t,e,s,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=H(t,0);let s=(null==e?void 0:e.length)||0;if(e&&11===t[s]&&119===t[s+1]&&void 0!==W(e)&&lr(t,s)<=16)return!1;for(let e=t.length;s<e;s++)if(ar(t,s))return v.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return ir(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,s){if(null!==this.basePTS)return sr(t,e,s,this.basePTS,this.frameIndex)}},remux:MP4Remuxer}];br.splice(2,0,{demux:AC3Demuxer,remux:MP4Remuxer});class Transmuxer{constructor(t,e,s,r,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=s,this.vendor=r,this.id=i}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,s,r){const i=s.transmuxing;i.executeStart=vr();let n=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:g,timeOffset:m,initSegmentChange:p}=r||a,{audioCodec:y,videoCodec:E,defaultInitPts:T,duration:S,initSegmentData:L}=o,A=function(t,e){let s=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(s=e);return s}(n,e);if(A&&"AES-128"===A.method){const t=this.getDecrypter();if(!t.isSync())return this.decryptionPromise=t.webCryptoDecrypt(n,A.key.buffer,A.iv.buffer).then(t=>{const e=this.push(t,null,s);return this.decryptionPromise=null,e}),this.decryptionPromise;{let e=t.softwareDecrypt(n,A.key.buffer,A.iv.buffer);if(s.part>-1&&(e=t.flush()),!e)return i.executeEnd=vr(),kr(s);n=new Uint8Array(e)}}const R=this.needsProbing(h,d);if(R){const t=this.configureTransmuxer(n);if(t)return v.warn("[transmuxer] "+t.message),this.observer.emit(c.ERROR,c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),i.executeEnd=vr(),kr(s)}(h||d||p||R)&&this.resetInitSegment(L,y,E,S,e),(h||p||R)&&this.resetInitialTimestamp(T),l||this.resetContiguity();const b=this.transmux(n,A,m,g,s),k=this.currentTransmuxState;return k.contiguous=!0,k.discontinuity=!1,k.trackSwitch=!1,i.executeEnd=vr(),b}flush(t){const e=t.transmuxing;e.executeStart=vr();const{decrypter:s,currentTransmuxState:r,decryptionPromise:i}=this;if(i)return i.then(()=>this.flush(t));const n=[],{timeOffset:a}=r;if(s){const e=s.flush();e&&n.push(this.push(e,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return e.executeEnd=vr(),[kr(t)];const h=o.flush(a);return Dr(h)?h.then(e=>(this.flushRemux(n,e,t),n)):(this.flushRemux(n,h,t),n)}flushRemux(t,e,s){const{audioTrack:r,videoTrack:i,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;v.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const h=this.remuxer.remux(r,i,n,a,l,o,!0,this.id);t.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=vr()}resetInitialTimestamp(t){const{demuxer:e,remuxer:s}=this;e&&s&&(e.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,s,r,i){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,s,r),a.resetInitSegment(t,e,s,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,s,r,i){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,s,r,i):this.transmuxUnencrypted(t,s,r,i),n}transmuxUnencrypted(t,e,s,r){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,s,!1,this.id),chunkMeta:r}}transmuxSampleAes(t,e,s,r,i){return this.demuxer.demuxSampleAes(t,e,s).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,r,!1,this.id),chunkMeta:i}))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:r,vendor:i}=this;let n;for(let e=0,s=br.length;e<s;e++){var a;if(null!=(a=br[e].demux)&&a.probe(t)){n=br[e];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,h=n.remux,d=n.demux;l&&l instanceof h||(this.remuxer=new h(s,e,r,i)),o&&o instanceof d||(this.demuxer=new d(s,e,r),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Decrypter(this.config)),t}}const kr=t=>({remuxResult:{},chunkMeta:t});function Dr(t){return"then"in t&&t.then instanceof Function}class TransmuxConfig{constructor(t,e,s,r,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=s,this.duration=r,this.defaultInitPts=i||null}}class TransmuxState{constructor(t,e,s,r,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=s,this.trackSwitch=r,this.timeOffset=i,this.initSegmentChange=n}}var Cr={exports:{}};!function(t){var e=Object.prototype.hasOwnProperty,s="~";function r(){}function i(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function n(t,e,r,n,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new i(r,n||t,a),l=s?s+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 r:delete t._events[e]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,r,i=[];if(0===this._eventsCount)return i;for(r in t=this._events)e.call(t,r)&&i.push(s?r.slice(1):r);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(t)):i},o.prototype.listeners=function(t){var e=s?s+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,n=r.length,a=new Array(n);i<n;i++)a[i]=r[i].fn;return a},o.prototype.listenerCount=function(t){var e=s?s+t:t,r=this._events[e];return r?r.fn?1:r.length:0},o.prototype.emit=function(t,e,r,i,n,a){var o=s?s+t:t;if(!this._events[o])return!1;var l,h,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,r),!0;case 4:return d.fn.call(d.context,e,r,i),!0;case 5:return d.fn.call(d.context,e,r,i,n),!0;case 6:return d.fn.call(d.context,e,r,i,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(t,d[h].fn,void 0,!0),c){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,e);break;case 3:d[h].fn.call(d[h].context,e,r);break;case 4:d[h].fn.call(d[h].context,e,r,i);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(t,e,s){return n(this,t,e,s,!1)},o.prototype.once=function(t,e,s){return n(this,t,e,s,!0)},o.prototype.removeListener=function(t,e,r,i){var n=s?s+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||r&&o.context!==r||a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==e||i&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=s?s+t:t,this._events[e]&&a(this,e)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,t.exports=o}(Cr);var wr=t(Cr.exports);class TransmuxerInterface{constructor(t,e,s,r){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=s,this.onFlush=r;const n=(t,e)=>{(e=e||{}).frag=this.frag,e.id=this.id,t===c.ERROR&&(this.error=e.error),this.hls.trigger(t,e)};this.observer=new wr,this.observer.on(c.FRAG_DECRYPTED,n),this.observer.on(c.ERROR,n);const a=Ot(i.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')},l=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(i.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{i.workerPath?(v.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)):(v.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 s=new Error(`${t.message} (${t.filename}:${t.lineno})`);i.enableWorker=!1,v.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(c.ERROR,{type:u.OTHER_ERROR,details:f.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:s})},t.postMessage({cmd:"init",typeSupported:o,vendor:l,id:e,config:JSON.stringify(i)})}catch(t){v.warn(`Error setting up "${e}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,o,i,l,e)}return}}this.transmuxer=new Transmuxer(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,s,r,i,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{transmuxer:u}=this,f=n?n.start:i.start,g=i.decryptdata,m=this.frag,p=!(m&&i.cc===m.cc),y=!(m&&l.level===m.level),E=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),L=!y&&(1===E||0===E&&(1===T||S&&T<=0)),A=self.performance.now();(y||E||0===i.stats.parsing.start)&&(i.stats.parsing.start=A),!n||!T&&L||(n.stats.parsing.start=A);const R=!(m&&(null==(d=i.initSegment)?void 0:d.url)===(null==(c=m.initSegment)?void 0:c.url)),b=new TransmuxState(p,L,o,y,f,R);if(!L||p||R){v.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: ${y}\n contiguous: ${L}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${R}`);const t=new TransmuxConfig(s,r,e,a,h);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:b},t instanceof ArrayBuffer?[t]:[]);else if(u){const e=u.push(t,g,l,b);Dr(e)?(u.async=!0,e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")})):(u.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 s=e.flush(t);Dr(s)||e.async?(Dr(s)||(s=Promise.resolve(s)),s.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")})):this.handleFlushResult(s,t)}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,chunkMeta:e,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}onWorkerMessage(t){const e=t.data,s=this.hls;switch(e.event){case"init":{var r;const t=null==(r=this.workerContext)?void 0:r.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":v[e.data.logType]&&v[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,s.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)}}function Pr(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!Ir(t[s].attrs,e[s].attrs))return!1;return!0}function Ir(t,e,s){const r=t["STABLE-RENDITION-ID"];return r&&!s?r===e["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>t[s]!==e[s])}function _r(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class BufferableInstance{constructor(t){this.buffered=void 0;const e=(e,s,r)=>{if((s>>>=0)>r-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${r})`);return t[s][e]};this.buffered={get length(){return t.length},end:s=>e("end",s,t.length),start:s=>e("start",s,t.length)}}}class BufferOperationQueue{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e,s){const r=this.queues[e];r.push(t),1!==r.length||s||this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const s=new Promise(t=>{e=t}),r={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,t),s}executeNext(t){const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(e){v.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${e}`),s.onError(e);const r=this.buffers[t];null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Mr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function xr(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}const Fr={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Or=function(t){let e=t;return Fr.hasOwnProperty(t)&&(e=Fr[t]),String.fromCharCode(e)},Nr={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ur={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Br={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},$r={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Gr=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class CaptionsLogger{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const s="function"==typeof e?e():e;v.log(`${this.time} [${t}] ${s}`)}}}const Kr=function(t){const e=[];for(let s=0;s<t.length;s++)e.push(t[s].toString(16));return e};class PenState{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const e=["foreground","underline","italics","background","flash"];for(let s=0;s<e.length;s++){const r=e[s];t.hasOwnProperty(r)&&(this[r]=t[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class StyledUnicodeChar{constructor(){this.uchar=" ",this.penState=new PenState}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class Row{constructor(t){this.chars=[],this.pos=0,this.currPenState=new PenState,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<100;t++)this.chars.push(new StyledUnicodeChar);this.logger=t}equals(t){for(let e=0;e<100;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<100;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<100;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>100&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=100)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=Or(t);this.pos>=100?this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<100;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let s=0;s<100;s++){const r=this.chars[s].uchar;" "!==r&&(e=!1),t.push(r)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class CaptionScreen{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<15;e++)this.rows.push(new Row(t));this.logger=t}reset(){for(let t=0;t<15;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let s=0;s<15;s++)if(!this.rows[s].equals(t.rows[s])){e=!1;break}return e}copy(t){for(let e=0;e<15;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<15;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+JSON.stringify(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<15;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const r=s.rows[t].cueStartTime,i=this.logger.time;if(null!==r&&null!==i&&r<i)for(let r=0;r<this.nrRollUpRows;r++)this.rows[e-this.nrRollUpRows+r+1].copy(s.rows[t+r])}}this.currRow=e;const s=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,r=Math.max(e-1,0);s.setCursor(t.indent),t.color=s.chars[r].penState.foreground}const r={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+JSON.stringify(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let s="",r=-1;for(let s=0;s<15;s++){const i=this.rows[s].getTextString();i&&(r=s+1,t?e.push("Row "+r+": '"+i+"'"):e.push(i.trim()))}return e.length>0&&(s=t?"["+e.join(" | ")+"]":e.join("\n")),s}getTextAndFormat(){return this.rows}}class Cea608Channel{constructor(t,e,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new CaptionScreen(s),this.nonDisplayedMemory=new CaptionScreen(s),this.lastOutputScreen=new CaptionScreen(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const s=Math.floor(t/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=r[s]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class Cea608Parser{constructor(t,e,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const r=this.logger=new CaptionsLogger;this.channels=[null,new Cea608Channel(t,e,r),new Cea608Channel(t+1,s,r)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){let s,r,i,n=!1;this.logger.time=t;for(let t=0;t<e.length;t+=2)if(r=127&e[t],i=127&e[t+1],0!==r||0!==i){if(this.logger.log(3,"["+Kr([e[t],e[t+1]])+"] -> ("+Kr([r,i])+")"),s=this.parseCmd(r,i),s||(s=this.parseMidrow(r,i)),s||(s=this.parsePAC(r,i)),s||(s=this.parseBackgroundAttributes(r,i)),!s&&(n=this.parseChars(r,i),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}s||n||this.logger.log(2,"Couldn't parse cleaned data "+Kr([r,i])+" orig: "+Kr([e[t],e[t+1]]))}}parseCmd(t,e){const{cmdHistory:s}=this;if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;if(Vr(t,e,s))return Hr(null,null,s),this.logger.log(3,"Repeated command ("+Kr([t,e])+") is dropped"),!0;const r=20===t||21===t||23===t?1:2,i=this.channels[r];return 20===t||21===t||28===t||29===t?32===e?i.ccRCL():33===e?i.ccBS():34===e?i.ccAOF():35===e?i.ccAON():36===e?i.ccDER():37===e?i.ccRU(2):38===e?i.ccRU(3):39===e?i.ccRU(4):40===e?i.ccFON():41===e?i.ccRDC():42===e?i.ccTR():43===e?i.ccRTD():44===e?i.ccEDM():45===e?i.ccCR():46===e?i.ccENM():47===e&&i.ccEOC():i.ccTO(e-32),Hr(t,e,s),this.currentChannel=r,!0}parseMidrow(t,e){let s=0;if((17===t||25===t)&&e>=32&&e<=47){if(s=17===t?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[s];return!!r&&(r.ccMIDROW(e),this.logger.log(3,"MIDROW ("+Kr([t,e])+")"),!0)}return!1}parsePAC(t,e){let s;const r=this.cmdHistory;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;if(Vr(t,e,r))return Hr(null,null,r),!0;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?Nr[t]:Br[t]:1===i?Ur[t]:$r[t];const n=this.channels[i];return!!n&&(n.setPAC(this.interpretPAC(s,e)),Hr(t,e,r),this.currentChannel=i,!0)}interpretPAC(t,e){let s;const r={color:null,italics:!1,indent:null,underline:!1,row:t};return s=e>95?e-96:e-64,r.underline=1==(1&s),s<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((s-16)/2),r}parseChars(t,e){let s,r=null,i=null;if(t>=25?(s=2,i=t-8):(s=1,i=t),i>=17&&i<=19){let t;t=17===i?e+80:18===i?e+112:e+144,this.logger.log(2,"Special char '"+Or(t)+"' in channel "+s),r=[t]}else t>=32&&t<=127&&(r=0===e?[t]:[t,e]);if(r){const s=Kr(r);this.logger.log(3,"Char codes = "+s.join(",")),Hr(t,e,this.cmdHistory)}return r}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let s;const r={};16===t||24===t?(s=Math.floor((e-32)/2),r.background=Gr[s],e%2==1&&(r.background=r.background+"_semi")):45===e?r.background="transparent":(r.foreground="black",47===e&&(r.underline=!0));const i=t<=23?1:2;return this.channels[i].setBkgData(r),Hr(t,e,this.cmdHistory),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}this.cmdHistory={a:null,b:null}}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const s=this.channels[e];s&&s.cueSplitAtTime(t)}}}function Hr(t,e,s){s.a=t,s.b=e}function Vr(t,e,s){return s.a===t&&s.b===e}class OutputFilter{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,s){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Yr=function(){if(null!=C&&C.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function s(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const s=e.toLowerCase();return!!~t.indexOf(s)&&s}function r(t){return s(e,t)}function i(t,...e){let s=1;for(;s<arguments.length;s++){const e=arguments[s];for(const s in e)t[s]=e[s]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,c=e,u=n,f=a,g=null,m="",p=!0,y="auto",v="start",E=50,T="middle",S=50,L="middle";Object.defineProperty(o,"id",i({},l,{get:function(){return h},set:function(t){h=""+t}})),Object.defineProperty(o,"pauseOnExit",i({},l,{get:function(){return d},set:function(t){d=!!t}})),Object.defineProperty(o,"startTime",i({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",i({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",i({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",i({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",i({},l,{get:function(){return m},set:function(e){const r=function(e){return s(t,e)}(e);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");m=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",i({},l,{get:function(){return p},set:function(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",i({},l,{get:function(){return y},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",i({},l,{get:function(){return v},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",i({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",i({},l,{get:function(){return T},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",i({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",i({},l,{get:function(){return L},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");L=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class StringDecoder{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Wr(t){function e(t,e,s,r){return 3600*(0|t)+60*(0|e)+(0|s)+parseFloat(r||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?e(s[2],s[3],0,s[4]):e(s[1],s[2],s[3],s[4]):null}class Settings{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,s){return s?this.has(t)?this.values[t]:e[s]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,s){for(let r=0;r<s.length;++r)if(e===s[r]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const s=parseFloat(e);if(s>=0&&s<=100)return this.set(t,s),!0}return!1}}function jr(t,e,s,r){const i=r?t.split(r):[t];for(const t in i){if("string"!=typeof i[t])continue;const r=i[t].split(s);if(2!==r.length)continue;e(r[0],r[1])}}const qr=new Yr(0,0,""),Xr="middle"===qr.align?"middle":"center";function zr(t,e,s){const r=t;function i(){const e=Wr(t);if(null===e)throw new Error("Malformed timestamp: "+r);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=i(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);t=t.slice(3),n(),e.endTime=i(),n(),function(t,e){const r=new Settings;jr(t,(function(t,e){let i;switch(t){case"region":for(let i=s.length-1;i>=0;i--)if(s[i].id===e){r.set(t,s[i].region);break}break;case"vertical":r.alt(t,e,["rl","lr"]);break;case"line":i=e.split(","),r.integer(t,i[0]),r.percent(t,i[0])&&r.set("snapToLines",!1),r.alt(t,i[0],["auto"]),2===i.length&&r.alt("lineAlign",i[1],["start",Xr,"end"]);break;case"position":i=e.split(","),r.percent(t,i[0]),2===i.length&&r.alt("positionAlign",i[1],["start",Xr,"end","line-left","line-right","auto"]);break;case"size":r.percent(t,e);break;case"align":r.alt(t,e,["start",Xr,"end","left","right"])}}),/:/,/\s/),e.region=r.get("region",null),e.vertical=r.get("vertical","");let i=r.get("line","auto");"auto"===i&&-1===qr.line&&(i=-1),e.line=i,e.lineAlign=r.get("lineAlign","start"),e.snapToLines=r.get("snapToLines",!0),e.size=r.get("size",100),e.align=r.get("align",Xr);let n=r.get("position","auto");"auto"===n&&50===qr.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function Qr(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class VTTParser{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new StringDecoder,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function s(){let t=e.buffer,s=0;for(t=Qr(t);s<t.length&&"\r"!==t[s]&&"\n"!==t[s];)++s;const r=t.slice(0,s);return"\r"===t[s]&&++s,"\n"===t[s]&&++s,e.buffer=t.slice(s),r}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=s();const r=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let r=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(r?r=!1:t=s(),e.state){case"HEADER":/:/.test(t)?jr(t,(function(t,e){}),/:/):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new Yr(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{zr(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==t.indexOf("--\x3e");if(!t||s&&(r=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const Jr=/\r\n|\n\r|\n|\r/g,Zr=function(t,e,s=0){return t.slice(s,s+e.length)===e},ti=function(t){let e=5381,s=t.length;for(;s;)e=33*e^t.charCodeAt(--s);return(e>>>0).toString()};function ei(t,e,s){return ti(t.toString())+ti(e.toString())+ti(s)}function si(t,e,s,r,i,n,a){const o=new VTTParser,h=et(new Uint8Array(t)).trim().replace(Jr,"\n").split("\n"),d=[],c=e?function(t,e=1){return pr(t,9e4,1/e)}(e.baseTime,e.timescale):0;let u,f="00:00.000",g=0,m=0,p=!0;o.oncue=function(t){const n=s[r];let a=s.ccOffset;const o=(g-c)/9e4;if(null!=n&&n.new&&(void 0!==m?a=s.ccOffset=n.start:function(t,e,s){let r=t[e],i=t[r.prevCC];if(!i||!i.new&&r.new)return t.ccOffset=t.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=i)&&n.new;){var n;t.ccOffset+=r.start-i.start,r.new=!1,r=i,i=t[r.prevCC]}t.presentationOffset=s}(s,r,o)),o){if(!e)return void(u=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=t.endTime-t.startTime,h=Sr(9e4*(t.startTime+a-m),9e4*i)/9e4;t.startTime=Math.max(h,0),t.endTime=Math.max(h+l,0);const f=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(f)),t.id||(t.id=ei(t.startTime,t.endTime,f)),t.endTime>0&&d.push(t)},o.onparsingerror=function(t){u=t},o.onflush=function(){u?a(u):n(d)},h.forEach(t=>{if(p){if(Zr(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach(t=>{Zr(t,"LOCAL:")?f=t.slice(6):Zr(t,"MPEGTS:")&&(g=parseInt(t.slice(7)))});try{m=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),i=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(l(e)&&l(s)&&l(r)&&l(i)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+t);return e+=1e3*s,e+=6e4*r,e+=36e5*i,e}(f)/1e3}catch(t){u=t}return}""===t&&(p=!1)}o.parse(t+"\n")}),o.flush()}const ri=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,ii=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ni={left:"start",center:"center",right:"end",start:"start",end:"end"};function ai(t,e,s,r){const i=gt(new Uint8Array(t),["mdat"]);if(0===i.length)return void r(new Error("Could not parse IMSC1 mdat"));const n=i.map(t=>et(t)),a=function(t,e,s=1,r=!1){return pr(t,e,1/s,r)}(e.baseTime,1,e.timescale);try{n.forEach(t=>s(function(t,e){const s=new DOMParser,r=s.parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(i).reduce((t,e)=>(t[e]=r.getAttribute("ttp:"+e)||i[e],t),{}),a="preserve"!==r.getAttribute("xml:space"),l=li(oi(r,"styling","style")),h=li(oi(r,"layout","region")),d=oi(r,"body","[begin]");return[].map.call(d,t=>{const s=function t(e,s){return[].slice.call(e.childNodes).reduce((e,r,i)=>{var n;return"br"===r.nodeName&&i?e+"\n":null!=(n=r.childNodes)&&n.length?t(r,s):s?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent},"")}(t,a);if(!s||!t.hasAttribute("begin"))return null;const r=ci(t.getAttribute("begin"),n),i=ci(t.getAttribute("dur"),n);let d=ci(t.getAttribute("end"),n);if(null===r)throw di(t);if(null===d){if(null===i)throw di(t);d=r+i}const c=new Yr(r-e,d-e,s);c.id=ei(c.startTime,c.endTime,c.text);const u=function(t,e,s){const r="http://www.w3.org/ns/ttml#styling";let i=null;const n=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;n&&s.hasOwnProperty(n)&&(i=s[n]);return["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((s,n)=>{const a=hi(e,r,n)||hi(t,r,n)||hi(i,r,n);return a&&(s[n]=a),s},{})}(h[t.getAttribute("region")],l[t.getAttribute("style")],l),{textAlign:f}=u;if(f){const t=ni[f];t&&(c.lineAlign=t),c.align=f}return o(c,u),c}).filter(t=>null!==t)}(t,a)))}catch(t){r(t)}}function oi(t,e,s){const r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(s)):[]}function li(t){return t.reduce((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t},{})}function hi(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function di(t){return new Error("Could not parse ttml timestamp "+t)}function ci(t,e){if(!t)return null;let s=Wr(t);return null===s&&(ri.test(t)?s=function(t,e){const s=ri.exec(t),r=(0|s[4])+(0|s[5])/e.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+r/e.frameRate}(t,e):ii.test(t)&&(s=function(t,e){const s=ii.exec(t),r=Number(s[1]);switch(s[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}(t,e))),s}function ui(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function fi(t,e){return!!t&&t.kind===ui(e)&&_r(e,t)}class CapLevelController{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(c.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(c.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(c.MANIFEST_PARSED,this.onManifestParsed,this),t.on(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(c.BUFFER_CODECS,this.onBufferCodecs,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(c.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(c.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(c.MANIFEST_PARSED,this.onManifestParsed,this),t.off(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(c.BUFFER_CODECS,this.onBufferCodecs,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const s=this.hls.levels[e.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.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 s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&l(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,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&v.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,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 s=e.filter((e,s)=>this.isLevelAllowed(e)&&s<=t);return this.clientRect=null,CapLevelController.getMaxLevelByMediaSize(s,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 s=t.getBoundingClientRect();e.width=s.width,e.height=s.height,e.width||e.height||(e.width=s.right-s.left||t.width||0,e.height=s.bottom-s.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,s){if(null==t||!t.length)return-1;let r=t.length-1;const i=Math.max(e,s);for(let e=0;e<t.length;e+=1){const s=t[e];if((s.width>=i||s.height>=i)&&(n=s,!(a=t[e+1])||n.width!==a.width||n.height!==a.height)){r=e;break}}var n,a;return r}}class EMEController{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=EMEController.CDMCleanupPromise?[EMEController.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=v.debug.bind(v,"[eme]"),this.log=v.log.bind(v,"[eme]"),this.warn=v.warn.bind(v,"[eme]"),this.error=v.error.bind(v,"[eme]"),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(c.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(c.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(c.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(c.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(c.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(c.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(c.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,r=e[t];if(r)return r.licenseUrl;if(t===w.WIDEVINE&&s)return s;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,s=e[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,s=(t,e,s)=>!!t&&s.indexOf(t)===e,r=e.map(t=>t.audioCodec).filter(s),i=e.map(t=>t.videoCodec).filter(s);return r.length+i.length===0&&i.push("avc1.42e01e"),new Promise((e,s)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,r,i).then(t=>e({keySystem:a,mediaKeys:t})).catch(e=>{t.length?n(t):s(e instanceof EMEKeyError?e:new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))})};n(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let t="Configured requestMediaKeySystemAccess is not a function "+s;return null===U&&"http:"===self.location.protocol&&(t="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(t))}return s(t,e)}getMediaKeysPromise(t,e,s){const r=function(t,e,s,r){let i;switch(t){case w.FAIRPLAY:i=["cenc","sinf"];break;case w.WIDEVINE:case w.PLAYREADY:i=["cenc"];break;case w.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+t)}return function(t,e,s,r){return[{initDataTypes:t,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs="${t}"`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:s.map(t=>({contentType:`video/mp4; codecs="${t}"`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}(i,e,s,r)}(t,e,s,this.config.drmSystemOptions),i=this.keySystemAccessPromises[t];let n=null==i?void 0:i.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(r)}`),n=this.requestMediaKeySystemAccess(t,r);const e=this.keySystemAccessPromises[t]={keySystemAccess:n};return n.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),n.then(s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const r=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),e.mediaKeys=s.createMediaKeys().then(e=>(this.log(`Media-keys created for "${t}"`),r.then(s=>s?this.setMediaKeysServerCertificate(e,t,s):e))),e.mediaKeys.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),e.mediaKeys})}return n.then(()=>i.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:s}){this.log(`Creating key-system session "${e}" keyId: ${it(t.keyId||[])}`);const r=s.createSession(),i={decryptdata:t,keySystem:e,mediaKeys:s,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const s=this.createMediaKeySessionContext(t),r=this.getKeyIdString(e),i="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(s,i,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return it(t.keyId)}updateKeySession(t,e){var s;const r=t.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${it((null==(s=t.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${e?e.byteLength:e})`),r.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise((e,s)=>{const r=N(this.config),i=t.map(x).filter(t=>!!t&&-1!==r.indexOf(t));return this.getKeySystemSelectionPromise(i).then(({keySystem:t})=>{const r=O(t);r?e(r):s(new Error(`Unable to find format for key-system "${t}"`))}).catch(s)})}loadKey(t){const e=t.keyInfo.decryptdata,s=this.getKeyIdString(e),r=`(keyId: ${s} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log("Starting session for key "+r);let i=this.keyIdToKeySessionPromise[s];return i||(i=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(e).then(({keySystem:s,mediaKeys:i})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${r}`),this.attemptSetMediaKeys(s,i).then(()=>{this.throwIfDestroyed();const t=this.createMediaKeySessionContext({keySystem:s,mediaKeys:i,decryptdata:e});return this.generateRequestWithPreferredKeySession(t,"cenc",e.pssh,"playlist-key")}))),i.catch(t=>this.handleError(t))),i}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof EMEKeyError?this.hls.trigger(c.ERROR,t.data):this.hls.trigger(c.ERROR,{type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[e];if(!s){const e=x(t.keyFormat),s=e?[e]:N(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=N(this.config)),0===t.length)throw new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+JSON.stringify({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:s}=t;if(this.debug(`"${t.type}" event: init data type: "${e}"`),null===s)return;let r,i;if("sinf"===e&&this.config.drmSystems[w.FAIRPLAY]){const t=lt(new Uint8Array(s));try{const e=b(JSON.parse(t).sinf),s=St(new Uint8Array(e));if(!s)return;r=s.subarray(8,24),i=w.FAIRPLAY}catch(t){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const t=function(t){if(!(t instanceof ArrayBuffer)||t.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},s=new DataView(t),r=s.getUint32(0);if(t.byteLength!==r&&r>44)return null;if(1886614376!==s.getUint32(4))return null;if(e.version=s.getUint32(8)>>>24,e.version>1)return null;e.systemId=it(new Uint8Array(t,12,16));const i=s.getUint32(28);if(0===e.version){if(r-32<i)return null;e.data=new Uint8Array(t,32,i)}else if(1===e.version){e.kids=[];for(let s=0;s<i;s++)e.kids.push(new Uint8Array(t,32+16*s,16))}return e}(s);if(null===t)return;0===t.version&&t.systemId===F&&t.data&&(r=t.data.subarray(8,24)),i=function(t){if(t===F)return w.WIDEVINE}(t.systemId)}if(!i||!r)return;const n=it(r),{keyIdToKeySessionPromise:a,mediaKeySessions:o}=this;let l=a[n];for(let t=0;t<o.length;t++){const i=o[t],h=i.decryptdata;if(h.pssh||!h.keyId)continue;const d=it(h.keyId);if(n===d||-1!==h.uri.replace(/-/g,"").indexOf(n)){l=a[d],delete a[d],h.pssh=new Uint8Array(s),h.keyId=r,l=a[n]=l.then(()=>this.generateRequestWithPreferredKeySession(i,e,s,"encrypted-event-key-match"));break}}l||(l=a[n]=this.getKeySystemSelectionPromise([i]).then(({keySystem:t,mediaKeys:i})=>{var a;this.throwIfDestroyed();const o=new LevelKey("ISO-23001-7",n,null!=(a=O(t))?a:"");return o.pssh=new Uint8Array(s),o.keyId=r,this.attemptSetMediaKeys(t,i).then(()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:o,keySystem:t,mediaKeys:i});return this.generateRequestWithPreferredKeySession(r,e,s,"encrypted-event-no-match")})})),l.catch(t=>this.handleError(t))}_onWaitingForKey(t){this.log(`"${t.type}" event`)}attemptSetMediaKeys(t,e){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const r=Promise.all(s).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${t}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===s.indexOf(t))})}generateRequestWithPreferredKeySession(t,e,s,r){var i,n;const a=null==(i=this.config.drmSystems)||null==(n=i[t.keySystem])?void 0:n.generateRequest;if(a)try{const r=a.call(this.hls,e,s,t);if(!r)throw new Error("Invalid response from configured generateRequest filter");e=r.initDataType,s=t.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}if(null===s)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const l=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${e} length: ${s?s.byteLength:null})`);const h=new wr,d=t._onmessage=e=>{const s=t.mediaKeysSession;if(!s)return void h.emit("error",new Error("invalid state"));const{messageType:r,message:i}=e;this.log(`"${r}" message event for session "${s.sessionId}" message size: ${i.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(t,i).catch(t=>{this.handleError(t),h.emit("error",t)}):"license-release"===r?t.keySystem===w.FAIRPLAY&&(this.updateKeySession(t,D("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${r}"`)},c=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const s=t.keyStatus;h.emit("keyStatus",s),"expired"===s&&(this.warn(`${t.keySystem} expired for key ${l}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",d),t.mediaKeysSession.addEventListener("keystatuseschange",c);const g=new Promise((t,e)=>{h.on("error",e),h.on("keyStatus",s=>{s.startsWith("usable")?t():"output-restricted"===s?e(new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?e(new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${s}"`)):"expired"===s?e(new Error("key expired while generating request")):this.warn(`unhandled key status change "${s}"`)})});return t.mediaKeysSession.generateRequest(e,s).then(()=>{var e;this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l}`)}).catch(t=>{throw new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},"Error generating key-session request: "+t)}).then(()=>g).catch(e=>{throw h.removeAllListeners(),this.removeSession(t),e}).then(()=>(h.removeAllListeners(),t))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach((e,s)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${it("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${it(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e})}fetchServerCertificate(t){const e=this.config,s=new(0,e.loader)(e),r=this.getServerCertificateUrl(t);return r?(this.log(`Fetching server certificate for "${t}"`),new Promise((n,a)=>{const o={responseType:"arraybuffer",url:r},l=e.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,s,r)=>{n(t.data)},onError:(e,s,n,l)=>{a(new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:i({url:o.url,data:void 0},e)},`"${t}" certificate request failed (${r}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,i)=>{a(new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:{url:o.url,data:void 0}},`"${t}" certificate request timed out (${r})`))},onAbort:(t,e,s)=>{a(new Error("aborted"))}};s.load(o,h,d)})):Promise.resolve()}setMediaKeysServerCertificate(t,e,s){return new Promise((r,i)=>{t.setServerCertificate(s).then(i=>{this.log(`setServerCertificate ${i?"success":"not supported by CDM"} (${null==s?void 0:s.byteLength}) on "${e}"`),r(t)}).catch(t=>{i(new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(e=>this.updateKeySession(t,new Uint8Array(e)).catch(t=>{throw new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))}unpackPlayReadyKeyMessage(t,e){const s=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const r=(new DOMParser).parseFromString(s,"application/xml"),i=r.querySelectorAll("HttpHeader");if(i.length>0){let e;for(let s=0,r=i.length;s<r;s++){var n,a;e=i[s];const r=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;r&&o&&t.setRequestHeader(r,o)}}const o=r.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return D(atob(l))}setupLicenseXHR(t,e,s,r){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return i.call(this.hls,t,e,s,r)}).catch(n=>{if(!s.decryptdata)throw n;return t.open("POST",e,!0),i.call(this.hls,t,e,s,r)}).then(s=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:s||r}}):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,e){const s=this.config.keyLoadPolicy.default;return new Promise((r,i)=>{const n=this.getLicenseServerUrl(t.keySystem);this.log("Sending license request to URL: "+n);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return i(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log("License received "+(e instanceof ArrayBuffer?e.byteLength:e));const s=this.config.licenseResponseCallback;if(s)try{e=s.call(this.hls,a,n,t)}catch(t){this.error(t)}r(e)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)i(new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(t,e).then(r,i)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then(({xhr:e,licenseChallenge:s})=>{t.keySystem==w.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(e,s)),e.send(s)})})}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},LevelKey.clearKeyUriToKeyIdMap();const s=e.length;EMEController.CDMCleanupPromise=Promise.all(e.map(t=>this.removeSession(t)).concat(null==t?void 0:t.setMediaKeys(null).catch(t=>{this.log("Could not clear media keys: "+t)}))).then(()=>{s&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)}).catch(t=>{this.log("Could not close sessions and clear media keys: "+t)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t),[]);this.log("Selecting key-system from session-keys "+t.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:s}=t;if(e){this.log("Remove licenses and keys and close session "+e.sessionId),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(t);return r>-1&&this.mediaKeySessions.splice(r,1),e.remove().catch(t=>{this.log("Could not remove session: "+t)}).then(()=>e.close()).catch(t=>{this.log("Could not close session: "+t)})}}}EMEController.CDMCleanupPromise=void 0;class EMEKeyError extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}var gi,mi,pi;!function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"}(gi||(gi={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}(mi||(mi={})),function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"}(pi||(pi={}));const yi={[pi.OBJECT]:["br","d","ot","tb"],[pi.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[pi.SESSION]:["cid","pr","sf","sid","st","v"],[pi.STATUS]:["bs","rtp"]};class SfItem{constructor(t,e){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map(t=>t instanceof SfItem?t:new SfItem(t))),this.value=t,this.params=e}}class SfToken{constructor(t){this.description=void 0,this.description=t}}function vi(t,e,s,r){return new Error(`failed to ${t} "${i=e,Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":"object"==typeof i?JSON.stringify(i):String(i)}" as ${s}`,{cause:r});var i}const Ei=/[\x00-\x1f\x7f]+/;function Ti(t,e,s){return vi("serialize",t,e,s)}function Si(t){if(!1===ArrayBuffer.isView(t))throw Ti(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function Li(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw Ti(t,"Integer");return t.toString()}function Ai(t){const e=function t(e,s){if(e<0)return-t(-e,s);const r=Math.pow(10,s);if(Math.abs(e*r%1-.5)<Number.EPSILON){const t=Math.floor(e*r);return(t%2==0?t:t+1)/r}return Math.round(e*r)/r}(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ti(t,"Decimal");const s=e.toString();return s.includes(".")?s:s+".0"}function Ri(t){const e=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw Ti(e,"Token");return e}function bi(t){switch(typeof t){case"number":if(!l(t))throw Ti(t,"Bare Item");return Number.isInteger(t)?Li(t):Ai(t);case"string":return function(t){if(Ei.test(t))throw Ti(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return Ri(t);case"boolean":return function(t){if("boolean"!=typeof t)throw Ti(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return"@"+Li(t.getTime()/1e3)}(t);if(t instanceof Uint8Array)return Si(t);if(t instanceof SfToken)return Ri(t);default:throw Ti(t,"Bare Item")}}function ki(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw Ti(t,"Key");return t}function Di(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?";"+ki(t):`;${ki(t)}=${bi(e)}`).join("")}function Ci(t){return t instanceof SfItem?`${bi(t.value)}${Di(t.params)}`:bi(t)}function wi(t,e={whitespace:!0}){if("object"!=typeof t)throw Ti(t,"Dict");const s=t instanceof Map?t.entries():Object.entries(t),r=null!=e&&e.whitespace?" ":"";return Array.from(s).map(([t,e])=>{e instanceof SfItem==!1&&(e=new SfItem(e));let s=ki(t);var r;return!0===e.value?s+=Di(e.params):(s+="=",Array.isArray(e.value)?s+=`(${(r=e).value.map(Ci).join(" ")})${Di(r.params)}`:s+=Ci(e)),s}).join(","+r)}const Pi=t=>Math.round(t),Ii=t=>100*Pi(t/100),_i={br:Pi,d:Pi,bl:Ii,dl:Ii,mtp:Ii,nor:(t,e)=>(null!=e&&e.baseUrl&&(t=function(t,e){const s=new URL(t),r=new URL(e);if(s.origin!==r.origin)return t;const i=s.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;i[0]===n[0];)i.shift(),n.shift();for(;n.length;)n.shift(),i.unshift("..");return i.join("/")}(t,e.baseUrl)),encodeURIComponent(t)),rtp:Ii,tb:Pi};function Mi(t,e){const s={};if(null==t||"object"!=typeof t)return s;const r=Object.keys(t).sort(),i=o({},_i,null==e?void 0:e.formatters),n=null==e?void 0:e.filter;return r.forEach(r=>{if(null!=n&&n(r))return;let a=t[r];const o=i[r];o&&(a=o(a,e)),"v"===r&&1===a||"pr"==r&&1===a||(t=>"number"==typeof t?l(t):null!=t&&""!==t&&!1!==t)(a)&&((t=>"ot"===t||"sf"===t||"st"===t)(r)&&"string"==typeof a&&(a=new SfToken(a)),s[r]=a)}),s}function xi(t,e={}){return t?function(t,e){return wi(t,e)}(Mi(t,e),o({whitespace:!1},e)):""}function Fi(t,e,s){return o(t,function(t,e={}){if(!t)return{};const s=Object.entries(t),r=Object.entries(yi).concat(Object.entries((null==e?void 0:e.customHeaderMap)||{})),i=s.reduce((t,e)=>{var s;const[i,n]=e,a=(null==(s=r.find(t=>t[1].includes(i)))?void 0:s[0])||pi.REQUEST;return null!=t[a]||(t[a]={}),t[a][i]=n,t},{});return Object.entries(i).reduce((t,[s,r])=>(t[s]=xi(r,e),t),{})}(e,s))}const Oi=/CMCD=[^&#]+/;function Ni(t,e,s){const r=function(t,e={}){if(!t)return"";const s=xi(t,e);return"CMCD="+encodeURIComponent(s)}(e,s);if(!r)return t;if(Oi.test(t))return t.replace(Oi,r);const i=t.includes("?")?"&":"?";return`${t}${i}${r}`}function Ui(t,e,s,r){t&&Object.keys(e).forEach(i=>{const n=t.filter(t=>t.groupId===i).map(t=>{const n=o({},t);return n.details=void 0,n.attrs=new AttrList(n.attrs),n.url=n.attrs.URI=Bi(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=e[i],n.attrs["PATHWAY-ID"]=r,n});t.push(...n)})}function Bi(t,e,s,r){const{HOST:i,PARAMS:n,[s]:a}=r;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 $i=/^age:\s*[\d.]+\s*$/im;class XhrLoader{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 LoadStats,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,s){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=s,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!this.stats.aborted)return i(s,e.url)}).catch(t=>(s.open("GET",e.url,!0),i(s,e.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(s,e,t)}).catch(t=>{this.callbacks.onError({code:s.status,text:t.message},e,s,r)}):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const r=e.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:n}=s.loadPolicy;if(r)for(const e in r)t.setRequestHeader(e,r[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),s.timeout=i&&l(i)?i:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:s}=this;if(!t||!e)return;const r=e.readyState,i=this.config;if(!s.aborted&&r>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.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-(s.loading.first-s.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const r=e.status,n="text"!==e.responseType;if(r>=200&&r<300&&(n&&e.response||null!==e.responseText)){s.loading.end=Math.max(self.performance.now(),s.loading.first);const i=n?e.response:e.responseText,a="arraybuffer"===e.responseType?i.byteLength:i.length;if(s.loaded=s.total=a,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(s,t,i,e),!this.callbacks)return;const l={url:e.responseURL,data:i,code:r};this.callbacks.onSuccess(l,s,t,e)}else{const n=i.loadPolicy.errorRetry;Ye(n,s.retry,!1,{url:t.url,data:void 0,code:r})?this.retry(n):(v.error(`${r} while loading ${t.url}`),this.callbacks.onError({code:r,text:e.statusText},t,e,s))}}}loadtimeout(){var t;const e=null==(t=this.config)?void 0:t.loadPolicy.timeoutRetry;if(Ye(e,this.stats.retry,!0))this.retry(e);else{var s;v.warn("timeout while loading "+(null==(s=this.context)?void 0:s.url));const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:s}=this;this.retryDelay=He(t,s.retry),s.retry++,v.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${s.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&&$i.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}}const Gi=/(\d+)-(\d+)\/(\d+)/;class FetchLoader{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||Ki,this.controller=new self.AbortController,this.stats=new LoadStats}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,s){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const i=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(o({},t.headers))};t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return s}(t,this.controller.signal),n=s.onProgress,a="arraybuffer"===t.responseType,h=a?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:c}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=s,this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),e.timeout=d&&l(d)?d:c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(r,t,this.response)},e.timeout),self.fetch(this.request).then(i=>{this.response=this.loader=i;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(r,t,this.response)},c-(o-r.loading.start)),!i.ok){const{status:t,statusText:e}=i;throw new FetchError(e||"fetch, bad network response",t,i)}return r.loading.first=o,r.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Gi.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(l(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(i.headers)||r.total,n&&l(e.highWaterMark)?this.loadProgressively(i,r,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),r.loading.end=Math.max(self.performance.now(),r.loading.first);const o=i[h];o&&(r.loaded=r.total=o);const d={url:a.url,data:i,code:a.status};n&&!l(e.highWaterMark)&&n(r,t,i,a),s.onSuccess(d,r,t,a)}).catch(e=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const i=e&&e.code||0,n=e?e.message:null;s.onError({code:i,text:n},t,e?e.details:null,r)})}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,s,r=0,i){const n=new ChunkCache,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&i(e,s,n.flush(),t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h<r||n.dataLength?(n.push(l),n.dataLength>=r&&i(e,s,n.flush(),t)):i(e,s,l,t),o()}).catch(()=>Promise.reject());return o()}}function Ki(t,e){return new self.Request(t.url,e)}class FetchError extends Error{constructor(t,e,s){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=s}}const Hi=/\s/,Vi={newCue(t,e,s,r){const i=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<r.rows.length;u++)if(n=r.rows[u],o=!0,l=0,h="",!n.isEmpty()){var c;for(let t=0;t<n.chars.length;t++)Hi.test(n.chars[t].uchar)&&o?l++:(h+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===s&&(s+=1e-4),l>=16?l--:l++;const r=Qr(h.trim()),f=ei(e,s,r);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new d(e,s,r),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),i.push(a))}return t&&i.length&&(i.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),i.forEach(e=>me(t,e))),i}},Yi=i(i({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:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class AbrController{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:s}=this,{autoLevelEnabled:r,media:i}=s;if(!t||!i)return;const n=performance.now(),a=e?e.stats:t.stats,o=e?e.duration:t.duration,h=n-a.loading.start,d=s.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||t.level<=d)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||i.paused||!i.playbackRate||!i.readyState)return;const u=s.mainForwardBufferInfo;if(null===u)return;const f=this.bwEstimator.getEstimateTTFB(),g=Math.abs(i.playbackRate);if(h<=Math.max(f,o/(2*g)*1e3))return;const m=u.len/g,p=a.loading.first?a.loading.first-a.loading.start:-1,y=a.loaded&&p>-1,E=this.getBwEstimate(),T=s.levels,S=T[t.level],L=a.total||Math.max(a.loaded,Math.round(o*S.averageBitrate/8));let A=y?h-p:h;A<1&&y&&(A=Math.min(h,8*a.loaded/E));const R=y?1e3*a.loaded/A:0,b=R?(L-a.loaded)/R:8*L/E+f/1e3;if(b<=m)return;const k=R?8*R:E;let D,C=Number.POSITIVE_INFINITY;for(D=t.level-1;D>d;D--){const t=T[D].maxBitrate;if(C=this.getTimeToLoadFrag(f/1e3,k,o*t,!T[D].details),C<m)break}if(C>=b)return;if(C>10*o)return;s.nextLoadLevel=s.nextAutoLevel=D,y?this.bwEstimator.sample(h-Math.min(f,p),a.loaded):this.bwEstimator.sampleTTFB(h);const w=T[D].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>w&&this.resetEstimator(w),this.clearTimer(),v.warn(`[abr] Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} is loading too slowly;\n Time to underbuffer: ${m.toFixed(3)} s\n Estimated load time for current fragment: ${b.toFixed(3)} s\n Estimated load time for down switch fragment: ${C.toFixed(3)} s\n TTFB estimate: ${0|p} ms\n Current BW estimate: ${l(E)?0|E:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${D} @ ${0|w} bps`),s.trigger(c.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:a})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(v.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 EwmaBandWidthEstimator(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.FRAG_LOADING,this.onFragLoading,this),t.on(c.FRAG_LOADED,this.onFragLoaded,this),t.on(c.FRAG_BUFFERED,this.onFragBuffered,this),t.on(c.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(c.LEVEL_LOADED,this.onLevelLoaded,this),t.on(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(c.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(c.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.FRAG_LOADING,this.onFragLoading,this),t.off(c.FRAG_LOADED,this.onFragLoaded,this),t.off(c.FRAG_BUFFERED,this.onFragBuffered,this),t.off(c.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(c.LEVEL_LOADED,this.onLevelLoaded,this),t.off(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(c.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(c.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 s=e.frag;if(!this.ignoreFragment(s)){var r;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(r=e.part)?r: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 f.BUFFER_ADD_CODEC_ERROR:case f.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case f.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:s,partCurrent:r}=this;if(t&&s&&t.sn===s.sn&&t.level===s.level){const e=performance.now(),s=r?r.stats:t.stats,i=e-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(i-Math.min(t,n),s.loaded)}else this.bwEstimator.sampleTTFB(i)}break}}}getTimeToLoadFrag(t,e,s,r){return t+s/e+(r?this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{loading:r}=e.stats,i=r.end-r.start;l(i)&&(this.lastLevelLoadSec=i/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}onFragLoaded(t,{frag:e,part:s}){const r=s?s.stats:e.stats;if(e.type===he&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=s?s.duration:e.duration,i=this.hls.levels[e.level],n=(i.loaded?i.loaded.bytes:0)+r.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:r,frag:e,part:s,id:e.type};this.onFragBuffered(c.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:s,part:r}=e,i=null!=r&&r.stats.loaded?r.stats:s.stats;if(i.aborted)return;if(this.ignoreFragment(s))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(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==he||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,s=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,i=this.findBestLevel(s,e,t,0,r,1,1);if(i>-1)return i;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return v.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(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const r=e&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,r)&&e[t].loadError<=e[r].loadError)return t}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this,{maxAutoLevel:r,config:i,minAutoLevel:n}=s,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=i.abrBandWidthFactor,d=i.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,r,l,0,h,d);if(t>=0)return t}let c=a?Math.min(a,i.maxStarvationDelay):i.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,i.maxLoadingDelay):i.maxLoadingDelay)-t,v.info(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,r,l,c,h,d);if(v.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`),u>-1)return u;const f=s.levels[n],g=s.levels[s.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:s.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const s=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,r=t.mainForwardBufferInfo;return(r?r.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,s,r,i,n,a){var o;const h=r+i,d=this.lastLoadedFragLevel,c=-1===d?this.hls.firstLevel:d,{fragCurrent:u,partCurrent:f}=this,{levels:g,allAudioTracks:m,loadLevel:p,config:y}=this.hls;if(1===g.length)return 0;const E=g[c],T=!(null==E||null==(o=E.details)||!o.live),S=-1===p||-1===d;let L,A="SDR",R=(null==E?void 0:E.frameRate)||0;const{audioPreference:b,videoPreference:k}=y,D=this.audioTracksByGroup||(this.audioTracksByGroup=function(t){return t.reduce((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(e);const r=e.channels||"2";return s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(m));if(S){if(-1!==this.firstSelection)return this.firstSelection;const r=function(t,e,s,r,i){const n=Object.keys(t),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,h=a&&2===parseInt(a);let d=!0,c=!1,u=1/0,f=1/0,g=1/0,m=0,p=[];const{preferHDR:y,allowedVideoRanges:v}=os(e,i);for(let e=n.length;e--;){const s=t[n[e]];d=s.channels[2]>0,u=Math.min(u,s.minHeight),f=Math.min(f,s.minFramerate),g=Math.min(g,s.minBitrate);const r=v.filter(t=>s.videoRanges[t]>0);r.length>0&&(c=!0,p=r)}u=l(u)?u:0,f=l(f)?f:0;const E=Math.max(1080,u),T=Math.max(30,f);return g=l(g)?g:s,s=Math.max(g,s),c||(e=void 0,p=[]),{codecSet:n.reduce((e,r)=>{const i=t[r];if(r===e)return e;if(i.minBitrate>s)return ls(r,`min bitrate of ${i.minBitrate} > current estimate of ${s}`),e;if(!i.hasDefaultAudio)return ls(r,"no renditions with default or auto-select sound found"),e;if(o&&r.indexOf(o.substring(0,4))%5!=0)return ls(r,`audio codec preference "${o}" not found`),e;if(a&&!h){if(!i.channels[a])return ls(r,`no renditions with ${a} channel sound found (channels options: ${Object.keys(i.channels)})`),e}else if((!o||h)&&d&&0===i.channels[2])return ls(r,"no renditions with stereo sound found"),e;return i.minHeight>E?(ls(r,`min resolution of ${i.minHeight} > maximum of ${E}`),e):i.minFramerate>T?(ls(r,`min framerate of ${i.minFramerate} > maximum of ${T}`),e):p.some(t=>i.videoRanges[t]>0)?i.maxScore<m?(ls(r,`max score of ${i.maxScore} < selected max of ${m}`),e):e&&(Kt(r)>=Kt(e)||i.fragmentError>t[e].fragmentError)?e:(m=i.maxScore,r):(ls(r,`no variants with VIDEO-RANGE of ${JSON.stringify(p)} found`),e)},void 0),videoRanges:p,preferHDR:y,minFramerate:f,minBitrate:g}}(this.codecTiers||(this.codecTiers=function(t,e,s,r){return t.slice(s,r+1).reduce((t,s)=>{if(!s.codecSet)return t;const r=s.audioGroups;let i=t[s.codecSet];i||(t[s.codecSet]=i={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),i.minBitrate=Math.min(i.minBitrate,s.bitrate);const n=Math.min(s.height,s.width);return i.minHeight=Math.min(i.minHeight,n),i.minFramerate=Math.min(i.minFramerate,s.frameRate),i.maxScore=Math.max(i.maxScore,s.score),i.fragmentError+=s.fragmentError,i.videoRanges[s.videoRange]=(i.videoRanges[s.videoRange]||0)+1,r&&r.forEach(t=>{if(!t)return;const s=e.groups[t];s&&(i.hasDefaultAudio=i.hasDefaultAudio||e.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(s.channels).forEach(t=>{i.channels[t]=(i.channels[t]||0)+s.channels[t]}))}),t},{})}(g,D,e,s)),A,t,b,k),{codecSet:i,videoRanges:n,minFramerate:a,minBitrate:o,preferHDR:h}=r;L=i,A=h?n[n.length-1]:n[0],R=a,t=Math.max(t,o),v.log("[abr] picked start tier "+JSON.stringify(r))}else L=null==E?void 0:E.codecSet,A=null==E?void 0:E.videoRange;const C=f?f.duration:u?u.duration:0,w=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let o=s;o>=e;o--){var I;const e=g[o],u=o>c;if(!e)continue;if(y.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&ns(e,D,A,R,t,b)?(e.supportedPromise=as(e,D,s),e.supportedPromise.then(t=>{if(!this.hls)return;e.supportedResult=t;const s=this.hls.levels,r=s.indexOf(e);t.error?v.warn(`[abr] MediaCapabilities decodingInfo error: "${t.error}" for level ${r} ${JSON.stringify(t)}`):t.supported||(v.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${r} ${JSON.stringify(t)}`),r>-1&&s.length>1&&(v.log("[abr] Removing unsupported level "+r),this.hls.removeLevel(r)))})):e.supportedResult=rs}if(L&&e.codecSet!==L||A&&e.videoRange!==A||u&&R>e.frameRate||!u&&R>0&&R<e.frameRate||e.supportedResult&&(null==(I=e.supportedResult.decodingInfoResults)||!I[0].smooth)){P.push(o);continue}const m=e.details,k=(f?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||C;let _;_=u?a*t:n*t;const M=C&&r>=2*C&&0===i?g[o].averageBitrate:g[o].maxBitrate,x=this.getTimeToLoadFrag(w,_,M*k,void 0===m);if(_>=M&&(o===d||0===e.loadError&&0===e.fragmentError)&&(x<=w||!l(x)||T&&!this.bitrateTestDelay||x<h)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(P.length&&v.trace(`[abr] Skipped level(s) ${P.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[P[0]].codecs}" ${g[P[0]].videoRange}; not compatible with "${E.codecs}" ${A}`),v.info(`[abr] switch candidate:${c}->${o} adjustedbw(${Math.round(_)})-bitrate=${Math.round(_-M)} ttfb:${w.toFixed(1)} avgDuration:${k.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${S} codecSet:${L} videoRange:${A} hls.loadLevel:${p}`)),S&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:s}=this.hls,r=Math.min(Math.max(t,s),e);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}},bufferController:class BufferController{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(c.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&&v.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t;const e="[buffer-controller]";var s;this.appendSource=(s=Ot(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.log=v.log.bind(v,e),this.warn=v.warn.bind(v,e),this.error=v.error.bind(v,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(c.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_PARSED,this.onManifestParsed,this),t.on(c.BUFFER_RESET,this.onBufferReset,this),t.on(c.BUFFER_APPENDING,this.onBufferAppending,this),t.on(c.BUFFER_CODECS,this.onBufferCodecs,this),t.on(c.BUFFER_EOS,this.onBufferEos,this),t.on(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(c.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(c.FRAG_PARSED,this.onFragParsed,this),t.on(c.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(c.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_PARSED,this.onManifestParsed,this),t.off(c.BUFFER_RESET,this.onBufferReset,this),t.off(c.BUFFER_APPENDING,this.onBufferAppending,this),t.off(c.BUFFER_CODECS,this.onBufferCodecs,this),t.off(c.BUFFER_EOS,this.onBufferEos,this),t.off(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(c.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(c.FRAG_PARSED,this.onFragParsed,this),t.off(c.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new BufferOperationQueue(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 s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")}onMediaAttaching(t,e){const s=this.media=e.media,r=Ot(this.appendSource);if(s&&r){var i;const t=this.mediaSource=new r;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{s.removeAttribute("src");const r=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||r&&t instanceof r,xr(s),function(t,e){const s=self.document.createElement("source");s.type="video/mp4",s.src=e,t.appendChild(s)}(s,e),s.load()}catch(t){s.src=e}else s.src=e;s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:s}=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),s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(t.removeAttribute("src"),this.appendSource&&xr(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(c.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(t=>{this.resetBuffer(t)}),this._initSourceBuffer()}resetBuffer(t){const e=this.sourceBuffer[t];try{var s;if(e)this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e)}catch(e){this.warn("onBufferReset "+t,e)}}onBufferCodecs(t,e){const s=this.getSourceBufferTypes().length,r=Object.keys(e);if(r.forEach(t=>{if(s){const s=this.tracks[t];if(s&&"function"==typeof s.buffer.changeType){var r;const{id:i,codec:n,levelCodec:a,container:o,metadata:l}=e[t],h=Wt(s.codec,s.levelCodec),d=null==h?void 0:h.replace(Mr,"$1");let c=Wt(n,a);const u=null==(r=c)?void 0:r.replace(Mr,"$1");if(c&&d!==u){"audio"===t.slice(0,5)&&(c=Yt(c,this.appendSource));const e=`${o};codecs=${c}`;this.appendChangeType(t,e),this.log(`switching codec ${h} to ${c}`),this.tracks[t]={buffer:s.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:i}}}}else this.pendingTracks[t]=e[t]}),s)return;const i=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==i&&(this.log(`${i} bufferCodec event(s) expected ${r.join(",")}`),this.bufferCodecEventsExpected=i),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(t,e){const{operationQueue:s}=this,r={execute:()=>{const r=this.sourceBuffer[t];r&&(this.log(`changing ${t} sourceBuffer type to ${e}`),r.changeType(e)),s.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};s.append(r,t,!!this.pendingTracks[t])}onBufferAppending(t,e){const{hls:s,operationQueue:r,tracks:i}=this,{data:n,type:a,frag:o,part:l,chunkMeta:h}=e,d=h.buffering[a],g=self.performance.now();d.start=g;const m=o.stats.buffering,p=l?l.stats.buffering:null;0===m.start&&(m.start=g),p&&0===p.start&&(p.start=g);const y=i.audio;let v=!1;"audio"===a&&"audio/mpeg"===(null==y?void 0:y.container)&&(v=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const E=o.start,T={execute:()=>{if(d.executeStart=self.performance.now(),v){const t=this.sourceBuffer[a];if(t){const e=E-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${E} (delta: ${e}) sn: ${o.sn})`),t.timestampOffset=E)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();d.executeEnd=d.end=t,0===m.first&&(m.first=t),p&&0===p.first&&(p.first=t);const{sourceBuffer:e}=this,s={};for(const t in e)s[t]=BufferHelper.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(c.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:s})},onError:t=>{const e={type:u.MEDIA_ERROR,parent:o.type,details:f.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:h,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)e.details=f.BUFFER_FULL_ERROR;else{const t=++this.appendErrors[a];e.details=f.BUFFER_APPEND_ERROR,this.warn(`Failed ${t}/${s.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),t>=s.config.appendErrorMaxRetry&&(e.fatal=!0)}s.trigger(c.ERROR,e)}};r.append(T,a,!!this.pendingTracks[a])}onBufferFlushing(t,e){const{operationQueue:s}=this,r=t=>({execute:this.removeExecutor.bind(this,t,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(c.BUFFER_FLUSHED,{type:t})},onError:e=>{this.warn(`Failed to remove from ${t} SourceBuffer`,e)}});e.type?s.append(r(e.type),e.type):this.getSourceBufferTypes().forEach(t=>{s.append(r(t),t)})}onFragParsed(t,e){const{frag:s,part:r}=e,i=[],n=r?r.elementaryStreams:s.elementaryStreams;n[R]?i.push("audiovideo"):(n[L]&&i.push("audio"),n[A]&&i.push("video"));0===i.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(()=>{const t=self.performance.now();s.stats.buffering.end=t,r&&(r.stats.buffering.end=t);const e=r?r.stats:s.stats;this.hls.trigger(c.FRAG_BUFFERED,{frag:s,part:r,stats:e,id:s.type})},i)}onFragChanged(t,e){this.trimBuffers()}onBufferEos(t,e){this.getSourceBufferTypes().reduce((t,s)=>{const r=this.sourceBuffer[s];return!r||e.type&&e.type!==s||(r.ending=!0,r.ended||(r.ended=!0,this.log(s+" sourceBuffer now EOS"))),t&&!(r&&!r.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:s}=this;if(!s||null===e)return;if(!this.getSourceBufferTypes().length)return;const r=t.config,i=s.currentTime,n=e.levelTargetDuration,a=e.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(l(a)&&a>0){const t=Math.max(a,n),e=Math.floor(i/n)*n-t;this.flushBackBuffer(i,n,e)}if(l(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const t=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),e=Math.max(t,n),s=Math.floor(i/n)*n+e;this.flushFrontBuffer(i,n,s)}}flushBackBuffer(t,e,s){const{details:r,sourceBuffer:i}=this;this.getSourceBufferTypes().forEach(n=>{const a=i[n];if(a){const i=BufferHelper.getBuffered(a);if(i.length>0&&s>i.start(0)){if(this.hls.trigger(c.BACK_BUFFER_REACHED,{bufferEnd:s}),null!=r&&r.live)this.hls.trigger(c.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});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(c.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:n})}}})}flushFrontBuffer(t,e,s){const{sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(i=>{const n=r[i];if(n){const r=BufferHelper.getBuffered(n),a=r.length;if(a<2)return;const o=r.start(a-1),l=r.end(a-1);if(s>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(c.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:s,mediaSource:r}=this,i=t.fragments[0].start+t.totalduration,n=s.duration,a=l(r.duration)?r.duration:0;t.live&&e.config.liveDurationInfinity?(r.duration=1/0,this.updateSeekableRange(t)):(i>a&&i>n||!l(n))&&(this.log("Updating Media Source duration to "+i.toFixed(3)),r.duration=i)}updateSeekableRange(t){const e=this.mediaSource,s=t.fragments;if(s.length&&t.live&&null!=e&&e.setLiveSeekableRange){const r=Math.max(0,s[0].start),i=Math.max(r,r+t.totalduration);this.log(`Media Source duration is set to ${e.duration}. Setting seekable range to ${r}-${i}.`),e.setLiveSeekableRange(r,i)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:s}=this,r=Object.keys(s).length;if(r&&(!t||2===r||"audiovideo"in s)){this.createSourceBuffers(s),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(c.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(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const i in t)if(!e[i]){var r;const n=t[i];if(!n)throw Error(`source buffer exists for track ${i}, however track does not`);let a=-1===(null==(r=n.levelCodec)?void 0:r.indexOf(","))?n.levelCodec:n.codec;a&&"audio"===i.slice(0,5)&&(a=Yt(a,this.appendSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const t=e[i]=s.addSourceBuffer(o),r=i;this.addBufferListener(r,"updatestart",this._onSBUpdateStart),this.addBufferListener(r,"updateend",this._onSBUpdateEnd),this.addBufferListener(r,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(r,"bufferedchange",(t,e)=>{const s=e.removedRanges;null!=s&&s.length&&this.hls.trigger(c.BUFFER_FLUSHED,{type:i})}),this.tracks[i]={buffer:t,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(t){this.error("error while trying to add sourceBuffer: "+t.message),this.hls.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:i,mimeType:o})}}}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:s}=this;s.current(t).onComplete(),s.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){var s;const r=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(""+r,e),this.hls.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});const i=this.operationQueue.current(t);i&&i.onError(r)}removeExecutor(t,e,s){const{media:r,mediaSource:i,operationQueue:n,sourceBuffer:a}=this,o=a[t];if(!r||!i||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(t);const h=l(r.duration)?r.duration:1/0,d=l(i.duration)?i.duration:1/0,c=Math.max(0,e),u=Math.min(s,h,d);u>c&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${c},${u}] from the ${t} SourceBuffer`),o.remove(c,u)):n.shiftAndExecuteNext(t)}appendExecutor(t,e){const s=this.sourceBuffer[e];if(s)s.ended=!1,s.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:s}=this,r=e.map(t=>s.appendBlocker(t));Promise.all(r).then(()=>{t(),e.forEach(t=>{const e=this.sourceBuffer[t];null!=e&&e.updating||s.shiftAndExecuteNext(t)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,s){const r=this.sourceBuffer[t];if(!r)return;const i=s.bind(this,t);this.listeners[t].push({event:e,listener:i}),r.addEventListener(e,i)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach(t=>{e.removeEventListener(t.event,t.listener)})}},capLevelController:CapLevelController,errorController:class ErrorController{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=v.log.bind(v,"[info]:"),this.warn=v.warn.bind(v,"[warning]:"),this.error=v.error.bind(v,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(c.ERROR,this.onError,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(c.ERROR,this.onError,this),t.off(c.ERROR,this.onErrorOut,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.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)===he?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var s,r;if(e.fatal)return;const i=this.hls,n=e.context;switch(e.details){case f.FRAG_LOAD_ERROR:case f.FRAG_LOAD_TIMEOUT:case f.KEY_LOAD_ERROR:case f.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case f.FRAG_PARSING_ERROR:if(null!=(s=e.frag)&&s.gap)return void(e.errorAction={action:ze,flags:ts});case f.FRAG_GAP:case f.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Qe);case f.LEVEL_EMPTY_ERROR:case f.LEVEL_PARSING_ERROR:{var a,o;const t=e.parent===he?e.level:i.loadLevel;e.details===f.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 f.LEVEL_LOAD_ERROR:case f.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.level)));case f.AUDIO_TRACK_LOAD_ERROR:case f.AUDIO_TRACK_LOAD_TIMEOUT:case f.SUBTITLE_LOAD_ERROR:case f.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const t=i.levels[i.loadLevel];if(t&&(n.type===oe&&t.hasAudioGroup(n.groupId)||n.type===le&&t.hasSubtitleGroup(n.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.loadLevel),e.errorAction.action=Qe,void(e.errorAction.flags=es)}return;case f.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=i.levels[i.loadLevel],s=null==t?void 0:t.attrs["HDCP-LEVEL"];s?e.errorAction={action:Qe,flags:ss,hdcpLevel:s}:this.keySystemError(e)}return;case f.BUFFER_ADD_CODEC_ERROR:case f.REMUX_ALLOC_ERROR:case f.BUFFER_APPEND_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(r=e.level)?r:i.loadLevel));case f.INTERNAL_EXCEPTION:case f.BUFFER_APPENDING_ERROR:case f.BUFFER_FULL_ERROR:case f.LEVEL_SWITCH_ERROR:case f.BUFFER_STALLED_ERROR:case f.BUFFER_SEEK_OVER_HOLE:case f.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:ze,flags:ts})}e.type===u.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 s=Ke(this.hls.config.playlistLoadPolicy,t),r=this.playlistError++;if(Ye(s,r,Ge(t),t.response))return{action:Ze,flags:ts,retryConfig:s,retryCount:r};const i=this.getLevelSwitchAction(t,e);return s&&(i.retryConfig=s,i.retryCount=r),i}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),r=e.levels[s],{fragLoadPolicy:i,keyLoadPolicy:n}=e.config,a=Ke(t.details.startsWith("key")?n:i,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(r){t.details!==f.FRAG_GAP&&r.fragmentError++;if(Ye(a,o,Ge(t),t.response))return{action:Ze,flags:ts,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const r=this.hls.levels[e];if(r){var i,n;const e=t.details;r.loadError++,e===f.BUFFER_APPEND_ERROR&&r.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||(s.loadLevel=-1);const g=null==(i=t.frag)?void 0:i.type,m=(g===de&&e===f.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===f.BUFFER_ADD_CODEC_ERROR||e===f.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:t})=>r.audioCodec!==t),p="video"===t.sourceBufferName&&(e===f.BUFFER_ADD_CODEC_ERROR||e===f.BUFFER_APPEND_ERROR)&&h.some(({codecSet:t,audioCodec:e})=>r.codecSet!==t&&r.audioCodec===e),{type:y,groupId:v}=null!=(n=t.context)?n:{};for(let s=h.length;s--;){const i=(s+d)%h.length;if(i!==d&&i>=c&&i<=u&&0===h[i].loadError){var a,o;const s=h[i];if(e===f.FRAG_GAP&&t.frag){const e=h[i].details;if(e){const s=je(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(y===oe&&s.hasAudioGroup(v)||y===le&&s.hasSubtitleGroup(v))continue;if(g===de&&null!=(a=r.audioGroups)&&a.some(t=>s.hasAudioGroup(t))||g===ce&&null!=(o=r.subtitleGroups)&&o.some(t=>s.hasSubtitleGroup(t))||m&&r.audioCodec===s.audioCodec||!m&&r.audioCodec!==s.audioCodec||p&&r.codecSet===s.codecSet)continue}l=i;break}}if(l>-1&&s.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:Qe,flags:ts,nextAutoLevel:l}}return{action:Qe,flags:es}}onErrorOut(t,e){var s;switch(null==(s=e.errorAction)?void 0:s.action){case ze:break;case Qe:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===f.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;const{flags:r,hdcpLevel:i,nextAutoLevel:n}=s;switch(r){case ts:this.switchLevel(t,n);break;case ss:i&&(e.maxHdcpLevel=ke[ke.indexOf(i)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}s.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)}},fpsController:class FPSController{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(c.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(c.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const s=this.hls.config;if(s.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),s.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,s){const r=performance.now();if(e){if(this.lastTime){const t=r-this.lastTime,i=s-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*i/t,o=this.hls;if(o.trigger(c.FPS_DROP,{currentDropped:i,currentDecoded:n,totalDroppedFrames:s}),a>0&&i>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;v.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(c.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=s,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)}},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:U,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},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:Vi,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class SubtitleStreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"[subtitle-stream-controller]",ce),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.LEVEL_LOADED,this.onLevelLoaded,this),t.on(c.ERROR,this.onError,this),t.on(c.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(c.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(c.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(c.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(c.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.LEVEL_LOADED,this.onLevelLoaded,this),t.off(c.ERROR,this.onError,this),t.off(c.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(c.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(c.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(c.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(c.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=Ps,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:s,success:r}=e;if(this.fragPrevious=s,this.state=Ps,!r)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let n;const a=s.start;for(let t=0;t<i.length;t++)if(a>=i[t].start&&a<=i[t].end){n=i[t];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},i.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null)}onBufferFlushing(t,e){const{startOffset:s,endOffset:r}=e;if(0===s&&r!==Number.POSITIVE_INFINITY){const t=r-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{for(let s=0;s<e.length;)if(e[s].end<=t)e.shift();else{if(!(e[s].start<t))break;e[s].start=t,s++}}),this.fragmentTracker.removeFragmentsInRange(s,t,ce)}}onFragBuffered(t,e){var s;this.loadedmetadata||e.frag.type!==he||null!=(s=this.media)&&s.buffered.length&&(this.loadedmetadata=!0)}onError(t,e){const s=e.frag;(null==s?void 0:s.type)===ce&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==ws&&(this.state=Ps))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&Pr(this.levels,e)?this.levels=e.map(t=>new Level(t)):(this.tracksBuffered=[],this.levels=e.map(t=>{const e=new Level(t);return this.tracksBuffered[e.id]=[],e}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ce),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:r,levels:i}=this,{details:n,id:a}=e;if(!i)return void this.warn("Subtitle tracks were reset while loading level "+a);const o=i[r];if(a>=i.length||a!==r||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(s=o.details)&&s.live){const t=this.mainDetails;if(n.deltaUpdateFailed||!t)return;const e=t.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&e&&(l=e.start,Ne(n,l));else n.hasProgramDateTime&&t.hasProgramDateTime?(Rs(n,t),l=n.fragments[0].start):e&&(l=e.start,Ne(n,l))}if(o.details=n,this.levelLastLoaded=o,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===Ps){je(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t,r=e.decryptdata,i=this.hls;if(!this.fragContextChanged(e)&&s&&s.byteLength>0&&null!=r&&r.key&&r.iv&&"AES-128"===r.method){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer).catch(t=>{throw i.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(s=>{const r=performance.now();i.trigger(c.FRAG_DECRYPTED,{frag:e,payload:s,stats:{tstart:t,tdecrypt:r}})}).catch(t=>{this.warn(`${t.name}: ${t.message}`),this.state=Ps})}}doTick(){if(this.media){if(this.state===Ps){const{currentTrackId:t,levels:e}=this,s=null==e?void 0:e[t];if(!s||!e.length||!s.details)return;const{config:r}=this,i=this.getLoadPosition(),n=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,r.maxBufferHole),{end:a,len:o}=n,l=this.getFwdBufferInfo(this.media,he),h=s.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+h.levelTargetDuration)return;const d=h.fragments,c=d.length,u=h.edge;let f=null;const g=this.fragPrevious;if(a<u){const t=r.maxFragLookUpTolerance,e=a>u-t?0:t;f=je(g,d,Math.max(d[0].start,a),e),!f&&g&&g.start<d[0].start&&(f=d[0])}else f=d[c-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const t=d[f.sn-h.startSN-1];t&&t.cc===f.cc&&this.fragmentTracker.getState(t)===fs&&(f=t)}this.fragmentTracker.getState(f)===fs&&this.loadFragment(f,s,a)}}else this.state=Ps}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.max(e,t):e}loadFragment(t,e,s){this.fragCurrent=t,"initSegment"===t.sn?this._loadInitSegment(t,e):(this.startFragRequested=!0,super.loadFragment(t,e,s))}get mediaBufferTimeRanges(){return new BufferableInstance(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class SubtitleTrackController extends BasePlaylistController{constructor(t){super(t,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=ve(this.media.textTracks);for(let s=0;s<e.length;s++)if("hidden"===e[s].mode)t=e[s];else if("showing"===e[s].mode){t=e[s];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_PARSED,this.onManifestParsed,this),t.on(c.LEVEL_LOADING,this.onLevelLoading,this),t.on(c.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(c.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(c.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_PARSED,this.onManifestParsed,this),t.off(c.LEVEL_LOADING,this.onLevelLoading,this),t.off(c.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(c.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(c.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);ve(this.media.textTracks).forEach(t=>{pe(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,groupId:r,details:i}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==r)return void this.warn(`Subtitle track with id:${s} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.subtitleGroups||null,r=this.groupIds;let i=this.currentTrack;if(!s||(null==r?void 0:r.length)!==(null==s?void 0:s.length)||null!=s&&s.some(t=>-1===(null==r?void 0:r.indexOf(t)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!s||-1!==s.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!i&&e){this.selectDefaultTrack=!1;const s=hs(e,t);if(s>-1)i=t[s];else{const t=hs(e,this.tracks);i=this.tracks[t]}}let r=this.findTrackId(i);-1===r&&i&&(r=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(c.SUBTITLE_TRACKS_UPDATED,n),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}else this.shouldReloadPlaylist(i)&&this.setSubtitleTrack(this.trackId)}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let r=0;r<e.length;r++){const i=e[r];if((!s||i.default)&&(s||t)&&(!t||ds(i,t)))return r}if(t){for(let s=0;s<e.length;s++){const r=e[s];if(Ir(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const r=e[s];if(Ir(t.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){if(_r(e[s],t))return s}}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==le||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const s=this.currentTrack;if(s&&ds(t,s))return s;const r=hs(t,this.tracksInGroup);if(r>-1){const t=this.tracksInGroup[r];return this.setSubtitleTrack(r),t}if(s)return null;{const s=hs(t,e);if(s>-1)return e[s]}}}return null}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){const s=e.id,r=e.groupId;let i=e.url;if(t)try{i=t.addDirectives(i)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("Loading subtitle playlist for id "+s),this.hls.trigger(c.SUBTITLE_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null})}}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=ve(t.textTracks),s=this.currentTrack;let r;if(s&&(r=e.filter(t=>_r(s,t))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(e).forEach(t=>{"disabled"!==t.mode&&t!==r&&(t.mode="disabled")}),r){const t=this.subtitleDisplay?"showing":"hidden";r.mode!==t&&(r.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!l(t))return void this.warn("Invalid subtitle track id: "+t);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,r=e[t]||null;if(this.trackId=t,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(c.SUBTITLE_TRACK_SWITCH,{id:t});const i=!!r.details&&!r.details.live;if(t===this.trackId&&r===s&&i)return;this.log("Switching to subtitle-track "+t+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:n,groupId:a="",name:o,type:h,url:d}=r;this.hls.trigger(c.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:h,url:d});const u=this.switchParams(r.url,null==s?void 0:s.details,r.details);this.loadPlaylist(u)}},timelineController:class TimelineController{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(c.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(c.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(c.FRAG_LOADING,this.onFragLoading,this),t.on(c.FRAG_LOADED,this.onFragLoaded,this),t.on(c.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(c.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(c.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(c.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(c.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(c.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(c.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(c.FRAG_LOADING,this.onFragLoading,this),t.off(c.FRAG_LOADED,this.onFragLoaded,this),t.off(c.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(c.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(c.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(c.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(c.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const t=new OutputFilter(this,"textTrack1"),e=new OutputFilter(this,"textTrack2"),s=new OutputFilter(this,"textTrack3"),r=new OutputFilter(this,"textTrack4");this.cea608Parser1=new Cea608Parser(1,t,e),this.cea608Parser2=new Cea608Parser(3,s,r)}}addCues(t,e,s,r,i){let n=!1;for(let t=i.length;t--;){const r=i[t],d=(a=r[0],o=r[1],l=e,h=s,Math.min(o,h)-Math.max(a,l));if(d>=0&&(r[0]=Math.min(r[0],e),r[1]=Math.max(r[1],s),n=!0,d/(s-e)>.5))return}var a,o,l,h;if(n||i.push([e,s]),this.config.renderTextTracksNatively){const i=this.captionsTracks[t];this.Cues.newCue(i,e,s,r)}else{const i=this.Cues.newCue(null,e,s,r);this.hls.trigger(c.CUES_PARSED,{type:"captions",cues:i,track:t})}}onInitPtsFound(t,{frag:e,id:s,initPTS:r,timescale:i}){const{unparsedVttFrags:n}=this;"main"===s&&(this.initPTS[e.cc]={baseTime:r,timescale:i}),n.length&&(this.unparsedVttFrags=[],n.forEach(t=>{this.onFragLoaded(c.FRAG_LOADED,t)}))}getExistingTrack(t,e){const{media:s}=this;if(s)for(let r=0;r<s.textTracks.length;r++){const i=s.textTracks[r];if(fi(i,{name:t,lang:e,attrs:{}}))return i}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:s,media:r}=this,{label:i,languageCode:n}=e[t],a=this.getExistingTrack(i,n);if(a)s[t]=a,pe(s[t]),ge(s[t],r);else{const e=this.createTextTrack("captions",i,n);e&&(e[t]=!0,s[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const s={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=s,this.hls.trigger(c.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(t,e,s){const r=this.media;if(r)return r.addTextTrack(t,e,s)}onMediaAttaching(t,e){this.media=e.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:t}=this;Object.keys(t).forEach(e=>{pe(t[e]),delete t[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;t<e.length;t++)pe(e[t])}onSubtitleTracksUpdated(t,e){const s=e.subtitleTracks||[],r=s.some(t=>"stpp.ttml.im1t"===t.textCodec);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Pr(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,e=t?ve(t.textTracks):null;if(this.tracks.forEach((t,s)=>{let r;if(e){let s=null;for(let r=0;r<e.length;r++)if(e[r]&&fi(e[r],t)){s=e[r],e[r]=null;break}s&&(r=s)}if(r)pe(r);else{const e=ui(t);r=this.createTextTrack(e,t.name,t.lang),r&&(r.mode="disabled")}r&&this.textTracks.push(r)}),null!=e&&e.length){const t=e.filter(t=>null!==t).map(t=>t.label);t.length&&v.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger(c.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const s="textTrack"+e[1],r=this.captionsProperties[s];r&&(r.label=t.name,t.lang&&(r.languageCode=t.lang),r.media=t)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:r,lastCc:i,lastSn:n,lastPartIndex:a}=this;if(this.enabled&&s&&r&&e.frag.type===he){var o,l;const{cc:t,sn:h}=e.frag,d=null!=(o=null==e||null==(l=e.part)?void 0:l.index)?o:-1;h===n+1||h===n&&d===a+1||t===i||(s.reset(),r.reset()),this.lastCc=t,this.lastSn=h,this.lastPartIndex=d}}onFragLoaded(t,e){const{frag:s,payload:r}=e;if(s.type===ce)if(r.byteLength){const t=s.decryptdata,i="stats"in e;if(null==t||!t.encrypted||i){const t=this.tracks[s.level],i=this.vttCCs;i[s.cc]||(i[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),t&&"stpp.ttml.im1t"===t.textCodec?this._parseIMSC1(s,r):this._parseVTTs(e)}}else this.hls.trigger(c.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const s=this.hls;ai(e,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),s.trigger(c.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},e=>{v.log("Failed to parse IMSC1: "+e),s.trigger(c.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})})}_parseVTTs(t){var e;const{frag:s,payload:r}=t,{initPTS:i,unparsedVttFrags:n}=this,a=i.length-1;if(!i[s.cc]&&-1===a)return void n.push(t);const o=this.hls;si(null!=(e=s.initSegment)&&e.data?At(s.initSegment.data,new Uint8Array(r)):r,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,t=>{this._appendCues(t,s.level),o.trigger(c.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},e=>{const i="Missing initPTS for VTT MPEGTS"===e.message;i?n.push(t):this._fallbackToIMSC1(s,r),v.log("Failed to parse VTT cue: "+e),i&&a>s.cc||o.trigger(c.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:e})})}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||ai(e,this.initPTS[t.cc],()=>{s.textCodec="stpp.ttml.im1t",this._parseIMSC1(t,e)},()=>{s.textCodec="wvtt"})}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||"disabled"===s.mode)return;t.forEach(t=>me(s,t))}else{const r=this.tracks[e];if(!r)return;const i=r.default?"default":"subtitles"+e;s.trigger(c.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,e){const{frag:s}=e;s.type===ce&&this.onFragLoaded(c.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:r}=this;if(!this.enabled||!s||!r)return;const{frag:i,samples:n}=e;if(i.type!==he||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<n.length;t++){const e=n[t].bytes;if(e){const i=this.extractCea608Data(e);s.addData(n[t].pts,i[0]),r.addData(n[t].pts,i[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:s,endOffsetSubtitles:r,type:i}){const{media:n}=this;if(n&&!(n.currentTime<s)){if(!i||"video"===i){const{captionsTracks:t}=this;Object.keys(t).forEach(r=>ye(t[r],e,s))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==r){const{textTracks:t}=this;Object.keys(t).forEach(s=>ye(t[s],e,r))}}}extractCea608Data(t){const e=[[],[]],s=31&t[0];let r=2;for(let i=0;i<s;i++){const s=t[r++],i=127&t[r++],n=127&t[r++];if(0===i&&0===n)continue;if(0!=(4&s)){const t=3&s;0!==t&&1!==t||(e[t].push(i),e[t].push(n))}}return e}},audioStreamController:class AudioStreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"[audio-stream-controller]",de),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:t}=this;t.on(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.LEVEL_LOADED,this.onLevelLoaded,this),t.on(c.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(c.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(c.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(c.ERROR,this.onError,this),t.on(c.BUFFER_RESET,this.onBufferReset,this),t.on(c.BUFFER_CREATED,this.onBufferCreated,this),t.on(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(c.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(c.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(c.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.LEVEL_LOADED,this.onLevelLoaded,this),t.off(c.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(c.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(c.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(c.ERROR,this.onError,this),t.off(c.BUFFER_RESET,this.onBufferReset,this),t.off(c.BUFFER_CREATED,this.onBufferCreated,this),t.off(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(c.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(c.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(c.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(t,{frag:e,id:s,initPTS:r,timescale:i}){if("main"===s){const t=e.cc;this.initPTS[e.cc]={baseTime:r,timescale:i},this.log(`InitPTS for cc: ${t} found from main: ${r}`),this.videoTrackCC=t,this.state===Bs&&this.tick()}}startLoad(t){if(!this.levels)return this.startPosition=t,void(this.state=ws);const e=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),e>0&&-1===t?(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e,this.state=Ps):(this.loadedmetadata=!1,this.state=xs),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case Ps:this.doTickIdle();break;case xs:{var t;const{levels:e,trackId:s}=this,r=null==e||null==(t=e[s])?void 0:t.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=Bs}break}case Ms:{var e;const t=performance.now(),s=this.retryDate;if(!s||t>=s||null!=(e=this.media)&&e.seeking){const{levels:t,trackId:e}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[e])||null),this.state=Ps}break}case Bs:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:r,complete:i}=t;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=_s;const t={frag:e,part:s,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(t),i&&super._handleFragmentLoadComplete(t)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${e.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const t=this.getLoadPosition(),s=BufferHelper.bufferInfo(this.mediaBuffer,t,this.config.maxBufferHole);qe(s.end,this.config.maxFragLookUpTolerance,e)<0&&(this.log(`Waiting fragment cc (${e.cc}) @ ${e.start} cancelled because another fragment at ${s.end} is needed`),this.clearWaitingFragment())}}else this.state=Ps}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Ps)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:e,media:s,trackId:r}=this,i=t.config;if(!s&&(this.startFragRequested||!i.startFragPrefetch)||null==e||!e[r])return;const n=e[r],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=xs);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,L,de));const l=this.getFwdBufferInfo(o,de);if(null===l)return;const{bufferedTrack:h,switchingTrack:d}=this;if(!d&&this._streamEnded(l,a))return t.trigger(c.BUFFER_EOS,{type:"audio"}),void(this.state=Ns);const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,he),f=l.len,g=this.getMaxBufferLength(null==u?void 0:u.len),m=a.fragments,p=m[0].start;let y=this.flushing?this.getLoadPosition():l.end;if(d&&s){const t=this.getLoadPosition();h&&!Ir(d.attrs,h.attrs)&&(y=t),a.PTSKnown&&t<p&&(l.end>p||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=p+.05)}if(f>=g&&!d&&y<m[m.length-1].start)return;let v=this.getNextFragment(y,a),E=!1;if(v&&this.isLoopLoading(v,y)&&(E=!!v.gap,v=this.getNextFragmentLoopLoading(v,a,l,he,g)),!v)return void(this.bufferFlushed=!0);const T=u&&v.start>u.end+a.targetduration;if(T||(null==u||!u.len)&&l.len){const t=this.getAppendedFrag(v.start,he);if(null===t)return;if(E||(E=!!t.gap||!!T&&0===u.len),T&&!E||E&&l.nextStart&&l.nextStart<t.end)return}this.loadFragment(v,n,y)}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.min(Math.max(e,t),this.config.maxMaxBufferLength):e}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new Level(t))}onAudioTrackSwitching(t,e){const s=!!e.url;this.trackId=e.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),s?this.setInterval(100):this.resetTransmuxer(),s?(this.switchingTrack=e,this.state=Ps,this.flushAudioIfNeeded(e)):(this.switchingTrack=null,this.bufferedTrack=e,this.state=ws),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(c.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,e){var s;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=e);const{levels:r}=this,{details:i,id:n}=e;if(!r)return void this.warn("Audio tracks were reset while loading level "+n);this.log(`Audio track ${n} loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const a=r[n];let o=0;if(i.live||null!=(s=a.details)&&s.live){this.checkLiveUpdate(i);const t=this.mainDetails;if(i.deltaUpdateFailed||!t)return;var l;if(!a.details&&i.hasProgramDateTime&&t.hasProgramDateTime)Rs(i,t),o=i.fragments[0].start;else o=this.alignPlaylists(i,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=i,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&i.live||this.setStartPosition(this.mainDetails||i,o),this.state!==xs||this.waitForCdnTuneIn(i)||(this.state=Ps),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:s,part:r,payload:i}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new TransmuxerInterface(this.hls,de,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(e=s.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=r?r.index:-1,n=-1!==e,a=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,i.byteLength,e,n);c.push(i,f,d,"",s,r,h.totalduration,t,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:s,part:r,cache:new ChunkCache,complete:!1};t.push(new Uint8Array(i)),this.waitingVideoCC=this.videoTrackCC,this.state=Bs}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,e){const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)}onFragBuffered(t,e){const{frag:s,part:r}=e;if(s.type===de)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==s.sn){this.fragPrevious=s;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(c.AUDIO_TRACK_SWITCHED,i({},t)))}this.fragBufferedComplete(s,r)}else if(!this.loadedmetadata&&s.type===he){const t=this.videoBuffer||this.media;if(t){BufferHelper.getBuffered(t).length&&(this.loadedmetadata=!0)}}}onError(t,e){var s;if(e.fatal)this.state=Us;else switch(e.details){case f.FRAG_GAP:case f.FRAG_PARSING_ERROR:case f.FRAG_DECRYPT_ERROR:case f.FRAG_LOAD_ERROR:case f.FRAG_LOAD_TIMEOUT:case f.KEY_LOAD_ERROR:case f.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(de,e);break;case f.AUDIO_TRACK_LOAD_ERROR:case f.AUDIO_TRACK_LOAD_TIMEOUT:case f.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==xs||(null==(s=e.context)?void 0:s.type)!==oe||(this.state=Ps);break;case f.BUFFER_APPEND_ERROR:case f.BUFFER_FULL_ERROR:if(!e.parent||"audio"!==e.parent)return;if(e.details===f.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case f.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==A&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==A){this.flushing=!1,this.bufferFlushed=!0,this.state===Ns&&(this.state=Ps);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,de),this.tick())}}_handleTransmuxComplete(t){var e;const s="audio",{hls:r}=this,{remuxResult:i,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:l,part:h,level:d}=a,{details:u}=d,{audio:f,text:g,id3:m,initSegment:p}=i;if(!this.fragContextChanged(l)&&u){if(this.state=Fs,this.switchingTrack&&f&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){const t=l.initSegment||l;this._bufferInitSegment(d,p.tracks,t,n),r.trigger(c.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:p.tracks})}if(f){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=f;h&&(h.elementaryStreams[L]={startPTS:t,endPTS:e,startDTS:s,endDTS:r}),l.setElementaryStreamInfo(L,t,e,s,r),this.bufferFragmentData(f,l,h,n)}if(null!=m&&null!=(e=m.samples)&&e.length){const t=o({id:s,frag:l,details:u},m);r.trigger(c.FRAG_PARSING_METADATA,t)}if(g){const t=o({id:s,frag:l,details:u},g);r.trigger(c.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(l)}_bufferInitSegment(t,e,s,r){if(this.state!==Fs)return;e.video&&delete e.video;const i=e.audio;if(!i)return;i.id="audio";const n=t.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${n}/${i.codec}]`),n&&1===n.split(",").length&&(i.levelCodec=n),this.hls.trigger(c.BUFFER_CODECS,e);const a=i.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:s,part:null,chunkMeta:r,parent:s.type,data:a};this.hls.trigger(c.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,s){const r=this.fragmentTracker.getState(t);var i;if(this.fragCurrent=t,this.switchingTrack||r===fs||r===ms)if("initSegment"===t.sn)this._loadInitSegment(t,e);else if(null!=(i=e.details)&&i.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Bs;const s=this.mainDetails;s&&s.fragments[0].start!==e.details.fragments[0].start&&Rs(e.details,s)}else this.startFragRequested=!0,super.loadFragment(t,e,s);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){const{media:e,bufferedTrack:s}=this,r=null==s?void 0:s.attrs,i=t.attrs;e&&r&&(r.CHANNELS!==i.CHANNELS||s.name!==t.name||s.lang!==t.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(c.AUDIO_TRACK_SWITCHED,i({},t))}},audioTrackController:class AudioTrackController extends BasePlaylistController{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_PARSED,this.onManifestParsed,this),t.on(c.LEVEL_LOADING,this.onLevelLoading,this),t.on(c.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(c.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(c.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_PARSED,this.onManifestParsed,this),t.off(c.LEVEL_LOADING,this.onLevelLoading,this),t.off(c.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(c.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(c.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:r,details:i}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==r)return void this.warn(`Audio track with id:${s} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.audioGroups||null,r=this.groupIds;let i=this.currentTrack;if(!s||(null==r?void 0:r.length)!==(null==s?void 0:s.length)||null!=s&&s.some(t=>-1===(null==r?void 0:r.indexOf(t)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!s||-1!==s.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!i&&e){const s=hs(e,t,cs);if(s>-1)i=t[s];else{const t=hs(e,this.tracks);i=this.tracks[t]}}let r=this.findTrackId(i);-1===r&&i&&(r=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(c.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==r&&-1===o)this.setAudioTrack(r);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}else this.shouldReloadPlaylist(i)&&this.setAudioTrack(this.trackId)}onError(t,e){!e.fatal&&e.context&&(e.context.type!==oe||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||(this.requestScheduled=-1,this.checkRetry(e)))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const r=this.currentTrack;if(r&&ds(t,r,cs))return r;const i=hs(t,this.tracksInGroup,cs);if(i>-1){const t=this.tracksInGroup[i];return this.setAudioTrack(i),t}if(r){let r=e.loadLevel;-1===r&&(r=e.firstAutoLevel);const i=function(t,e,s,r,i){const n=e[r],a=e.reduce((t,e,s)=>{const r=e.uri;return(t[r]||(t[r]=[])).push(s),t},{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=us(e,r,e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;const r=e.audioGroups,n=s.filter(t=>!r||-1!==r.indexOf(t.groupId));return hs(t,n,i)>-1});return d>-1?d:us(e,r,e=>{const r=e.audioGroups,n=s.filter(t=>!r||-1!==r.indexOf(t.groupId));return hs(t,n,i)>-1})}(t,e.levels,s,r,cs);if(-1===i)return null;e.nextLoadLevel=i}if(t.channels||t.audioCodec){const e=hs(t,s);if(e>-1)return s[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn("Invalid audio track id: "+t);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,r=e[t],n=r.details&&!r.details.live;if(t===this.trackId&&r===s&&n)return;if(this.log(`Switching to audio-track ${t} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=t,this.currentTrack=r,this.hls.trigger(c.AUDIO_TRACK_SWITCHING,i({},r)),n)return;const a=this.switchParams(r.url,null==s?void 0:s.details,r.details);this.loadPlaylist(a)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const r=e[s];if((!this.selectDefaultTrack||r.default)&&(!t||ds(t,r,cs)))return s}if(t){const{name:s,lang:r,assocLang:i,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(ds({name:s,lang:r,assocLang:i,characteristics:n,audioCodec:a,channels:o},e[t],cs))return t}for(let s=0;s<e.length;s++){const r=e[s];if(Ir(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const r=e[s];if(Ir(t.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}loadPlaylist(t){const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){super.loadPlaylist();const s=e.id,r=e.groupId;let i=e.url;if(t)try{i=t.addDirectives(i)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log(`loading audio-track playlist ${s} "${e.name}" lang:${e.lang} group:${r}`),this.clearTimer(),this.hls.trigger(c.AUDIO_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null})}}},emeController:EMEController,cmcdController:class CMCDController{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:gi.MANIFEST,su:!this.initialized})}catch(t){v.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const e=t.frag,s=this.hls.levels[e.level],r=this.getObjectType(e),i={d:1e3*e.duration,ot:r};r!==gi.VIDEO&&r!==gi.AUDIO&&r!=gi.MUXED||(i.br=s.bitrate/1e3,i.tb=this.getTopBandwidth(r)/1e3,i.bl=this.getBufferLength(r)),this.apply(t,i)}catch(t){v.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:s}=e;null!=s&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|8).toString(16)})}}}(),this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(c.MEDIA_DETACHED,this.onMediaDetached,this),t.on(c.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(c.MEDIA_DETACHED,this.onMediaDetached,this),t.off(c.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var s,r;this.audioBuffer=null==(s=e.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(r=e.tracks.video)?void 0:r.buffer}createData(){var t;return{v:1,sf:mi.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){o(e,this.createData());const s=e.ot===gi.INIT||e.ot===gi.VIDEO||e.ot===gi.MUXED;this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:r}=this;r&&(e=Object.keys(e).reduce((t,s)=>(r.includes(s)&&(t[s]=e[s]),t),{})),this.useHeaders?(t.headers||(t.headers={}),Fi(t.headers,e)):t.url=Ni(t.url,e)}getObjectType(t){const{type:e}=t;return"subtitle"===e?gi.TIMED_TEXT:"initSegment"===t.sn?gi.INIT:"audio"===e?gi.AUDIO:"main"===e?this.hls.audioTracks.length?gi.VIDEO:gi.MUXED:void 0}getTopBandwidth(t){let e,s=0;const r=this.hls;if(t===gi.AUDIO)e=r.audioTracks;else{const t=r.maxAutoLevel,s=t>-1?t+1:r.levels.length;e=r.levels.slice(0,s)}for(const t of e)t.bitrate>s&&(s=t.bitrate);return s>0?s:NaN}getBufferLength(t){const e=this.hls.media,s=t===gi.AUDIO?this.audioBuffer:this.videoBuffer;if(!s||!e)return NaN;return 1e3*BufferHelper.bufferInfo(s,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,s=t||this.config.loader;return class CmcdPlaylistLoader{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,r){e(t),this.loader.load(t,s,r)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=t||this.config.loader;return class CmcdFragmentLoader{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,r){e(t),this.loader.load(t,s,r)}}}},contentSteeringController:class ContentSteeringController{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=v.log.bind(v,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(c.MANIFEST_PARSED,this.onManifestParsed,this),t.on(c.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(c.MANIFEST_PARSED,this.onManifestParsed,this),t.off(c.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:s}=e;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:s}=e;if((null==s?void 0:s.action)===Qe&&s.flags===es){const t=this.levels;let r=this.pathwayPriority,i=this.pathwayId;if(e.context){const{groupId:s,pathwayId:r,type:n}=e.context;s&&t?i=this.getPathwayForGroupId(s,n,i):r&&(i=r)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!r&&t&&(r=t.reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==i),s.resolved||v.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${i} levels: ${t?t.length:t} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),e=this.getLevelsForPathway(s),this.pathwayId=s}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 s=this.penalizedPathways,r=performance.now();Object.keys(s).forEach(t=>{r-s[t]>3e5&&delete s[t]});for(let r=0;r<t.length;r++){const i=t[r];if(i in s)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,$e(e),this.hls.trigger(c.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,s){const r=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<r.length;s++)if(e===oe&&r[s].hasAudioGroup(t)||e===le&&r[s].hasSubtitleGroup(t))return r[s].pathwayId;return s}clonePathways(t){const e=this.levels;if(!e)return;const s={},r={};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 AttrList(t.attrs);e["PATHWAY-ID"]=i;const n=e.AUDIO&&`${e.AUDIO}_clone_${i}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${i}`;n&&(s[e.AUDIO]=n,e.AUDIO=n),o&&(r[e.SUBTITLES]=o,e.SUBTITLES=o);const l=Bi(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new Level({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++)h.addGroupId("audio",`${t.audioGroups[e]}_clone_${i}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)h.addGroupId("text",`${t.subtitleGroups[e]}_clone_${i}`);return h});e.push(...o),Ui(this.audioTracks,s,a,i),Ui(this.subtitleTracks,r,a,i)})}loadSteeringManifest(t){const e=this.hls.config,s=e.loader;let r;this.loader&&this.loader.destroy(),this.loader=new s(e);try{r=new self.URL(t)}catch(e){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: "+t)}if("data:"!==r.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+t)}const i={responseType:"json",url:r.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,s,i)=>{this.log(`Loaded steering manifest: "${r}"`);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,r).href}catch(t){return this.enabled=!1,void this.log("Failed to parse Steering Manifest RELOAD-URI: "+a)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:r.toString()};this.hls.trigger(c.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,s,r)=>{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,s)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log("Requesting steering manifest: "+r),this.loader.load(i,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const s=null==(e=this.hls)?void 0:e.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}}});function Wi(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Wi):Object.keys(t).reduce((e,s)=>(e[s]=Wi(t[s]),e),{}):t}function ji(t){const e=t.loader;if(e!==FetchLoader&&e!==XhrLoader)v.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=FetchLoader,t.progressive=!0,t.enableSoftwareAES=!0,v.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let qi;class LevelController extends BasePlaylistController{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(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(c.LEVEL_LOADED,this.onLevelLoaded,this),t.on(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(c.FRAG_BUFFERED,this.onFragBuffered,this),t.on(c.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(c.LEVEL_LOADED,this.onLevelLoaded,this),t.off(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(c.FRAG_BUFFERED,this.onFragBuffered,this),t.off(c.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 s=this.hls.config.preferManagedMediaSource,r=[],i={},n={};let a=!1,o=!1,l=!1;e.levels.forEach(t=>{var e,h;const d=t.attrs;let{audioCodec:c,videoCodec:u}=t;-1!==(null==(e=c)?void 0:e.indexOf("mp4a.40.34"))&&(qi||(qi=/chrome|firefox/i.test(navigator.userAgent)),qi&&(t.audioCodec=c=void 0)),c&&(t.audioCodec=c=Yt(c,s)),0===(null==(h=u)?void 0:h.indexOf("avc1"))&&(u=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}(u));const{width:f,height:g,unknownCodecs:m}=t;if(a||(a=!(!f||!g)),o||(o=!!u),l||(l=!!c),null!=m&&m.length||c&&!Ut(c,"audio",s)||u&&!Ut(u,"video",s))return;const{CODECS:p,"FRAME-RATE":y,"HDCP-LEVEL":v,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=d,L=`${(E||".")+"-"}${t.bitrate}-${T}-${y}-${p}-${S}-${v}`;if(i[L])if(i[L].uri===t.url||t.attrs["PATHWAY-ID"])i[L].addGroupId("audio",d.AUDIO),i[L].addGroupId("text",d.SUBTITLES);else{const e=n[L]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const s=new Level(t);i[L]=s,r.push(s)}else{const e=new Level(t);i[L]=e,n[L]=1,r.push(e)}}),this.filterAndSortMediaOptions(r,e,a,o,l)}filterAndSortMediaOptions(t,e,s,r,i){let n=[],a=[],o=t;if((s||r)&&i&&(o=o.filter(({videoCodec:t,videoRange:e,width:s,height:r})=>{return(!!t||!(!s||!r))&&(!!(i=e)&&De.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(c.ERROR,{type:u.MEDIA_ERROR,details:f.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||Ut(e.audioCodec,"audio",t)),Xi(n)}e.subtitles&&(a=e.subtitles,Xi(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(s&&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 De.indexOf(t.videoRange)-De.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const s=Gt(t.videoCodec),r=Gt(e.videoCodec);if(s!==r)return r-s}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const s=Kt(t.codecSet),r=Kt(e.codecSet);if(s!==r)return r-s}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let h=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){h=l[t];break}this._levels=o;for(let t=0;t<o.length;t++)if(o[t]===h){var d;this._firstLevel=t;const e=h.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${e}`),void 0===(null==(d=this.hls.userConfig)?void 0:d.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>s&&s===Yi.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const g=i&&!r,m={levels:o,audioTracks:n,subtitleTracks:a,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:i,video:r,altAudio:!g&&n.some(t=>!!t.url)};this.hls.trigger(c.MANIFEST_PARSED,m),(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 s=new Error("invalid level idx"),r=t<0;if(this.hls.trigger(c.ERROR,{type:u.OTHER_ERROR,details:f.LEVEL_SWITCH_ERROR,level:t,fatal:r,error:s,reason:s.message}),r)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,s===t&&n.details&&r&&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 ${s}${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(c.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==r?void 0:r.details,l);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===ae&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===he){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const s=this._levels[e.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var s;const{level:r,details:i}=e,n=this._levels[r];var a;if(!n)return this.warn("Invalid level index "+r),void(null!=(a=e.deliveryDirectives)&&a.skip&&(i.deltaUpdateFailed=!0));r===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(r,e,n.details)):null!=(s=e.deliveryDirectives)&&s.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){let r=s.uri;if(t)try{r=t.addDirectives(r)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}const i=s.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:""} ${r}`),this.clearTimer(),this.hls.trigger(c.LEVEL_LOADING,{url:r,level:e,pathwayId:s.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 s=this._levels.filter((e,s)=>s!==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));$e(s),this._levels=s,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(c.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(c.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Xi(t){const e={};t.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}class KeyLoader{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[s].loader;if(r){var e;if(t&&t!==(null==(e=r.context)?void 0:e.frag.type))return;r.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=f.KEY_LOAD_ERROR,s,r,i){return new LoadError({type:u.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:i,error:s,networkDetails:r})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:r}=t;for(let t=0;t<e.length;t++){const i=e[t];if(r<=i.cc&&("initSegment"===s||"initSegment"===i.sn||s<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 s,r;e&&t.setKeyFormat(e);const i=t.decryptdata;if(!i){const s=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,f.KEY_LOAD_ERROR,s))}const n=i.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,f.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(s=a)&&s.decryptdata.key)return i.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var o;if(null!=(r=a)&&r.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,f.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t,e){const s={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(s);if(e)return(t.keyLoadPromise=e.then(e=>(t.mediaKeySessionContext=e,s))).catch(e=>{throw t.keyLoadPromise=null,e})}return Promise.resolve(s)}loadKeyHTTP(t,e){const s=this.config,r=new(0,s.loader)(s);return e.keyLoader=t.loader=r,t.keyLoadPromise=new Promise((n,a)=>{const o={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,s,r)=>{const{frag:i,keyInfo:o,url:l}=s;if(!i.decryptdata||o!==this.keyUriToKeyInfo[l])return a(this.createKeyLoadError(i,f.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=i.decryptdata.key=new Uint8Array(t.data),i.keyLoader=null,o.loader=null,n({frag:i,keyInfo:o})},onError:(t,s,r,n)=>{this.resetLoader(s),a(this.createKeyLoadError(e,f.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),r,i({url:o.url,data:void 0},t)))},onTimeout:(t,s,r)=>{this.resetLoader(s),a(this.createKeyLoadError(e,f.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(t,s,r)=>{this.resetLoader(s),a(this.createKeyLoadError(e,f.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(o,h,d)})}resetLoader(t){const{frag:e,keyInfo:s,url:r}=t,i=s.loader;e.keyLoader===i&&(e.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[r],i&&i.destroy()}}function zi(){return self.SourceBuffer||self.WebKitSourceBuffer}function Qi(){if(!Ot())return!1;const t=zi();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class GapController{constructor(t,e,s,r){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=s,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:s,media:r,stalled:i}=this;if(null===r)return;const{currentTime:n,seeking:a}=r,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;v.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(r.paused&&!a||r.ended||0===r.playbackRate||!BufferHelper.getBuffered(r).length)return void(this.nudgeRetry=0);const h=BufferHelper.bufferInfo(r,n,0),d=h.nextStart||0;if(a){const t=h.len>2,s=!d||e&&e.start<=n||d-n>2&&!this.fragmentTracker.getPartialFragment(n);if(t||s)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var c;if(!(h.len>0)&&!d)return;const t=Math.max(d,h.start||0)-n,e=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,s=(null==e||null==(c=e.details)?void 0:c.live)?2*e.details.targetduration:2,i=this.fragmentTracker.getPartialFragment(n);if(t>0&&(t<=s||i))return void(r.paused||this._trySkipBufferHole(i))}const u=self.performance.now();if(null===i)return void(this.stalled=u);const f=u-i;if(!a&&f>=250&&(this._reportStall(h),!this.media))return;const g=BufferHelper.bufferInfo(r,n,s.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(t,e){const{config:s,fragmentTracker:r,media:i}=this;if(null===i)return;const n=i.currentTime,a=r.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(t.len>s.maxBufferHole||t.nextStart&&t.nextStart-n<s.maxBufferHole)&&e>1e3*s.highBufferWatchdogPeriod&&(v.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:s,stallReported:r}=this;if(!r&&s){this.stallReported=!0;const r=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(t)})`);v.warn(r.message),e.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:s,media:r}=this;if(null===r)return 0;const i=r.currentTime,n=BufferHelper.bufferInfo(r,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&&r.readyState<3,h=a-i;if(h>0&&(o||l)){if(h>e.maxBufferHole){const{fragmentTracker:e}=this;let s=!1;if(0===i){const t=e.getAppendedFrag(0,he);t&&a<t.end&&(s=!0)}if(!s){const s=t||e.getAppendedFrag(i,he);if(s){let t=!1,r=s.end;for(;r<a;){const s=e.getPartialFragment(r);if(!s){t=!0;break}r+=s.duration}if(t)return 0}}}const n=Math.max(a+.05,i+.1);if(v.warn(`skipping hole, adjusting currentTime from ${i} to ${n}`),this.moved=!0,this.stalled=null,r.currentTime=n,t&&!t.gap){const e=new Error(`fragment loaded with buffer holes, seeking from ${i} to ${n}`);s.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:e,reason:e.message,frag:t})}return n}}return 0}_tryNudgeBuffer(){const{config:t,hls:e,media:s,nudgeRetry:r}=this;if(null===s)return;const i=s.currentTime;if(this.nudgeRetry++,r<t.nudgeMaxRetry){const n=i+(r+1)*t.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${i} to ${n}`);v.warn(a.message),s.currentTime=n,e.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const s=new Error(`Playhead still not moving while enough data buffered @${i} after ${t.nudgeMaxRetry} nudges`);v.error(s.message),e.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_STALLED_ERROR,error:s,fatal:!0})}}}class StreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"[stream-controller]",he),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(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_PARSED,this.onManifestParsed,this),t.on(c.LEVEL_LOADING,this.onLevelLoading,this),t.on(c.LEVEL_LOADED,this.onLevelLoaded,this),t.on(c.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(c.ERROR,this.onError,this),t.on(c.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(c.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(c.BUFFER_CREATED,this.onBufferCreated,this),t.on(c.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(c.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_PARSED,this.onManifestParsed,this),t.off(c.LEVEL_LOADED,this.onLevelLoaded,this),t.off(c.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(c.ERROR,this.onError,this),t.off(c.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(c.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(c.BUFFER_CREATED,this.onBufferCreated,this),t.off(c.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(c.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(t){if(this.levels){const{lastCurrentTime:e,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=s.startLevel;-1===t&&(s.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=s.firstAutoLevel),s.nextLoadLevel=t,this.level=s.loadLevel,this.loadedmetadata=!1}e>0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=Ps,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=ws}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case $s:{const{levels:t,level:e}=this,s=null==t?void 0:t[e],r=null==s?void 0:s.details;if(r&&(!r.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(r))break;this.state=Ps;break}if(this.hls.nextLoadLevel!==this.level){this.state=Ps;break}break}case Ms:{var t;const e=self.performance.now(),s=this.retryDate;if(!s||e>=s||null!=(t=this.media)&&t.seeking){const{levels:t,level:e}=this,s=null==t?void 0:t[e];this.resetStartWhenNotLoaded(s||null),this.state=Ps}}}this.state===Ps&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:r}=this;if(null===e||!r&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const i=t.nextLoadLevel;if(null==s||!s[i])return;const n=s[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(c.BUFFER_EOS,t),void(this.state=Ns)}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===$s||l.live&&this.levelLastLoaded!==n)return this.level=i,void(this.state=$s);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let f=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==ps){var g;const t=(null!=(g=this.backtrackFragment)?g:f).sn-l.startSN,e=l.fragments[t-1];e&&f.cc===e.cc&&(f=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,u)){if(!f.gap){const t=this.audioOnly&&!this.altAudio?L:A,e=(t===A?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,he)}f=this.getNextFragmentLoopLoading(f,l,a,he,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,n,u))}loadFragment(t,e,s){const r=this.fragmentTracker.getState(t);this.fragCurrent=t,r===fs||r===ms?"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,s)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,he)}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 s;const r=this.getAppendedFrag(e.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.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],r=this.fragLastKbps;s=r&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*r)+1:0}else s=0;const n=this.getBufferedFrag(e.currentTime+s);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,r=Math.max(n.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,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 Is:case _s:case Ms:case Fs:case Os:this.state=Ps}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),s.addEventListener("playing",this.onvplaying),s.addEventListener("seeked",this.onvseeked),this.gapController=new GapController(this.config,s,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;l(e)&&this.log("Media seeked to "+e.toFixed(3));const s=this.getMainFwdBufferInfo();null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${s?s.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(c.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 s=!1,r=!1;e.levels.forEach(t=>{const e=t.audioCodec;e&&(s=s||-1!==e.indexOf("mp4a.40.2"),r=r||-1!==e.indexOf("mp4a.40.5"))}),this.audioCodecSwitch=s&&r&&!function(){var t;const e=zi();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:s}=this;if(!s||this.state!==Ps)return;const r=s[e.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=$s)}onLevelLoaded(t,e){var s;const{levels:r}=this,i=e.level,n=e.details,a=n.totalduration;if(!r)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=r[i],l=this.fragCurrent;!l||this.state!==_s&&this.state!==Ms||l.level!==e.level&&l.loader&&this.abortCurrentFrag();let h=0;if(n.live||null!=(s=o.details)&&s.live){var d;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(c.LEVEL_UPDATED,{details:n,level:i}),this.state===$s){if(this.waitForCdnTuneIn(n))return;this.state=Ps}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:s,part:r,payload:i}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=s.initSegment)?void 0:e.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,he,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,i.byteLength,f,g),p=this.initPTS[s.cc];u.push(i,d,c,l,s,r,o.totalduration,h,m,p)}onAudioTrackSwitching(t,e){const s=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;s&&(t.trigger(c.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(c.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=e.id,r=!!this.hls.audioTracks[s].url;if(r){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=r,this.tick()}onBufferCreated(t,e){const s=e.tracks;let r,i,n=!1;for(const t in s){const e=s[t];if("main"===e.id){if(i=t,r=e,"video"===t){const e=s[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&r?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:r}=e;if(s&&s.type!==he)return;if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Os&&(this.state=Ps));const i=r?r.stats:s.stats;this.fragLastKbps=Math.round(8*i.total/(i.buffering.end-i.loading.first)),"initSegment"!==s.sn&&(this.fragPrevious=s),this.fragBufferedComplete(s,r)}onError(t,e){var s;if(e.fatal)this.state=Us;else switch(e.details){case f.FRAG_GAP:case f.FRAG_PARSING_ERROR:case f.FRAG_DECRYPT_ERROR:case f.FRAG_LOAD_ERROR:case f.FRAG_LOAD_TIMEOUT:case f.KEY_LOAD_ERROR:case f.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(he,e);break;case f.LEVEL_LOAD_ERROR:case f.LEVEL_LOAD_TIMEOUT:case f.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==$s||(null==(s=e.context)?void 0:s.type)!==ae||(this.state=Ps);break;case f.BUFFER_APPEND_ERROR:case f.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;if(e.details===f.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case f.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}checkBuffer(){const{media:t,gapController:e}=this;if(t&&e&&t.readyState){if(this.loadedmetadata||!BufferHelper.getBuffered(t).length){const t=this.state!==Ps?this.fragCurrent:null;e.poll(this.lastCurrentTime,t)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=Ps,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==L||this.audioOnly&&!this.altAudio){const t=(e===A?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(t,e,he),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 s=this.startPosition;if(s>=0&&e<s){if(t.seeking)return void this.log(`could not seek to ${s}, already seeking at ${e}`);const r=BufferHelper.getBuffered(t),i=(r.length?r.start(0):0)-s;i>0&&(i<this.config.maxBufferHole||i<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${i} to match buffer start`),s+=i,this.startPosition=s),this.log(`seek to target start position ${s} from current time ${e}`),t.currentTime=s}}_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(s=>{const{hls:r}=this;if(!s||this.fragContextChanged(t))return;e.fragmentError=0,this.state=Ps,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(),r.trigger(c.FRAG_LOADED,s),t.bitrateTest=!1})}_handleTransmuxComplete(t){var e;const s="main",{hls:r}=this,{remuxResult:i,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:h,level:d}=a,{video:u,text:f,id3:g,initSegment:m}=i,{details:p}=d,y=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Fs,m){if(null!=m&&m.tracks){const t=o.initSegment||o;this._bufferInitSegment(d,m.tracks,t,n),r.trigger(c.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:m.tracks})}const t=m.initPTS,e=m.timescale;l(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:e},r.trigger(c.INIT_PTS_FOUND,{frag:o,id:s,initPTS:t,timescale:e}))}if(u&&p&&"initSegment"!==o.sn){const t=p.fragments[o.sn-1-p.startSN],e=o.sn===p.startSN,s=!t||o.cc>t.cc;if(!1!==i.independent){const{startPTS:t,endPTS:r,startDTS:i,endDTS:a}=u;if(h)h.elementaryStreams[u.type]={startPTS:t,endPTS:r,startDTS:i,endDTS:a};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!s&&(this.couldBacktrack=!0),u.dropped&&u.independent){const i=this.getMainFwdBufferInfo(),n=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,l=u.firstKeyFramePTS?u.firstKeyFramePTS:t;if(!e&&n<l-this.config.maxBufferHole&&!s)return void this.backtrack(o);s&&(o.gap=!0),o.setElementaryStreamInfo(u.type,o.start,r,o.start,a,!0)}else e&&t>2&&(o.gap=!0);o.setElementaryStreamInfo(u.type,t,r,i,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,h,n,e||s)}else{if(!e&&!s)return void this.backtrack(o);o.gap=!0}}if(y){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=y;h&&(h.elementaryStreams[L]={startPTS:t,endPTS:e,startDTS:s,endDTS:r}),o.setElementaryStreamInfo(L,t,e,s,r),this.bufferFragmentData(y,o,h,n)}if(p&&null!=g&&null!=(e=g.samples)&&e.length){const t={id:s,frag:o,details:p,samples:g.samples};r.trigger(c.FRAG_PARSING_METADATA,t)}if(p&&f){const t={id:s,frag:o,details:p,samples:f.samples};r.trigger(c.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,s,r){if(this.state!==Fs)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 s=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(e&&(e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==i.metadata.channelCount&&-1===s.indexOf("firefox")&&(e="mp4a.40.5")),e&&-1!==e.indexOf("mp4a.40.5")&&-1!==s.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(c.BUFFER_CODECS,e),Object.keys(e).forEach(t=>{const i=e[t].initSegment;null!=i&&i.byteLength&&this.hls.trigger(c.BUFFER_APPENDING,{type:t,data:i,frag:s,part:null,chunkMeta:r,parent:s.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,he)}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=Ps}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(BufferHelper.isBuffered(t,s)?e=this.getAppendedFrag(s):BufferHelper.isBuffered(t,s+.1)&&(e=this.getAppendedFrag(s+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,s=e.level;t&&e.sn===t.sn&&t.level===s||(this.fragPlaying=e,this.hls.trigger(c.FRAG_CHANGED,{frag:e}),t&&t.level===s||this.hls.trigger(c.LEVEL_SWITCHED,{level:s}))}}}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,s=this.currentFrag;if(s&&l(e)&&l(s.programDateTime)){const t=s.programDateTime+1e3*(e-s.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 Hls{static get version(){return"1.5.8"}static isMSESupported(){return Qi()}static isSupported(){return function(){if(!Qi())return!1;const t=Ot();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($t(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported($t(e,"audio"))))}()}static getMediaSource(){return Ot()}static get Events(){return c}static get ErrorTypes(){return u}static get ErrorDetails(){return f}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:Yi}static set DefaultConfig(t){Hls.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 wr,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){y(t,"debug","log","info","warn","error");try{p.log(`Debug logs enabled for "${e}" in hls.js version 1.5.8`)}catch(t){p=m}}else p=m}(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 s=Wi(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const i=("level"===t?"playlist":t)+"LoadPolicy",n=void 0===e[i],a=[];r.forEach(r=>{const o=`${t}Loading${r}`,l=e[o];if(void 0!==l&&n){a.push(o);const t=s[i].default;switch(e[i]={default:t},r){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}}),a.length&&v.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${i}": ${JSON.stringify(e[i])}`)}),i(i({},s),e)}(Hls.DefaultConfig,t);this.userConfig=t,e.progressive&&ji(e);const{abrController:s,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=e,l=new a(this),h=this.abrController=new s(this),d=this.bufferController=new r(this),u=this.capLevelController=new n(this),f=new o(this),g=new PlaylistLoader(this),E=new ID3TrackController(this),T=e.contentSteeringController,S=T?new T(this):null,L=this.levelController=new LevelController(this,S),A=new FragmentTracker(this),R=new KeyLoader(this.config),b=this.streamController=new StreamController(this,A,R);u.setStreamController(b),f.setStreamController(b);const k=[g,L,b];S&&k.splice(1,0,S),this.networkControllers=k;const D=[h,d,u,f,E,A];this.audioTrackController=this.createController(e.audioTrackController,k);const C=e.audioStreamController;C&&k.push(new C(this,A,R)),this.subtitleTrackController=this.createController(e.subtitleTrackController,k);const w=e.subtitleStreamController;w&&k.push(new w(this,A,R)),this.createController(e.timelineController,D),R.emeController=this.emeController=this.createController(e.emeController,D),this.cmcdController=this.createController(e.cmcdController,D),this.latencyController=this.createController(LatencyController,D),this.coreComponents=D,k.push(l);const P=l.onErrorOut;"function"==typeof P&&this.on(c.ERROR,P,l)}createController(t,e){if(t){const s=new t(this);return e&&e.push(s),s}return null}on(t,e,s=this){this._emitter.on(t,e,s)}once(t,e,s=this){this._emitter.once(t,e,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,s=this,r){this._emitter.off(t,e,s,r)}listeners(t){return this._emitter.listeners(t)}emit(t,e,s){return this._emitter.emit(t,e,s)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(v.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const s=t===c.ERROR;this.trigger(c.ERROR,{type:u.OTHER_ERROR,details:f.INTERNAL_EXCEPTION,fatal:s,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){v.log("destroy"),this.trigger(c.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){v.log("attachMedia"),this._media=t,this.trigger(c.MEDIA_ATTACHING,{media:t})}detachMedia(){v.log("detachMedia"),this.trigger(c.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,r=this.url,i=this.url=s.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,v.log("loadSource:"+i),e&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(c.MANIFEST_LOADING,{url:t})}startLoad(t=-1){v.log(`startLoad(${t})`),this.started=!0,this.networkControllers.forEach(e=>{e.startLoad(t)})}stopLoad(){v.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(){v.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){v.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){v.log("set currentLevel:"+t),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){v.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){v.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){v.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){v.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&&(v.log("set autoLevelCapping:"+t),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return ke.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 s=t.length;for(let r=0;r<s;r++)if(t[r].maxBitrate>=e)return r;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let r;if(r=-1===e&&null!=t&&t.length?t.length-1:e,s)for(let e=r;e--;){const r=t[e].attrs["HDCP-LEVEL"];if(r&&r<=s)return e}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}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}}Hls.defaultConfig=void 0;var Ji=Object.freeze({__proto__:null,ATTACHED:"hls:attached",BUFFER_CHECK_TICK:"hls:buffer_check"});function Zi(t){const e=function(){const t="undefined"!=typeof document&&"undefined"!=typeof window,e=t?navigator.userAgent:"",s=/iP(hone|od)/i.test(e)&&!/iPad/.test(e)&&!/IEMobile/i.test(e),r=/Android/.test(e)&&!/Firefox/.test(e),i=/^((?!chrome|android).)*safari/i.test(e),n=/chrome|crios/i.test(e)&&!/opr|opera|chromium|edg|ucbrowser|googlebot/i.test(e),a=/firefox|fxios/i.test(e)&&!/seamonkey/i.test(e),o=/edg/i.test(e),l=/opr|opera/i.test(e),h=/SamsungBrowser/.test(e),d=h&&/SMART-TV/.test(e);return{controls:!s,video:function(e){return t&&document.createElement("video").canPlayType(e)},lang:t&&window.navigator.language,android:r,iphone:s,safari:i,edge:o,opera:l,chrome:n,firefox:a,ios:t&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,samsung:h,samsung_tv:h&&d,touch:"ontouchstart"in window,tizen:"tizen"in window,webOS:"webos"in window}}();switch(t){case"com.widevine.alpha":return e.chrome||e.firefox||e.edge||e.opera;case"org.w3.clearkey":return e.chrome||e.firefox;case"com.apple.fps.1_0":return e.safari;case"com.microsoft.playready":return e.edge}}const tn="application/vnd.apple.mpegURL",en=[tn,"application/x-mpegurl"],sn=document.createElement("video").canPlayType(tn);function rn(t){const{pathname:e}=function(t){const e=document.createElement("a");return e.href=t,e}(t);return e.endsWith(".m3u8")}const nn=window&&window.Hls||Hls;function an(t,e){const s=function(){try{return localStorage.getItem("flowplayer/debug")}catch(t){return""}}(),r=(r,...i)=>{try{const n=(null==e?void 0:e.debug)||s;n&&t.match(n)&&console.log(`flowplayer/${t} -- ${r}`,...i)}catch(t){console.warn(t)}};return r.log=r,r}var on;!function(t){t[t.FRAGMENT_ERRORS=0]="FRAGMENT_ERRORS",t[t.STALE_MANIFEST=1]="STALE_MANIFEST"}(on||(on={}));const ln=an("hls:failover");class FailoverLoaderController{constructor(){this.playlistCounts={},this.fragmentFailures={},this.ttlMilliseconds=3e3}setHls(t){this.hls=t}reset(){return this.playlistCounts={},this.fragmentFailures={},this}failover(t){var e,s;this.reset();const r=this.hls;if(!r)return;const i=r.levelController,n=r.streamController,a=i.steering;if(!i||!n||!a)return;const o=i.currentLevel;if(!o)return;const l=a.levels.filter(t=>t.pathwayId!==o.pathwayId);l.length&&(null===(e=r.media)||void 0===e||e.dispatchEvent(new CustomEvent("hls/failover",{detail:{reason:t,from:null===(s=o.details)||void 0===s?void 0:s.url}})),i._levels=n.levels=l)}currentLevel(){var t;return null===(t=this.hls)||void 0===t?void 0:t.levels[this.hls.currentLevel]}nextTTL(){var t;const e=Date.now()+this.ttlMilliseconds,s=this.currentLevel();if(!s)return e;const r=null===(t=s.details)||void 0===t?void 0:t.averagetargetduration;return r?Date.now()+500*r:e}ensurePlaylistUpdating(t,e){this.playlistCounts[t]||(this.playlistCounts[t]={checksum:e,count:0,ttl:this.nextTTL()});const s=this.playlistCounts[t];Date.now()<s.ttl||(s.count=s.checksum===e?s.count+1:0,s.ttl=this.nextTTL(),s.checksum=e,s.count<3||(ln(`${t} / no change in ${s.count} tries`,this.playlistCounts),this.failover(on.STALE_MANIFEST)))}trackFragmentError(t){const e=this.fragmentFailures[t]||0;this.fragmentFailures[t]=e+1,this.fragmentFailures[t]>2&&this.failover(on.FRAGMENT_ERRORS)}createPlaylistLoader(t){const e=this;return class extends Hls.DefaultConfig.loader{load(s,r,i){const n=i.onSuccess;i.onSuccess=({data:r,url:i},...a)=>{"manifest"===(null==s?void 0:s.type)&&(t.manifest=r),e.ensurePlaylistUpdating(i,r),n({data:r,url:i},...a)},super.load(s,r,i)}}}createFragmentLoader(){const t=this;return class extends Hls.DefaultConfig.loader{load(e,s,r){const i=r.onError;r.onError=e=>{t.trackFragmentError(e.url),i(...arguments)},super.load(e,s,r)}}}}const hn={Unknown:"00-00",MediaUnknown:"01-00",MediaUnavailable:"01-01",MediaUnsupportedVideoFormat:"01-02",MediaUnsupportedAudioFormat:"01-03",MediaBitrateExceeded:"01-04",MediaBufferOverread:"01-05",MediaIntegerOverflow:"01-06",MediaQuotaExceeded:"01-07",MediaInvalidCompositionDuration:"01-08",MediaInvalidCompositionSourceDuration:"01-09",MediaInvalidCompositionSourceStartTime:"01-10",MediaMalformedDepth:"01-11",PlaybackUnknown:"02-00",PlaybackVideoBufferUnderRun:"02-01",PlaybackAudioBufferUnderRun:"02-02",PlaybackVideoBufferingTimeout:"02-03",PlaybackAudioBufferingTimeout:"02-04",PlaybackManifestParseError:"02-05",PlaybackVideoDecodeError:"02-06",PlaybackAudioDecodeError:"02-07",PlaybackDroppedFramesExceeded:"02-08",PlaybackPlayheadExceedsDuration:"02-09",PlaybackUnsupportedDevice:"02-10",PlaybackManifestLoadError:"02-11",PlaybackManifestLoadTimeout:"02-12",PlaybackManifestParsingError:"02-13",PlaybackManifestIncompatibleCodecs:"02-14",PlaybackLevelEmptyError:"02-15",PlaybackLevelLoadError:"02-16",PlaybackLevelLoadTimeout:"02-17",PlaybackLevelSwitchError:"02-18",PlaybackAudioTrackLoadError:"02-19",PlaybackAudioTrackLoadTimeout:"02-20",PlaybackFragLoadError:"02-21",PlaybackFragLoadTimeout:"02-22",PlaybackFragDecryptError:"02-23",PlaybackFragParsingError:"02-24",PlaybackFragGap:"02-25",PlaybackRemuxAllocError:"02-26",PlaybackBufferAddCodecError:"02-27",PlaybackBufferIncompatibleCodecs:"02-28",PlaybackBufferAppendError:"02-29",PlaybackBufferStalledError:"02-30",PlaybackBufferFullError:"02-31",PlaybackBufferSeekOverHole:"02-32",PlaybackBufferNudgeOnStall:"02-33",PlaybackInternalException:"02-34",PlaybackInternalAborted:"02-35",PlaybackManifestLoaderFailure:"02-36",PlaybackSegmentBaseLoaderError:"02-37",PlaybackTimeSyncFailed:"02-38",PlaybackFragmentLoaderFailure:"02-39",PlaybackAppendError:"02-40",PlaybackRemoveError:"02-41",PlaybackDataUpdateFailed:"02-42",PlaybackManifestNoStreams:"02-43",PlaybackUnknownManifestType:"02-44",PlaybackDashInsufficientSegmentInfo:"02-45",PlaybackDashNoRepresentations:"02-46",PlaybackDashNoAdaptationSets:"02-47",PlaybackDashNoInitSegment:"02-48",PlaybackDashUnsupportedContainerFormat:"02-49",PlaybackDashKeySystemMismatch:"02-50",PlaybackMultipleKeyIDs:"02-51",PlaybackDashConflictingKeyIDs:"02-52",PlaybackRestrictedStreams:"02-53",PlaybackHlsMasterAndMediaTags:"02-54",PlaybackRepresentationIdConflict:"02-55",PlaybackHlsUnsupportedKeyFormats:"02-56",PlaybackManifestNoVariants:"02-57",PlaybackHlsUndeclaredVariables:"02-58",PlaybackAes128InvalidKeyLength:"02-59",PlaybackDashConflictingAes128Keys:"02-60",PlaybackDashUnsupportedAes128Encryption:"02-61",PlaybackManifestPatchMismatch:"02-62",PlaybackEmptyMediaPlaylist:"02-63",PlaybackNonContiguousCompositionTrack:"02-64",PlaybackDecoderNotFound:"02-65",PlaybackDecoderTemporarilyUnavailable:"02-66",PlaybackIncompatibleAsset:"02-67",PlaybackNoCompatibleExternalDisplay:"02-69",PlaybackOutOfMemory:"02-70",PlaybackToneMappingFailed:"02-71",PlaybackVideoCompositorFailed:"02-72",NetworkUnknown:"03-00",NetworkNoInternet:"03-01",NetworkRequestTimeout:"03-02",NetworkUnableToResolveHost:"03-03",NetworkResourceNotFound:"03-04",NetworkExpiredUrl:"03-05",NetworkUrlResolutionFailed:"03-06",NetworkDownloadErrorIdManifest:"03-07",NetworkDownloadErrorIdSidx:"03-08",NetworkDownloadErrorIdContent:"03-09",NetworkDownloadErrorIdInitialization:"03-10",NetworkDownloadErrorIdXlink:"03-11",NetworkHttpRequestFailed:"03-12",NetworkMaxRetriesExceeded:"03-13",NetworkSegmentMissing:"03-14",NetworkHttp400BadRequest:"03-400",NetworkHttp401Unauthorized:"03-401",NetworkHttp402PaymentRequired:"03-402",NetworkHttp403Forbidden:"03-403",NetworkHttp404NotFound:"03-404",NetworkHttp405MethodNotAllowed:"03-405",NetworkHttp406NotAcceptable:"03-406",NetworkHttp407ProxyAuthenticationRequired:"03-407",NetworkHttp408RequestTimeout:"03-408",NetworkHttp409Conflict:"03-409",NetworkHttp410Gone:"03-410",NetworkHttp411LengthRequired:"03-411",NetworkHttp412PreconditionFailed:"03-412",NetworkHttp413PayloadTooLarge:"03-413",NetworkHttp414URITooLong:"03-414",NetworkHttp415UnsupportedMediaType:"03-415",NetworkHttp416RangeNotSatisfiable:"03-416",NetworkHttp417ExpectationFailed:"03-417",NetworkHttp418ImATeapot:"03-418",NetworkHttp421MisdirectedRequest:"03-421",NetworkHttp422UnprocessableEntity:"03-422",NetworkHttp423Locked:"03-423",NetworkHttp424FailedDependency:"03-424",NetworkHttp425TooEarly:"03-425",NetworkHttp426UpgradeRequired:"03-426",NetworkHttp428PreconditionRequired:"03-428",NetworkHttp429TooManyRequests:"03-429",NetworkHttp431RequestHeaderFieldsTooLarge:"03-431",NetworkHttp451UnavailableForLegalReasons:"03-451",NetworkHttp500InternalServerError:"03-500",NetworkHttp501NotImplemented:"03-501",NetworkHttp502BadGateway:"03-502",NetworkHttp503ServiceUnavailable:"03-503",NetworkHttp504GatewayTimeout:"03-504",NetworkHttp505HTTPVersionNotSupported:"03-505",NetworkHttp506VariantAlsoNegotiates:"03-506",NetworkHttp507InsufficientStorage:"03-507",NetworkHttp508LoopDetected:"03-508",NetworkHttp510NotExtended:"03-510",NetworkHttp511NetworkAuthenticationRequired:"03-511",ContentProtectionUnknown:"04-00",ContentProtectionConcurrentStreamLimitExceeded:"04-01",ContentProtectionEntitlementRefused:"04-02",ContentProtectionLicenseExpired:"04-03",ContentProtectionBadLicenseRequest:"04-04",ContentProtectionLicenseServerTimeout:"04-05",ContentProtectionInsufficientHDCPSupport:"04-06",ContentProtectionGeoRestricted:"04-07",ContentProtectionParentalControlRestricted:"04-08",ContentProtectionCDNUnauthorized:"04-09",ContentProtectionInvalidAccessToken:"04-10",ContentProtectionKeySystemNoKeys:"04-11",ContentProtectionKeySystemNoAccess:"04-12",ContentProtectionKeySystemNoSession:"04-13",ContentProtectionKeySystemNoConfiguredLicense:"04-14",ContentProtectionKeySystemCertificateRequestFailed:"04-15",ContentProtectionKeySystemCertificateUpdateFailed:"04-16",ContentProtectionKeySystemSessionUpdateFailed:"04-17",ContentProtectionKeySystemStatusOutputRestricted:"04-18",ContentProtectionKeySystemStatusInternalError:"04-19",ContentProtectionKeyLoadError:"04-20",ContentProtectionKeyLoadTimeout:"04-21",ContentProtectionCapabilityMediaKeysError:"04-22",ContentProtectionManifestKeySystemUnknown:"04-23",ContentProtectionKeySystemUnavailable:"04-24",ContentProtectionCDMCreationFailed:"04-25",ContentProtectionCDMAttachFailed:"04-26",ContentProtectionCDMServerCertificateRejected:"04-27",ContentProtectionCDMSessionCreationFailed:"04-28",ContentProtectionCDMLicenseRequestFailed:"04-29",ContentProtectionCDMLicenseResponseRejected:"04-30",ContentProtectionManifestMissingDRMInfo:"04-31",ContentProtectionLicenseServerMissing:"04-32",ContentProtectionOfflineSessionRemoved:"04-33",ContentProtectionInitDataTransformationError:"04-34",ContentProtectionServerCertificateRequestFailed:"04-35",ContentProtectionInsufficientHDCPVersion:"04-36",ContentProtectionHDCPVersionCheckFailed:"04-37",AdsUnknown:"08-00",AdsVastParseError:"08-100",AdsInvalidVastSchema:"08-101",AdsVastVersionNotSupported:"08-102",AdsUnexpectedAdType:"08-200",AdsCreativeLinearityMismatch:"08-201",AdsCreativeDurationMismatch:"08-202",AdsCreativeSizeMismatch:"08-203",AdsWrapperVastError:"08-300",AdsVastResponseRedirectTimeout:"08-301",AdsWrapperLimitReached:"08-302",AdsVastResponseEmpty:"08-303",AdsLinearAdDisplayError:"08-400",AdsMediaFileNotFound:"08-401",AdsMediaFileUnavailable:"08-402",AdsUnsupportedMimeType:"08-403",AdsUnableToDisplayMediaFile:"08-405",AdsMezzanineFileMissing:"08-406",AdsMezzanineFileDownloaded:"08-407",AdsRejectedAd:"08-408",AdsInteractiveCreativeError:"08-409",AdsVerificationNodeExecutionError:"08-410",AdsNonLinearAdDisplayError:"08-500",AdsNonLinearAdSizeMismatch:"08-501",AdsNonLinearAdFetchError:"08-502",AdsNonLinearUnsupportedType:"08-503",AdsCompanionAdDisplayError:"08-600",AdsCompanionAdSizeMismatch:"08-601",AdsRequiredCompanionAdError:"08-602",AdsCompanionAdFetchError:"08-603",AdsUndefinedVastError:"08-900",AdsUnknownVpaidError:"08-901",AdsVastDocumentEmpty:"08-999"},dn=Object.fromEntries(Object.entries(hn).map(([t,e])=>[e,t])),cn=[1e7]+""+-1e3+-4e3+-8e3+-1e11,un="on",fn="off";class FlowplayerError extends Error{static getErrorKey(t){return t in dn?dn[t]:dn["00-00"]}constructor(t,e,s={}){super(t),this.message=t,this.flowplayerErrorCode=e,this.config=s,this.id="undefined"==typeof crypto?"":cn.replace(/[018]/g,t=>(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)),this.isFatal=!!s.isFatal,this.errorKey=FlowplayerError.getErrorKey(this.flowplayerErrorCode)||"unknown"}toJSON(){return{message:this.message,flowplayer_error_code:this.flowplayerErrorCode,id:this.id,root_error_id:this.config.rootErrorId,resource:this.config.resource,is_fatal:this.isFatal,is_retry:!!this.config.isRetry}}}const gn=an("hls");function mn(t){switch(t){case f.KEY_SYSTEM_NO_KEYS:return hn.ContentProtectionKeySystemNoKeys;case f.KEY_SYSTEM_NO_ACCESS:return hn.ContentProtectionKeySystemNoAccess;case f.KEY_SYSTEM_NO_SESSION:return hn.ContentProtectionKeySystemNoSession;case f.KEY_SYSTEM_NO_CONFIGURED_LICENSE:return hn.ContentProtectionKeySystemNoConfiguredLicense;case f.KEY_SYSTEM_LICENSE_REQUEST_FAILED:return hn.ContentProtectionCDMLicenseRequestFailed;case f.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED:return hn.ContentProtectionServerCertificateRequestFailed;case f.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED:return hn.ContentProtectionKeySystemCertificateUpdateFailed;case f.KEY_SYSTEM_SESSION_UPDATE_FAILED:return hn.ContentProtectionKeySystemSessionUpdateFailed;case f.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return hn.ContentProtectionKeySystemStatusOutputRestricted;case f.KEY_SYSTEM_STATUS_INTERNAL_ERROR:return hn.ContentProtectionKeySystemStatusInternalError;case f.MANIFEST_LOAD_ERROR:return hn.PlaybackManifestLoadError;case f.MANIFEST_LOAD_TIMEOUT:return hn.PlaybackManifestLoadTimeout;case f.MANIFEST_PARSING_ERROR:return hn.PlaybackManifestParsingError;case f.MANIFEST_INCOMPATIBLE_CODECS_ERROR:return hn.PlaybackManifestIncompatibleCodecs;case f.LEVEL_EMPTY_ERROR:return hn.PlaybackLevelEmptyError;case f.LEVEL_LOAD_ERROR:return hn.PlaybackLevelLoadError;case f.LEVEL_LOAD_TIMEOUT:return hn.PlaybackLevelLoadTimeout;case f.LEVEL_PARSING_ERROR:return hn.PlaybackManifestParsingError;case f.LEVEL_SWITCH_ERROR:return hn.PlaybackLevelSwitchError;case f.AUDIO_TRACK_LOAD_ERROR:return hn.PlaybackAudioTrackLoadError;case f.AUDIO_TRACK_LOAD_TIMEOUT:return hn.PlaybackAudioTrackLoadTimeout;case f.SUBTITLE_LOAD_ERROR:return hn.NetworkDownloadErrorIdContent;case f.SUBTITLE_TRACK_LOAD_TIMEOUT:return hn.NetworkRequestTimeout;case f.FRAG_LOAD_ERROR:return hn.PlaybackFragLoadError;case f.FRAG_LOAD_TIMEOUT:return hn.PlaybackFragLoadTimeout;case f.FRAG_DECRYPT_ERROR:return hn.PlaybackFragDecryptError;case f.FRAG_PARSING_ERROR:return hn.PlaybackFragParsingError;case f.FRAG_GAP:return hn.PlaybackFragGap;case f.REMUX_ALLOC_ERROR:return hn.PlaybackRemuxAllocError;case f.KEY_LOAD_ERROR:return hn.ContentProtectionKeyLoadError;case f.KEY_LOAD_TIMEOUT:return hn.ContentProtectionKeyLoadTimeout;case f.BUFFER_ADD_CODEC_ERROR:return hn.PlaybackBufferAddCodecError;case f.BUFFER_INCOMPATIBLE_CODECS_ERROR:return hn.PlaybackBufferIncompatibleCodecs;case f.BUFFER_APPEND_ERROR:return hn.PlaybackBufferAppendError;case f.BUFFER_APPENDING_ERROR:return hn.PlaybackAppendError;case f.BUFFER_STALLED_ERROR:return hn.PlaybackBufferStalledError;case f.BUFFER_FULL_ERROR:return hn.PlaybackBufferFullError;case f.BUFFER_SEEK_OVER_HOLE:return hn.PlaybackBufferSeekOverHole;case f.BUFFER_NUDGE_ON_STALL:return hn.PlaybackBufferNudgeOnStall;case f.INTERNAL_EXCEPTION:return hn.PlaybackInternalException;case f.INTERNAL_ABORTED:return hn.PlaybackInternalAborted;case f.UNKNOWN:default:return hn.Unknown}}function pn(t,e,s){const r={},i={error_type:e.type,resource:e.url||t.original_src,isFatal:e.fatal};return e.fatal?(e.type===s.ErrorTypes.MEDIA_ERROR&&(i.showErrorUI=!1,r.retry=un,r.retryTimeout=0),[s.ErrorTypes.KEY_SYSTEM_ERROR,s.ErrorTypes.MUX_ERROR,s.ErrorTypes.OTHER_ERROR].includes(e.type)&&(r.retry=fn),Object.assign(i,{retryOpts:r})):(r.retry=fn,Object.assign(i,{retryOpts:r}))}function yn(t,e){e.on(nn.Events.ERROR,(function(e,s){var r;0!=t.reaper&&(!function(t,e,s){t.emit("flowplayer:error",{error:new FlowplayerError(e.error.message,mn(e.details),pn(t,e,s))})}(t,s,nn),s.fatal&&([nn.ErrorTypes.NETWORK_ERROR,nn.ErrorTypes.MEDIA_ERROR].includes(s.type)||null===(r=t.hls)||void 0===r||r.destroy()))}))}function vn(t,e){const s=t.seekable;if("object"!=typeof t.opts||0==s.length)return{head:0,tail:0};const r=function(t){var e;const s=t.seekable;return s.length?t.hasState("is-chromecast-playing")||!(null===(e=t.hls)||void 0===e?void 0:e.liveSyncPosition)?s.end(s.length-1):t.hls.liveSyncPosition:0}(t),i=e||t.live_state.dvr_window;return{head:r,tail:"number"!=typeof i||r-i<0?s.start(0):r-i}}function En(t,e){var s;!t.hasState("is-loaded")&&t.setState("is-loading",!0),null===(s=t.hls)||void 0===s||s.startLoad(e)}function Tn(t){t.on("remotesession:started",()=>{t.hls&&(t.hls.stopLoad(),delete t.opts.start_time)}),t.on("remotesession:ended",e=>{var s;if(!t.hls)return;if(!t.opts.live)return En(t,e.detail.currentTime);e.preventDefault();const r=function(t){const e=t.currentTime,s=vn(t);return{progress:Math.min(100,Math.max(0,(e-s.tail)/(s.head-s.tail)*100)),is_live:e-s.head>=-10}}(t).progress,i=t.hls;null===(s=t.hls)||void 0===s||s.once(nn.Events.LEVEL_LOADED,()=>{if(t.hls!==i)return;const e=t.live_state.dvr_window||0,s=(null==i?void 0:i.liveSyncPosition)||t.seekable.end(0);if(t.hasState("no-timeline")||isNaN(r))return t.currentTime=s;t.currentTime=s-e*((100-r)/100)}),En(t)})}var Sn;function Ln(t,e){if("object"==typeof t&&"object"==typeof e&&"number"==typeof t.bitrate&&"number"==typeof e.bitrate)return t.bitrate<e.bitrate}function An(t){const e=t.map((t,e)=>Object.assign(t,{level:e})).sort((t,e)=>e.width-t.width);return t.length>1&&t.every(t=>void 0!==t.bitrate)&&e.push({name:"AUTO",level:-1,width:0,height:0}),e}function Rn(t,e,s,r,i){let n;t.once(Hls.Events.LEVEL_LOADING,(function(){e.emit("content:loadstart")})),t.on(nn.Events.MANIFEST_PARSED,(function(t,n){const a=An(n.levels);e.emit("qualities",a),e.emit("parse:video:tracks",{url:i.src,manifest:r.manifest}),function(t,e,s){if(!t.hls)return;gn("Initializer::maybe_start_load_with_quality (start_quality, preload): (%d, %s)",e.start_quality,e.preload),void 0!==e.start_quality&&s.length&&(Sn.HIGH&e.start_quality&&(t.hls.startLevel=s[0].level),Sn.LOW&e.start_quality&&(t.hls.startLevel=s[s.length-1].level),Sn.MEDIUM&e.start_quality&&(t.hls.startLevel=s[Math.ceil(s.length/2)-1].level));(function(t,e){var s,r,i,n,a,o;if(!e.hls)return;if(null===(s=t.hls)||void 0===s?void 0:s.adaptive_buffer_control){const s=10,r=10,i=!0!==t.hls.adaptive_buffer_control&&t.hls.adaptive_buffer_control.initial_buffer_length?t.hls.adaptive_buffer_control.initial_buffer_length:s,l=!0!==(null===(n=t.hls)||void 0===n?void 0:n.adaptive_buffer_control)&&t.hls.adaptive_buffer_control.restore_buffer_player_time_threshold?null===(a=t.hls)||void 0===a?void 0:a.adaptive_buffer_control.restore_buffer_player_time_threshold:r;!function(t,e){var s;const r=null===(s=t.hls)||void 0===s?void 0:s.config.maxBufferLength;let i=!1;const n=setInterval(()=>{t.emit("hls:buffer_check")},500),a=()=>{i||t.currentTime>e&&(i=!0,t.hls&&r&&(t.hls.config.maxBufferLength=r))};t.on("src",()=>{clearInterval(n),t.off("hls:buffer_check",a)}),t.on("hls:buffer_check",a)}(e,l),bn(t,e,{maxBufferLength:i,maxBufferSize:null===(o=t.hls)||void 0===o?void 0:o.maxBufferSize})}else bn(t,e,{maxBufferLength:null===(r=t.hls)||void 0===r?void 0:r.maxBufferLength,maxBufferSize:null===(i=t.hls)||void 0===i?void 0:i.maxBufferSize})})(e,t),("none"!==e.preload||e.autoplay&&t.hasState("is-in-viewport"))&&En(t,e.start_time||-1)}(e,s,a.slice(0,-1))})),t.on(nn.Events.LEVEL_SWITCHING,(s,r)=>{if(t.nextLoadLevel===n)return;n=t.nextLoadLevel;const i=t.levels[t.currentLevel],a=t.levels[r.level];e.emit("qualitychange",{before:i,after:a,plugin:"hls",automatic:t.autoLevelEnabled,downscale:Ln(a,i)})})}function bn(t,e,s){if(!e.hls)return;const r=(null==s?void 0:s.maxBufferSize)||1024,i=(null==s?void 0:s.maxBufferLength)||30;gn("Setting maxBufferSize to %d",r),e.hls.config.maxBufferSize=r,"metadata"===t.preload&&gn("preload === metadata, setting maxBufferLength to 1sec"),e.hls.config.maxBufferLength="metadata"===t.preload?1:i,e.once("playing",()=>{gn("Playback started, set maxBufferLenght to %d",i),e.hls&&(e.hls.config.maxBufferLength=i)})}!function(t){t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=4]="HIGH"}(Sn||(Sn={}));function kn(t,e,s,r,i){!function(t,e){t.on(Hls.Events.AUDIO_TRACKS_UPDATED,(function(t,s){e.emit("audio:tracks",s.audioTracks)})),t.on(Hls.Events.AUDIO_TRACK_SWITCHING,(function(t,s){e.emit("audio:update",s)})),t.on(Hls.Events.MANIFEST_PARSED,(function(t,s){s.audioTracks&&e.emit("audio:tracks",s.audioTracks)}))}(t,r),function(t,e){t.on(Hls.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(s,r)=>{t.subtitleTracks.length||e.emit("tracks:text:all",r)}),t.on(Hls.Events.SUBTITLE_TRACKS_UPDATED,(t,s)=>{e.emit("tracks:text:all",{tracks:s.subtitleTracks.map(t=>Object.assign({},{subtitleTrack:t}))})}),t.on(Hls.Events.CUES_PARSED,(t,s)=>{e.emit("cues:parsed",s)})}(t,r),yn(r,t),Rn(t,r,e,s,i),function(t,e){t.on(Hls.Events.FRAG_PARSING_METADATA,(function(t,s){e.emit("ssai:hls:metadata",s)}))}(t,r),function(t,e){t.on(Hls.Events.BUFFER_CREATED,(t,s)=>{const r=s.tracks.video||s.tracks.audiovideo;if(!r)return e.emit("audioonlysource");const i=null==r?void 0:r.metadata.height,n=null==r?void 0:r.metadata.width;!e.opt("ratio")&&i&&n&&e.setOpts({ratio:n+":"+i})})}(t,r),function(t,e,s){const r="live"in s==0;e.on(nn.Events.LEVEL_LOADED,(function(s,i){var n,a,o,l,h;r&&t.setOpts({live:null===(n=null==i?void 0:i.details)||void 0===n?void 0:n.live});const d=null===(o=null===(a=e.levels[i.level])||void 0===a?void 0:a.details)||void 0===o?void 0:o.fragments;if(!d)return;const c=(null===(l=d[1])||void 0===l?void 0:l.start)||0,u=e.liveSyncPosition||(null===(h=d[d.length-1])||void 0===h?void 0:h.end)||0;t.emit("dvr/window",u-c)}))}(r,t,e)}function Dn(t,e,s){!function(t){t.on("audio:set",(function(e){var s,r;const i=null===(s=e.data)||void 0===s?void 0:s.id;"number"==typeof i&&i!=(null===(r=null==t?void 0:t.hls)||void 0===r?void 0:r.audioTrack)&&setTimeout((function(){(null==t?void 0:t.hls)&&(t.hls.audioTrack=i)}),0)}))}(t),function(t,e){t.on("src",(function(){t.hls&&(t.hls.destroy(),delete t.hls,e.manifest=void 0)})),t.on("reap",(function(){var e;null===(e=t.hls)||void 0===e||e.destroy()}))}(t,e),function(t){const e={media_recovers:0,audio_swaps:0};let s=0;t.on("error",e=>{var r,i,n;t.hls&&(null===(r=null==t?void 0:t.error)||void 0===r?void 0:r.code)===MediaError.MEDIA_ERR_DECODE&&(e.preventDefault(),++s,t.emit("flowplayer:error",{error:new FlowplayerError(null!==(n=null===(i=null==t?void 0:t.error)||void 0===i?void 0:i.message)&&void 0!==n?n:"An error occurred while decoding the media.",hn.PlaybackVideoDecodeError,{isFatal:!0,showErrorUI:s>=5,retryOpts:{retry:s<5?un:fn,retryTimeout:0}})}))}),t.on("canplay",()=>s=0),t.on("retry",s=>{var r,i,n,a;if(!t.hls)return;s.preventDefault();const o=s.detail.error,l=o.config;return o.flowplayerErrorCode===hn.PlaybackVideoDecodeError?(t.hls.config.autoStartLoad=!0,t.hls.recoverMediaError(),t.setState("is-waiting",!1)):l.error_type?l.error_type===nn.ErrorTypes.NETWORK_ERROR?((null===(r=t.normalizedSrc)||void 0===r?void 0:r.src)&&t.hls.loadSource(t.original_src),l.autoplay?t.togglePlay(!0):(t.setState("is-waiting",!1),t.emit("retry/done"))):l.error_type===nn.ErrorTypes.MEDIA_ERROR?(gn("recovering from "+l.error_type),e.media_recovers+5e3>Date.now()&&0==e.audio_swaps?(null===(i=t.hls)||void 0===i||i.swapAudioCodec(),gn(`calling swapAudioCodec() : {count=${e.audio_swaps}}`),e.audio_swaps++,e.media_recovers=Date.now(),null===(n=t.hls)||void 0===n||n.recoverMediaError(),t.setState("is-waiting",!1)):(e.media_recovers=Date.now(),e.audio_swaps=0,null===(a=t.hls)||void 0===a||a.recoverMediaError(),t.setState("is-waiting",!1))):void 0:void 0})}(t),Tn(t),function(t,e){t.on(["beforeplay","viewenter"],s=>{if(t.hls&&!t.hasState("is-casting")&&!t.hasState("is-loaded")&&"none"===e.preload&&("viewenter"!==s.type||e.autoplay))return t.hls.levels.length?En(t,e.start_time||-1):void t.hls.once(nn.Events.MANIFEST_PARSED,()=>{setTimeout(()=>{En(t,e.start_time||-1)},0)})}),t.on("quality:set",(function(e){var s;if(!t.hls)return;const r=null===(s=e.data)||void 0===s?void 0:s.level;"number"==typeof r&&(t.hls.levels[r]||-1===r?t.hls.nextLevel=r:console.error(new Error("skipping invalid quality: "+e.data)))})),t.on("tracks:video:select",(function(e){var s,r;const i=e.detail.track,n=null===(s=t.tracks)||void 0===s?void 0:s.find(t=>t.selected&&t!==i),a=t.hls;if(!n||!i||!a)return;n.selected=!1;const o=null===(r=i.data)||void 0===r?void 0:r.slice(0).map(t=>(t.details=void 0,t));a.stopLoad(),a.levelController._levels=a.streamController.levels=o,a.currentLevel=-1,t.emit("qualities",An(o)),t.hasState("is-starting")&&!t.hasState("is-loading")||a.startLoad()}));const s=t.opt("start_time");s&&t.once("loadedmetadata",(function(){t.currentTime=s}))}(t,s)}function Cn(t,e){if(t.drm&&"https:"!==location.protocol&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname){const s=new FlowplayerError("drm is unavailable in http contexts",hn.ContentProtectionKeySystemUnavailable,{resource:t.src,isFatal:!0,retryOpts:{retry:fn}});return e.emit("flowplayer:error",{error:s}),!1}return!0}function wn(t,e,s,r){if(!t.reaper||!(null==s?void 0:s.src))return;if(t.hls&&t.hls.destroy(),!Cn(s,t))return;kn(function(t,e,s,r){var i,n,a,o,l,h,d,c;const u=new FailoverLoaderController,f=function(t){return Object.assign(Object.assign({autoStartLoad:!1,levelLoadingMaxRetry:1},t.hls),{startPosition:t.start_time||-1})}(t);f.renderTextTracksNatively=!1,f.captionsTextTrack1Label=null!==(n=null===(i=null==t?void 0:t.hls)||void 0===i?void 0:i.captionsTextTrack1Label)&&void 0!==n?n:"CC1",f.captionsTextTrack2Label=null!==(o=null===(a=null==t?void 0:t.hls)||void 0===a?void 0:a.captionsTextTrack2Label)&&void 0!==o?o:"CC2",f.captionsTextTrack3Label=null!==(h=null===(l=null==t?void 0:t.hls)||void 0===l?void 0:l.captionsTextTrack3Label)&&void 0!==h?h:"CC3",f.captionsTextTrack4Label=null!==(c=null===(d=null==t?void 0:t.hls)||void 0===d?void 0:d.captionsTextTrack4Label)&&void 0!==c?c:"CC4",f.pLoader=u.createPlaylistLoader(e),f.fLoader=u.createFragmentLoader();const g=s.hls=new nn(f);return u.setHls(g),g.subtitleDisplay=!1,g.attachMedia(s),g.loadSource(r.src),setTimeout(()=>s.emit("hls:attached",{hls:s.hls})),g}(e,r,t,s),e,r,t,s)}var Pn;const In=((Pn=class HLS{init(t,e,s){Dn(s,this,t)}onload(t,e,s,r){s.normalizedSrc=r,wn(s,t,r,this)}wants(t,e,s){return Hls.isSupported()&&function({src:t="",type:e="",drm:s},r){const i=null==r?void 0:r.hls,n=Boolean(null==i?void 0:i.native);return(!sn||!n)&&(!(s&&!Object.keys(s).find(t=>Zi(t)))&&(!(!e||!en.includes(e))||rn(t)))}(e,s)}}).pluginName="hls",Pn.events=Ji,Pn.version=Hls.version,Pn.failover={Reasons:on},Pn);return function(t,e){if("object"==typeof exports&&"undefined"!=typeof module)return e;if(null===document.currentScript)return e;"flowplayer"in t||(t.flowplayer={extensions:[]});const s=t.flowplayer;return"function"==typeof s?(s(e),e):(Array.isArray(s.extensions)||(s.extensions=[]),~s.extensions.indexOf(e)||s.extensions.push(e),e)}(window,In)}));
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):((t="undefined"!=typeof globalThis?globalThis:t||self).flowplayer=t.flowplayer||{},t.flowplayer.hls=e())}(this,function(){"use strict";function t(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var e={exports:{}};!function(t){var e,s,r,i,n;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,i=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(t,e,r){if(r=r||{},t=t.trim(),!(e=e.trim())){if(!r.alwaysNormalize)return t;var i=n.parseURL(t);if(!i)throw new Error("Error trying to parse base URL.");return i.path=n.normalizePath(i.path),n.buildURLFromParts(i)}var a=n.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):e;var o=n.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=s.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,c=d.substring(0,d.lastIndexOf("/")+1)+a.path;h.path=n.normalizePath(c)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=r.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(h)},parseURL:function(t){var s=e.exec(t);return s?{scheme:s[1]||"",netLoc:s[2]||"",path:s[3]||"",params:s[4]||"",query:s[5]||"",fragment:s[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(r,"");t.length!==(t=t.replace(i,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=n}(e);var s=e.exports;function r(t,e){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),s.push.apply(s,r)}return s}function i(t){for(var e=1;e<arguments.length;e++){var s=null!=arguments[e]?arguments[e]:{};e%2?r(Object(s),!0).forEach(function(e){a(t,e,s[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):r(Object(s)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(s,e))})}return t}function n(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var s=t[Symbol.toPrimitive];if(void 0!==s){var r=s.call(t,e||"default");if("object"!=typeof r)return r;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 a(t,e,s){return(e=n(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function o(){return o=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},o.apply(this,arguments)}const l=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},h=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=d},d=Number.MAX_SAFE_INTEGER||9007199254740991;let c=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}({}),u=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}({}),f=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 g=function(){},m={trace:g,debug:g,log:g,warn:g,info:g,error:g};let p=m;function y(t,...e){e.forEach(function(e){p[e]=t[e]?t[e].bind(t):function(t){const e=self.console[t];return e?e.bind(self.console,`[${t}] >`):g}(e)})}const v=p,E=/^(\d+)x(\d+)$/,T=/(.+?)=(".*?"|.*?)(?:,|$)/g;class AttrList{constructor(t){"string"==typeof t&&(t=AttrList.parseAttrList(t)),o(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 s=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)s[t]=parseInt(e.slice(2*t,2*t+2),16);return s}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 s=this[t];return s?parseFloat(s):e}enumeratedString(t){return this[t]}bool(t){return"YES"===this[t]}decimalResolution(t){const e=E.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t){let e;const s={};for(T.lastIndex=0;null!==(e=T.exec(t));){let t=e[2];0===t.indexOf('"')&&t.lastIndexOf('"')===t.length-1&&(t=t.slice(1,-1));s[e[1].trim()]=t}return s}}function S(t){return"ID"!==t&&"CLASS"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function L(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}class DateRange{constructor(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){const s=e.attr;for(const e in s)if(Object.prototype.hasOwnProperty.call(t,e)&&t[e]!==s[e]){v.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=o(new AttrList({}),s,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"]);l(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(l(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&&l(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class LoadStats{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 A="audio",R="video",b="audiovideo";class BaseSegment{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[A]:null,[R]:null,[b]:null},this.baseurl=t}setByteRange(t,e){const s=t.split("@",2);let r;r=1===s.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(s[1]),this._byteRange=[r,parseInt(s[0])+r]}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=s.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}}class Fragment extends BaseSegment{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 LoadStats,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(!l(this.programDateTime))return null;const t=l(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,s,r,i,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,s),o.startDTS=Math.min(o.startDTS,r),o.endDTS=Math.max(o.endDTS,i)):a[t]={startPTS:e,endPTS:s,startDTS:r,endDTS:i,partial:n}}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[A]=null,t[R]=null,t[b]=null}}class Part extends BaseSegment{constructor(t,e,s,r,i){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new LoadStats,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=r;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 LevelDetails{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,s=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!s||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&s>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&&l(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}}function k(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function D(t){const e=t.split(":");let s=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),r=t[t.length-1].split(",");if(2===r.length){const e="base64"===r[0],i=r[1];e?(t.splice(-1,1),s=k(i)):s=function(t){const e=C(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(i)}}return s}function C(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}const P="undefined"!=typeof self?self:void 0;var w={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},I="org.w3.clearkey",_="com.apple.streamingkeydelivery",M="com.microsoft.playready",x="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function F(t){switch(t){case _:return w.FAIRPLAY;case M:return w.PLAYREADY;case x:return w.WIDEVINE;case I:return w.CLEARKEY}}var O="edef8ba979d64acea3c827dcd51d21ed";function N(t){switch(t){case w.FAIRPLAY:return _;case w.PLAYREADY:return M;case w.WIDEVINE:return x;case w.CLEARKEY:return I}}function U(t){const{drmSystems:e,widevineLicenseUrl:s}=t,r=e?[w.FAIRPLAY,w.WIDEVINE,w.PLAYREADY,w.CLEARKEY].filter(t=>!!e[t]):[];return!r[w.WIDEVINE]&&s&&r.push(w.WIDEVINE),r}const B=null!=P&&null!=($=P.navigator)&&$.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var $;function G(t,e,s){return Uint8Array.prototype.slice?t.slice(e,s):new Uint8Array(Array.prototype.slice.call(t,e,s))}const K=(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,H=(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,V=(t,e)=>{const s=e;let r=0;for(;K(t,e);){r+=10;r+=Y(t,e+6),H(t,e+10)&&(r+=10),e+=r}if(r>0)return t.subarray(s,s+r)},Y=(t,e)=>{let s=0;return s=(127&t[e])<<21,s|=(127&t[e+1])<<14,s|=(127&t[e+2])<<7,s|=127&t[e+3],s},W=(t,e)=>K(t,e)&&Y(t,e+6)+10<=t.length-e,j=t=>{const e=z(t);for(let t=0;t<e.length;t++){const s=e[t];if(q(s))return et(s)}},q=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]),s=Y(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}},z=t=>{let e=0;const s=[];for(;K(t,e);){const r=Y(t,e+6);e+=10;const i=e+r;for(;e+8<i;){const r=X(t.subarray(e)),i=Q(r);i&&s.push(i),e+=r.size+10}H(t,e)&&(e+=10)}return s},Q=t=>"PRIV"===t.type?J(t):"W"===t.type[0]?tt(t):Z(t),J=t=>{if(t.size<2)return;const e=st(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}},Z=t=>{if(t.size<2)return;if("TXXX"===t.type){let e=1;const s=st(t.data.subarray(e),!0);e+=s.length+1;const r=st(t.data.subarray(e));return{key:t.type,info:s,data:r}}const e=st(t.data.subarray(1));return{key:t.type,data:e}},tt=t=>{if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=st(t.data.subarray(e),!0);e+=s.length+1;const r=st(t.data.subarray(e));return{key:t.type,info:s,data:r}}const e=st(t.data);return{key:t.type,data:e}},et=t=>{if(8===t.data.byteLength){const e=new Uint8Array(t.data),s=1&e[3];let r=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return r/=45,s&&(r+=47721858.84),Math.round(r)}},st=(t,e=!1)=>{const s=it();if(s){const r=s.decode(t);if(e){const t=r.indexOf("\0");return-1!==t?r.substring(0,t):r}return r.replace(/\0/g,"")}const r=t.length;let i,n,a,o="",l=0;for(;l<r;){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 rt;function it(){if(!navigator.userAgent.includes("PlayStation 4"))return rt||void 0===self.TextDecoder||(rt=new self.TextDecoder("utf-8")),rt}const nt=function(t){let e="";for(let s=0;s<t.length;s++){let r=t[s].toString(16);r.length<2&&(r="0"+r),e+=r}return e},at=Math.pow(2,32)-1,ot=[].push,lt={video:1,audio:2,id3:3,text:4};function ht(t){return String.fromCharCode.apply(null,t)}function dt(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function ct(t,e){const s=ft(t,e);return s<0?4294967296+s:s}function ut(t,e){let s=ct(t,e);return s*=Math.pow(2,32),s+=ct(t,e+4),s}function ft(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function gt(t,e,s){t[e]=s>>24,t[e+1]=s>>16&255,t[e+2]=s>>8&255,t[e+3]=255&s}function mt(t,e){const s=[];if(!e.length)return s;const r=t.byteLength;for(let i=0;i<r;){const n=ct(t,i),a=n>1?i+n:r;if(ht(t.subarray(i+4,i+8))===e[0])if(1===e.length)s.push(t.subarray(i+8,a));else{const r=mt(t.subarray(i+8,a),e.slice(1));r.length&&ot.apply(s,r)}i=a}return s}function pt(t){const e=[],s=t[0];let r=8;const i=ct(t,r);r+=4;let n=0,a=0;0===s?(n=ct(t,r),a=ct(t,r+4),r+=8):(n=ut(t,r),a=ut(t,r+8),r+=16),r+=2;let o=t.length+a;const l=dt(t,r);r+=2;for(let s=0;s<l;s++){let s=r;const n=ct(t,s);s+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return v.warn("SIDX has hierarchical references (not supported)"),null;const l=ct(t,s);s+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/i,start:o,end:o+a-1}}),o+=a,s+=4,r=s}return{earliestPresentationTime:n,timescale:i,version:s,referencesCount:l,references:e}}function yt(t){const e=[],s=mt(t,["moov","trak"]);for(let t=0;t<s.length;t++){const r=s[t],n=mt(r,["tkhd"])[0];if(n){let t=n[0];const s=ct(n,0===t?12:20),a=mt(r,["mdia","mdhd"])[0];if(a){t=a[0];const n=ct(a,0===t?12:20),o=mt(r,["mdia","hdlr"])[0];if(o){const t=ht(o.subarray(8,12)),a={soun:A,vide:R}[t];if(a){const t=vt(mt(r,["mdia","minf","stbl","stsd"])[0]);e[s]={timescale:n,type:a},e[a]=i({timescale:n,id:s},t)}}}}}return mt(t,["moov","mvex","trex"]).forEach(t=>{const s=ct(t,4),r=e[s];r&&(r.default={duration:ct(t,12),flags:ct(t,20)})}),e}function vt(t){const e=t.subarray(8),s=e.subarray(86),r=ht(e.subarray(4,8));let i=r;const n="enca"===r||"encv"===r;if(n){const t=mt(e,[r])[0];mt(t.subarray("enca"===r?28:78),["sinf"]).forEach(t=>{const e=mt(t,["schm"])[0];if(e){const s=ht(e.subarray(4,8));if("cbcs"===s||"cenc"===s){const e=mt(t,["frma"])[0];e&&(i=ht(e))}}})}switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const t=mt(s,["avcC"])[0];i+="."+Tt(t[1])+Tt(t[2])+Tt(t[3]);break}case"mp4a":{const t=mt(e,[r])[0],s=mt(t.subarray(28),["esds"])[0];if(s&&s.length>12){let t=4;if(3!==s[t++])break;t=Et(s,t),t+=2;const e=s[t++];if(128&e&&(t+=2),64&e&&(t+=s[t++]),4!==s[t++])break;t=Et(s,t);const r=s[t++];if(64!==r)break;if(i+="."+Tt(r),t+=12,5!==s[t++])break;t=Et(s,t);const n=s[t++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&s[t])>>5)),i+="."+a}break}case"hvc1":case"hev1":{const t=mt(s,["hvcC"])[0],e=t[1],r=["","A","B","C"][e>>6],n=31&e,a=ct(t,2),o=(32&e)>>5?"H":"L",l=t[12],h=t.subarray(6,12);i+="."+r+n,i+="."+a.toString(16).toUpperCase(),i+="."+o+l;let d="";for(let t=h.length;t--;){const e=h[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}i+=d;break}case"dvh1":case"dvhe":{const t=mt(s,["dvcC"])[0],e=t[2]>>1&127,r=t[2]<<5&32|t[3]>>3&31;i+="."+St(e)+"."+St(r);break}case"vp09":{const t=mt(s,["vpcC"])[0],e=t[4],r=t[5],n=t[6]>>4&15;i+="."+St(e)+"."+St(r)+"."+St(n);break}case"av01":{const t=mt(s,["av1C"])[0],e=t[1]>>>5,r=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,h=(16&t[2])>>4,d=(8&t[2])>>3,c=(4&t[2])>>2,u=3&t[2],f=1,g=1,m=1,p=0;i+="."+e+"."+St(r)+n+"."+St(l)+"."+h+"."+d+c+u+"."+St(f)+"."+St(g)+"."+St(m)+"."+p;break}}return{codec:i,encrypted:n}}function Et(t,e){const s=e+5;for(;128&t[e++]&&e<s;);return e}function Tt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function St(t){return(t<10?"0":"")+t}function Lt(t){const e=mt(t,["schm"])[0];if(e){const s=ht(e.subarray(4,8));if("cbcs"===s||"cenc"===s)return mt(t,["schi","tenc"])[0]}return v.error("[eme] missing 'schm' box"),null}function At(t){const e=ct(t,0);let s=8;1&e&&(s+=4),4&e&&(s+=4);let r=0;const i=ct(t,4);for(let n=0;n<i;n++){if(256&e){r+=ct(t,s),s+=4}512&e&&(s+=4),1024&e&&(s+=4),2048&e&&(s+=4)}return r}function Rt(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}function bt(t,e){const s=[],r=e.samples,i=e.timescale,n=e.id;let a=!1;return mt(r,["moof"]).map(o=>{const l=o.byteOffset-8;mt(o,["traf"]).map(o=>{const h=mt(o,["tfdt"]).map(t=>{const e=t[0];let s=ct(t,4);return 1===e&&(s*=Math.pow(2,32),s+=ct(t,8)),s/i})[0];return void 0!==h&&(t=h),mt(o,["tfhd"]).map(h=>{const d=ct(h,4),c=16777215&ct(h,0);let u=0;const f=!!(16&c);let g=0;const m=!!(32&c);let p=8;d===n&&(!!(1&c)&&(p+=8),!!(2&c)&&(p+=4),!!(8&c)&&(u=ct(h,p),p+=4),f&&(g=ct(h,p),p+=4),m&&(p+=4),"video"===e.type&&(a=function(t){if(!t)return!1;const e=t.indexOf("."),s=e<0?t:t.substring(0,e);return"hvc1"===s||"hev1"===s||"dvh1"===s||"dvhe"===s}(e.codec)),mt(o,["trun"]).map(n=>{const o=n[0],h=16777215&ct(n,0),d=!!(1&h);let c=0;const f=!!(4&h),m=!!(256&h);let p=0;const y=!!(512&h);let v=0;const E=!!(1024&h),T=!!(2048&h);let S=0;const L=ct(n,4);let A=8;d&&(c=ct(n,A),A+=4),f&&(A+=4);let b=c+l;for(let l=0;l<L;l++){if(m?(p=ct(n,A),A+=4):p=u,y?(v=ct(n,A),A+=4):v=g,E&&(A+=4),T&&(S=0===o?ct(n,A):ft(n,A),A+=4),e.type===R){let e=0;for(;e<v;){const n=ct(r,b);if(b+=4,kt(a,r[b])){Dt(r.subarray(b,b+n),a?2:1,t+S/i,s)}b+=n,e+=n+4}}t+=p/i}}))})})}),s}function kt(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Dt(t,e,s,r){const i=Ct(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){v.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===i[e++]){const t=dt(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,h=new Uint8Array(l);if(o){h[0]=n;for(let t=1;t<l;t++)h[t]=i[e++]}r.push({type:t,payloadType:a,pts:s,bytes:h})}}}}}else if(5===a&&o>16){const t=[];for(let s=0;s<16;s++){const r=i[e++].toString(16);t.push(1==r.length?"0"+r:r),3!==s&&5!==s&&7!==s&&9!==s||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=i[e++];r.push({payloadType:a,pts:s,uuid:t.join(""),userData:st(l),userDataBytes:l})}}}function Ct(t){const e=t.byteLength,s=[];let r=1;for(;r<e-2;)0===t[r]&&0===t[r+1]&&3===t[r+2]?(s.push(r+2),r+=2):r++;if(0===s.length)return t;const i=e-s.length,n=new Uint8Array(i);let a=0;for(r=0;r<i;a++,r++)a===s[0]&&(a++,s.shift()),n[r]=t[a];return n}function Pt(t,e,s){if(16!==t.byteLength)throw new RangeError("Invalid system id");let r,i,n;if(e){r=1,i=new Uint8Array(16*e.length);for(let t=0;t<e.length;t++){const s=e[t];if(16!==s.byteLength)throw new RangeError("Invalid key");i.set(s,16*t)}}else r=0,i=new Uint8Array;r>0?(n=new Uint8Array(4),e.length>0&&new DataView(n.buffer).setUint32(0,e.length,!1)):n=new Uint8Array;const a=new Uint8Array(4);return s&&s.byteLength>0&&new DataView(a.buffer).setUint32(0,s.byteLength,!1),function(t,...e){const s=e.length;let r=8,i=s;for(;i--;)r+=e[i].byteLength;const n=new Uint8Array(r);for(n[0]=r>>24&255,n[1]=r>>16&255,n[2]=r>>8&255,n[3]=255&r,n.set(t,4),i=0,r=8;i<s;i++)n.set(e[i],r),r+=e[i].byteLength;return n}([112,115,115,104],new Uint8Array([r,0,0,0]),t,n,i,a,s||new Uint8Array)}let wt={};class LevelKey{static clearKeyUriToKeyIdMap(){wt={}}constructor(t,e,s,r=[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=s,this.keyFormatVersions=r,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;switch(this.keyFormat){case _:case x:case M:case I:return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(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||v.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 s=12;s<16;s++)e[s]=t>>8*(15-s)&255;return e}(t);return new LevelKey(this.method,this.uri,"identity",this.keyFormatVersions,e)}const e=D(this.uri);if(e)switch(this.keyFormat){case x:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case M:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Pt(t,null,e);const s=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(s)),i=r.substring(r.indexOf("<"),r.length),n=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(n){const t=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(t){const e=k(t).subarray(0,16);!function(t){const e=function(t,e,s){const r=t[e];t[e]=t[s],t[s]=r};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(e),this.keyId=e}}break}default:{let t=e.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(!this.keyId||16!==this.keyId.byteLength){let t=wt[this.uri];if(!t){const e=Object.keys(wt).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),wt[this.uri]=t}this.keyId=t}return this}}const It=/\{\$([a-zA-Z0-9-_]+)\}/g;function _t(t){return It.test(t)}function Mt(t,e,s){if(null!==t.variableList||t.hasVariableRefs)for(let r=s.length;r--;){const i=s[r],n=e[i];n&&(e[i]=xt(t,n))}}function xt(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(It,e=>{const r=e.substring(2,e.length-1),i=null==s?void 0:s[r];return void 0===i?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),e):i})}return e}function Ft(t,e,s){let r,i,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){r=e.QUERYPARAM;try{const t=new self.URL(s).searchParams;if(!t.has(r))throw new Error(`"${r}" does not match any query parameter in URI: "${s}"`);i=t.get(r)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else r=e.NAME,i=e.VALUE;r in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):n[r]=i||""}function Ot(t,e,s){const r=e.IMPORT;if(s&&r in s){let e=t.variableList;e||(t.variableList=e={}),e[r]=s[r]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}function Nt(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const Ut={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 Bt(t,e,s=!0){return!t.split(",").some(t=>!$t(t,e,s))}function $t(t,e,s=!0){var r;const i=Nt(s);return null!=(r=null==i?void 0:i.isTypeSupported(Gt(t,e)))&&r}function Gt(t,e){return`${e}/mp4;codecs="${t}"`}function Kt(t){if(t){const e=t.substring(0,4);return Ut.video[e]}return 2}function Ht(t){return t.split(",").reduce((t,e)=>{const s=Ut.video[e];return s?(2*s+t)/(t?3:2):(Ut.audio[e]+t)/(t?2:1)},0)}const Vt={};const Yt=/flac|opus/i;function Wt(t,e=!0){return t.replace(Yt,t=>function(t,e=!0){if(Vt[t])return Vt[t];const s={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let r=0;r<s.length;r++)if($t(s[r],"audio",e))return Vt[t]=s[r],s[r];return t}(t.toLowerCase(),e))}function jt(t,e){return t&&"mp4a"!==t?t:e?e.split(",")[0]:e}const qt=/#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,Xt=/#EXT-X-MEDIA:(.*)/g,zt=/^#EXT(?:INF|-X-TARGETDURATION):/m,Qt=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Jt=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 M3U8Parser{static findGroup(t,e){for(let s=0;s<t.length;s++){const r=t[s];if(r.id===e)return r}}static resolve(t,e){return s.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return zt.test(t)}static parseMasterPlaylist(t,e){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:_t(t)},r=[];let i;for(qt.lastIndex=0;null!=(i=qt.exec(t));)if(i[1]){var n;const t=new AttrList(i[1]);Mt(s,t,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=xt(s,i[2]),o={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:M3U8Parser.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),ee(t.CODECS,o),null!=(n=o.unknownCodecs)&&n.length||r.push(o),s.levels.push(o)}else if(i[3]){const t=i[3],r=i[4];switch(t){case"SESSION-DATA":{const t=new AttrList(r);Mt(s,t,["DATA-ID","LANGUAGE","VALUE","URI"]);const e=t["DATA-ID"];e&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[e]=t);break}case"SESSION-KEY":{const t=Zt(r,e,s);t.encrypted&&t.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(t)):v.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":{const t=new AttrList(r);Mt(s,t,["NAME","VALUE","QUERYPARAM"]),Ft(s,t,e)}break;case"CONTENT-STEERING":{const t=new AttrList(r);Mt(s,t,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:M3U8Parser.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=te(r)}}const a=r.length>0&&r.length<s.levels.length;return s.levels=a?r:s.levels,0===s.levels.length&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(t,e,s){let r;const i={},n=s.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(Xt.lastIndex=0;null!==(r=Xt.exec(t));){const t=new AttrList(r[1]),n=t.TYPE;if(n){const r=a[n],l=i[n]||[];i[n]=l,Mt(s,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const h=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],c=t.CHANNELS,u=t.CHARACTERISTICS,f=t["INSTREAM-ID"],g={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||h||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:h,url:t.URI?M3U8Parser.resolve(t.URI,e):""};if(d&&(g.assocLang=d),c&&(g.channels=c),u&&(g.characteristics=u),f&&(g.instreamId=f),null!=r&&r.length){const t=M3U8Parser.findGroup(r,g.groupId)||r[0];se(g,t,"audioCodec"),se(g,t,"textCodec")}l.push(g)}}return i}static parseLevelPlaylist(t,e,s,r,i,n){const a=new LevelDetails(e),h=a.fragments;let d,c,u,f=null,g=0,m=0,p=0,y=0,E=null,T=new Fragment(r,e),S=-1,L=!1,A=null;for(Qt.lastIndex=0,a.m3u8=t,a.hasVariableRefs=_t(t);null!==(d=Qt.exec(t));){L&&(L=!1,T=new Fragment(r,e),T.start=p,T.sn=g,T.cc=y,T.level=s,f&&(T.initSegment=f,T.rawProgramDateTime=f.rawProgramDateTime,f.rawProgramDateTime=null,A&&(T.setByteRange(A),A=null)));const t=d[1];if(t){T.duration=parseFloat(t);const e=(" "+d[2]).slice(1);T.title=e||null,T.tagList.push(e?["INF",t,e]:["INF",t])}else if(d[3]){if(l(T.duration)){T.start=p,u&&ne(T,u,a),T.sn=g,T.level=s,T.cc=y,h.push(T);const t=(" "+d[3]).slice(1);T.relurl=xt(a,t),re(T,E),E=T,p+=T.duration,g++,m=0,L=!0}}else if(d[4]){const t=(" "+d[4]).slice(1);E?T.setByteRange(t,E):T.setByteRange(t)}else if(d[5])T.rawProgramDateTime=(" "+d[5]).slice(1),T.tagList.push(["PROGRAM-DATE-TIME",T.rawProgramDateTime]),-1===S&&(S=h.length);else{if(d=d[0].match(Jt),!d){v.warn("No matches on slow regex match for level playlist!");continue}for(c=1;c<d.length&&void 0===d[c];c++);const t=(" "+d[c]).slice(1),i=(" "+d[c+1]).slice(1),p=d[c+2]?(" "+d[c+2]).slice(1):"";switch(t){case"PLAYLIST-TYPE":a.type=i.toUpperCase();break;case"MEDIA-SEQUENCE":g=a.startSN=parseInt(i);break;case"SKIP":{const t=new AttrList(i);Mt(a,t,["RECENTLY-REMOVED-DATERANGES"]);const e=t.decimalInteger("SKIPPED-SEGMENTS");if(l(e)){a.skippedSegments=e;for(let t=e;t--;)h.unshift(null);g+=e}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(a.recentlyRemovedDateranges=s.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":break;case"ENDLIST":a.live=!1;break;case"#":(i||p)&&T.tagList.push(p?[i,p]:[i]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([t]);break;case"BITRATE":T.tagList.push([t,i]);break;case"DATERANGE":{const t=new AttrList(i);Mt(a,t,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Mt(a,t,t.clientAttrs);const e=new DateRange(t,a.dateRanges[t.ID]);e.isValid||a.skippedSegments?a.dateRanges[e.id]=e:v.warn(`Ignoring invalid DATERANGE tag: "${i}"`),T.tagList.push(["EXT-X-DATERANGE",i]);break}case"DEFINE":{const t=new AttrList(i);Mt(a,t,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in t?Ot(a,t,n):Ft(a,t,e)}break;case"DISCONTINUITY-SEQUENCE":y=parseInt(i);break;case"KEY":{const t=Zt(i,e,a);if(t.isSupported()){if("NONE"===t.method){u=void 0;break}u||(u={}),u[t.keyFormat]&&(u=o({},u)),u[t.keyFormat]=t}else v.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${i}"`);break}case"START":a.startTimeOffset=te(i);break;case"MAP":{const t=new AttrList(i);if(Mt(a,t,["BYTERANGE","URI"]),T.duration){const i=new Fragment(r,e);ie(i,t,s,u),f=i,T.initSegment=f,f.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=f.rawProgramDateTime)}else{const e=T.byteRangeEndOffset;if(e){const t=T.byteRangeStartOffset;A=`${e-t}@${t}`}else A=null;ie(T,t,s,u),f=T,L=!0}break}case"SERVER-CONTROL":{const t=new AttrList(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 AttrList(i);a.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=a.partList;t||(t=a.partList=[]);const s=m>0?t[t.length-1]:void 0,r=m++,n=new AttrList(i);Mt(a,n,["BYTERANGE","URI"]);const o=new Part(n,T,e,r,s);t.push(o),T.duration+=o.duration;break}case"PRELOAD-HINT":{const t=new AttrList(i);Mt(a,t,["URI"]),a.preloadHint=t;break}case"RENDITION-REPORT":{const t=new AttrList(i);Mt(a,t,["URI"]),a.renditionReports=a.renditionReports||[],a.renditionReports.push(t);break}default:v.warn(`line parsed but not handled: ${d}`)}}}E&&!E.relurl?(h.pop(),p-=E.duration,a.partList&&(a.fragmentHint=E)):a.partList&&(re(T,E),T.cc=y,a.fragmentHint=T,u&&ne(T,u,a));const R=h.length,b=h[0],k=h[R-1];if(p+=a.skippedSegments*a.targetduration,p>0&&R&&k){a.averagetargetduration=p/R;const t=k.sn;a.endSN="initSegment"!==t?t:0,a.live||(k.endList=!0),b&&(a.startCC=b.cc)}else a.endSN=0,a.startCC=0;return a.fragmentHint&&(p+=a.fragmentHint.duration),a.totalduration=p,a.endCC=y,S>0&&function(t,e){let s=t[e];for(let r=e;r--;){const e=t[r];if(!e)return;e.programDateTime=s.programDateTime-1e3*e.duration,s=e}}(h,S),a}}function Zt(t,e,s){var r,i;const n=new AttrList(t);Mt(s,n,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(r=n.METHOD)?r:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(i=n.KEYFORMAT)?i:"identity";o&&n.IV&&!l&&v.error(`Invalid IV: ${n.IV}`);const c=o?M3U8Parser.resolve(o,e):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new LevelKey(a,c,d,u,l)}function te(t){const e=new AttrList(t).decimalFloatingPoint("TIME-OFFSET");return l(e)?e:null}function ee(t,e){let s=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text"].forEach(t=>{const r=s.filter(e=>function(t,e){const s=Ut[e];return!!s&&!!s[t.slice(0,4)]}(e,t));r.length&&(e[`${t}Codec`]=r.join(","),s=s.filter(t=>-1===r.indexOf(t)))}),e.unknownCodecs=s}function se(t,e,s){const r=e[s];r&&(t[s]=r)}function re(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),l(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function ie(t,e,s,r){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=s,t.sn="initSegment",r&&(t.levelkeys=r),t.initSegment=null}function ne(t,e,s){t.levelkeys=e;const{encryptedFragments:r}=s;r.length&&r[r.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||r.push(t)}var ae="manifest",oe="level",le="audioTrack",he="subtitleTrack",de="main",ce="audio",ue="subtitle";function fe(t){const{type:e}=t;switch(e){case le:return ce;case he:return ue;default:return de}}function ge(t,e){let s=t.url;return void 0!==s&&0!==s.indexOf("data:")||(s=e.url),s}class PlaylistLoader{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(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.LEVEL_LOADING,this.onLevelLoading,this),t.on(c.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(c.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.LEVEL_LOADING,this.onLevelLoading,this),t.off(c.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(c.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(t){const e=this.hls.config,s=e.pLoader,r=e.loader,i=new(s||r)(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:s}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ae,url:s,deliveryDirectives:null})}onLevelLoading(t,e){const{id:s,level:r,pathwayId:i,url:n,deliveryDirectives:a}=e;this.load({id:s,level:r,pathwayId:i,responseType:"text",type:oe,url:n,deliveryDirectives:a})}onAudioTrackLoading(t,e){const{id:s,groupId:r,url:i,deliveryDirectives:n}=e;this.load({id:s,groupId:r,level:null,responseType:"text",type:le,url:i,deliveryDirectives:n})}onSubtitleTrackLoading(t,e){const{id:s,groupId:r,url:i,deliveryDirectives:n}=e;this.load({id:s,groupId:r,level:null,responseType:"text",type:he,url:i,deliveryDirectives:n})}load(t){var e;const s=this.hls.config;let r,i=this.getInternalLoader(t);if(i){const e=i.context;if(e&&e.url===t.url&&e.level===t.level)return void v.trace("[playlist-loader]: playlist request ongoing");v.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),i.abort()}if(r=t.type===ae?s.manifestLoadPolicy.default:o({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(t),l(null==(e=t.deliveryDirectives)?void 0:e.part)){let e;if(t.type===oe&&null!==t.level?e=this.hls.levels[t.level].details:t.type===le&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===he&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,s=e.targetduration;if(t&&s){const e=1e3*Math.max(3*t,.8*s);r=o({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},h={onSuccess:(t,e,s,r)=>{const i=this.getInternalLoader(s);this.resetInternalLoader(s.type);const n=t.data;0===n.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(n)?this.handleTrackOrLevelPlaylist(t,e,s,r||null,i):this.handleMasterPlaylist(t,e,s,r)):this.handleManifestParsingError(t,s,new Error("no EXTM3U delimiter"),r||null,e)},onError:(t,e,s,r)=>{this.handleNetworkError(e,s,!1,t,r)},onTimeout:(t,e,s)=>{this.handleNetworkError(e,s,!0,void 0,t)}};i.load(t,a,h)}handleMasterPlaylist(t,e,s,r){const i=this.hls,n=t.data,a=ge(t,s),o=M3U8Parser.parseMasterPlaylist(n,a);if(o.playlistParsingError)return void this.handleManifestParsingError(t,s,o.playlistParsingError,r,e);const{contentSteering:l,levels:h,sessionData:d,sessionKeys:u,startTimeOffset:f,variableList:g}=o;this.variableList=g;const{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":y}=M3U8Parser.parseMasterPlaylistMedia(n,a,o);if(m.length){m.some(t=>!t.url)||!h[0].audioCodec||h[0].attrs.AUDIO||(v.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new AttrList({}),bitrate:0,url:""}))}i.trigger(c.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:p,captions:y,contentSteering:l,url:a,stats:e,networkDetails:r,sessionData:d,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(t,e,s,r,i){const n=this.hls,{id:a,level:o,type:h}=s,d=ge(t,s),u=l(o)?o:l(a)?a:0,f=fe(s),g=M3U8Parser.parseLevelPlaylist(t.data,d,u,f,0,this.variableList);if(h===ae){const t={attrs:new AttrList({}),bitrate:0,details:g,name:"",url:d};n.trigger(c.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:d,stats:e,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=g,this.handlePlaylistLoaded(g,t,e,s,r,i)}handleManifestParsingError(t,e,s,r,i){this.hls.trigger(c.ERROR,{type:u.NETWORK_ERROR,details:f.MANIFEST_PARSING_ERROR,fatal:e.type===ae,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:r,stats:i})}handleNetworkError(t,e,s=!1,r,n){let a=`A network ${s?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${t.type}`;t.type===oe?a+=`: ${t.level} id: ${t.id}`:t.type!==le&&t.type!==he||(a+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(a);v.warn(`[playlist-loader]: ${a}`);let l=f.UNKNOWN,h=!1;const d=this.getInternalLoader(t);switch(t.type){case ae:l=s?f.MANIFEST_LOAD_TIMEOUT:f.MANIFEST_LOAD_ERROR,h=!0;break;case oe:l=s?f.LEVEL_LOAD_TIMEOUT:f.LEVEL_LOAD_ERROR,h=!1;break;case le:l=s?f.AUDIO_TRACK_LOAD_TIMEOUT:f.AUDIO_TRACK_LOAD_ERROR,h=!1;break;case he:l=s?f.SUBTITLE_TRACK_LOAD_TIMEOUT:f.SUBTITLE_LOAD_ERROR,h=!1}d&&this.resetInternalLoader(t.type);const g={type:u.NETWORK_ERROR,details:l,fatal:h,url:t.url,loader:d,context:t,error:o,networkDetails:e,stats:n};if(r){const s=(null==e?void 0:e.url)||t.url;g.response=i({url:s,data:void 0},r)}this.hls.trigger(c.ERROR,g)}handlePlaylistLoaded(t,e,s,r,i,n){const a=this.hls,{type:o,level:l,id:h,groupId:d,deliveryDirectives:g}=r,m=ge(e,r),p=fe(r),y="number"==typeof r.level&&p===de?l:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void a.trigger(c.ERROR,{type:u.NETWORK_ERROR,details:f.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:t,reason:t.message,response:e,context:r,level:y,parent:p,networkDetails:i,stats:s})}t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));const v=t.playlistParsingError;if(v)a.trigger(c.ERROR,{type:u.NETWORK_ERROR,details:f.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:e,context:r,level:y,parent:p,networkDetails:i,stats:s});else switch(t.live&&n&&(n.getCacheAge&&(t.ageHeader=n.getCacheAge()||0),n.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case ae:case oe:a.trigger(c.LEVEL_LOADED,{details:t,level:y||0,id:h||0,stats:s,networkDetails:i,deliveryDirectives:g});break;case le:a.trigger(c.AUDIO_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:s,networkDetails:i,deliveryDirectives:g});break;case he:a.trigger(c.SUBTITLE_TRACK_LOADED,{details:t,id:h||0,groupId:d||"",stats:s,networkDetails:i,deliveryDirectives:g})}}}function me(t,e){let s;try{s=new Event("addtrack")}catch(t){s=document.createEvent("Event"),s.initEvent("addtrack",!1,!1)}s.track=t,e.dispatchEvent(s)}function pe(t,e){const s=t.mode;if("disabled"===s&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){v.debug(`[texttrack-utils]: ${s}`);try{const s=new self.TextTrackCue(e.startTime,e.endTime,e.text);s.id=e.id,t.addCue(s)}catch(t){v.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===s&&(t.mode=s)}function ye(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)}function ve(t,e,s,r){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&t.cues.length>0){const i=function(t,e,s){const r=[],i=function(t,e){if(e<t[0].startTime)return 0;const s=t.length-1;if(e>t[s].endTime)return-1;let r=0,i=s;for(;r<=i;){const n=Math.floor((i+r)/2);if(e<t[n].startTime)i=n-1;else{if(!(e>t[n].startTime&&r<s))return n;r=n+1}}return t[r].startTime-e<e-t[i].startTime?r: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<=s)r.push(i);else if(i.startTime>s)return r}return r}(t.cues,e,s);for(let e=0;e<i.length;e++)r&&!r(i[e])||t.removeCue(i[e])}"disabled"===i&&(t.mode=i)}function Ee(t){const e=[];for(let s=0;s<t.length;s++){const r=t[s];"subtitles"!==r.kind&&"captions"!==r.kind||!r.label||e.push(t[s])}return e}var Te="org.id3",Se="com.apple.quicktime.HLS",Le="https://aomedia.org/emsg/ID3";function Ae(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Re(t,e,s,r,n){let a=new t(e,s,"");try{a.value=r,n&&(a.type=n)}catch(o){a=new t(e,s,JSON.stringify(n?i({type:n},r):r))}return a}const be=(()=>{const t=Ae();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function ke(t,e){return t.getTime()/1e3-e}function De(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class ID3TrackController{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(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(c.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(c.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(ye(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 s=t[e];if("metadata"===s.kind&&"id3"===s.label)return me(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(t,e){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:r}}}=this;if(!s&&!r)return;const{samples:i}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Ae();if(n)for(let t=0;t<i.length;t++){const e=i[t].type;if(e===Le&&!s||!r)continue;const a=z(i[t].data);if(a){const s=i[t].pts;let r=s+i[t].duration;r>be&&(r=be);r-s<=0&&(r=s+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!q(i)){this.updateId3CueEnds(s,e);const t=Re(n,s,r,i,e);t&&this.id3Track.addCue(t)}}}}}updateId3CueEnds(t,e){var s;const r=null==(s=this.id3Track)?void 0:s.cues;if(r)for(let s=r.length;s--;){const i=r[s];i.type===e&&i.startTime<t&&i.endTime===be&&(i.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:s,type:r}){const{id3Track:i,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(i&&(a||o)){let t;t="audio"===r?t=>t.type===Te&&o:"video"===r?t=>t.type===Le&&a:t=>t.type===Te&&o||t.type===Le&&a,ve(i,e,s,t)}}onLevelUpdated(t,{details:e}){if(!this.media||!e.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:s,id3Track:r}=this,{dateRanges:i}=e,n=Object.keys(i);if(r){const t=Object.keys(s).filter(t=>!n.includes(t));for(let e=t.length;e--;){const i=t[e];Object.keys(s[i].cues).forEach(t=>{r.removeCue(s[i].cues[t])}),delete s[i]}}const a=e.fragments[e.fragments.length-1];if(0===n.length||!l(null==a?void 0:a.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const o=a.programDateTime/1e3-a.start,h=Ae();for(let t=0;t<n.length;t++){const e=n[t],r=i[e],a=ke(r.startDate,o),l=s[e],d=(null==l?void 0:l.cues)||{};let c=(null==l?void 0:l.durationKnown)||!1,u=be;const f=r.endDate;if(f)u=ke(f,o),c=!0;else if(r.endOnNext&&!c){const t=n.reduce((t,e)=>{if(e!==r.id){const s=i[e];if(s.class===r.class&&s.startDate>r.startDate&&(!t||r.startDate<t.startDate))return s}return t},null);t&&(u=ke(t.startDate,o),c=!0)}const g=Object.keys(r.attr);for(let t=0;t<g.length;t++){const s=g[t];if(!S(s))continue;const i=d[s];if(i)c&&!l.durationKnown&&(i.endTime=u);else if(h){let t=r.attr[s];L(s)&&(t=De(t));const i=Re(h,a,u,{key:s,data:t},Se);i&&(i.id=e,this.id3Track.addCue(i),d[s]=i)}}s[e]={cues:d,dateRange:r,durationKnown:c}}}}class LatencyController{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:s,targetduration:r}=t,{liveSyncDuration:i,liveSyncDurationCount:n,lowLatencyMode:a}=this.config,o=this.hls.userConfig;let l=a&&s||e;(o.liveSyncDuration||o.liveSyncDurationCount||0===l)&&(l=void 0!==i?i:n*r);const h=r;return l+Math.min(1*this.stallCount,h)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency,s=this.levelDetails;if(null===t||null===e||null===s)return null;const r=s.edge,i=t-e-this.edgeStalled,n=r-s.totalduration,a=r-(this.config.lowLatencyMode&&s.partTarget||s.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 s=t.buffered.length;return(s?t.buffered.end(s-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(c.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(c.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(c.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(c.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(c.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(c.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(c.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 s;e.details===f.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(s=this.levelDetails)&&s.live&&v.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 s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:i}=this.config;if(!r||1===i||!e.live)return;const n=this.targetLatency;if(null===n)return;const a=s-n;if(a<Math.min(this.maxLatency,n+e.targetduration)&&a>.05&&this.forwardBufferLength>1){const e=Math.min(2,Math.max(1,i)),s=Math.round(2/(1+Math.exp(-.75*a-this.edgeStalled))*20)/20;t.playbackRate=Math.min(e,Math.max(1,s))}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 Ce=["NONE","TYPE-0","TYPE-1",null];const Pe=["SDR","PQ","HLG"];var we="",Ie="YES",_e="v2";function Me(t){const{canSkipUntil:e,canSkipDateRanges:s,age:r}=t;return e&&r<e/2?s?_e:Ie:we}class HlsUrlParameters{constructor(t,e,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=s}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 Level{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 xe(this._audioGroups,t)}hasSubtitleGroup(t){return xe(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 xe(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Fe(t,e){const s=e.startPTS;if(l(s)){let r,i=0;e.sn>t.sn?(i=s-t.start,r=t):(i=t.start-s,r=e),r.duration!==i&&(r.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 Oe(t,e,s,r,i,n){r-s<=0&&(v.warn("Fragment should have a positive duration",e),r=s+e.duration,n=i+e.duration);let a=s,o=r;const h=e.startPTS,d=e.endPTS;if(l(h)){const t=Math.abs(h-s);l(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,a=Math.max(s,h),s=Math.min(s,h),i=Math.min(i,e.startDTS),o=Math.min(r,d),r=Math.max(r,d),n=Math.max(n,e.endDTS)}const c=s-e.start;0!==e.start&&(e.start=s),e.duration=r-e.start,e.startPTS=s,e.maxStartPTS=a,e.startDTS=i,e.endPTS=r,e.minEndPTS=o,e.endDTS=n;const u=e.sn;if(!t||u<t.startSN||u>t.endSN)return 0;let f;const g=u-t.startSN,m=t.fragments;for(m[g]=e,f=g;f>0;f--)Fe(m[f],m[f-1]);for(f=g;f<m.length-1;f++)Fe(m[f],m[f+1]);return t.fragmentHint&&Fe(m[m.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,c}function Ne(t,e){let s=null;const r=t.fragments;for(let t=r.length-1;t>=0;t--){const e=r[t].initSegment;if(e){s=e;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let i,n=0;if(function(t,e,s){const r=e.skippedSegments,i=Math.max(t.startSN,e.startSN)-e.startSN,n=(t.fragmentHint?1:0)+(r?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];r&&!n&&t<r&&(n=e.fragments[t]=i),i&&n&&s(i,n)}}(t,e,(t,r)=>{t.relurl&&(n=t.cc-r.cc),l(t.startPTS)&&l(t.endPTS)&&(r.start=r.startPTS=t.startPTS,r.startDTS=t.startDTS,r.maxStartPTS=t.maxStartPTS,r.endPTS=t.endPTS,r.endDTS=t.endDTS,r.minEndPTS=t.minEndPTS,r.duration=t.endPTS-t.startPTS,r.duration&&(i=r),e.PTSKnown=e.alignedSliding=!0),r.elementaryStreams=t.elementaryStreams,r.loader=t.loader,r.stats=t.stats,t.initSegment&&(r.initSegment=t.initSegment,s=t.initSegment)}),s){(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=s)?void 0:e.relurl)||(t.initSegment=s)})}if(e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(t=>!t),e.deltaUpdateFailed){v.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,s){const r=o({},t);s&&s.forEach(t=>{delete r[t]});return Object.keys(e).forEach(t=>{const s=new DateRange(e[t].attr,r[t]);s.isValid?r[t]=s:v.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[t].attr)}"`)}),r}(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(n){v.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,s){if(t&&e){let r=0;for(let i=0,n=t.length;i<=n;i++){const n=t[i],a=e[i+r];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?s(n,a):r--}}}(t.partList,e.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats}),i?Oe(e,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):Ue(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const h=e.advancedDateTime;if(e.advanced&&h){const t=e.edge;e.driftStart||(e.driftStartTime=h,e.driftStart=t),e.driftEndTime=h,e.driftEnd=t}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function Ue(t,e){const s=e.startSN+e.skippedSegments-t.startSN,r=t.fragments;s<0||s>=r.length||Be(e,r[s].start)}function Be(t,e){if(e){const s=t.fragments;for(let r=t.skippedSegments;r<s.length;r++)s[r].start+=e;t.fragmentHint&&(t.fragmentHint.start+=e)}}function $e(t,e,s){var r;return null!=t&&t.details?Ge(null==(r=t.details)?void 0:r.partList,e,s):null}function Ge(t,e,s){if(t)for(let r=t.length;r--;){const i=t[r];if(i.index===s&&i.fragment.sn===e)return i}return null}function Ke(t){t.forEach((t,e)=>{const{details:s}=t;null!=s&&s.fragments&&s.fragments.forEach(t=>{t.level=e})})}function He(t){switch(t.details){case f.FRAG_LOAD_TIMEOUT:case f.KEY_LOAD_TIMEOUT:case f.LEVEL_LOAD_TIMEOUT:case f.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ve(t,e){const s=He(e);return t.default[(s?"timeout":"error")+"Retry"]}function Ye(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function We(t){return i(i({},t),{errorRetry:null,timeoutRetry:null})}function je(t,e,s,r){if(!t)return!1;const i=null==r?void 0:r.code,n=e<t.maxNumRetry&&(function(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}(i)||!!s);return t.shouldRetry?t.shouldRetry(t,e,s,r,n):n}const qe=function(t,e){let s=0,r=t.length-1,i=null,n=null;for(;s<=r;){i=(s+r)/2|0,n=t[i];const a=e(n);if(a>0)s=i+1;else{if(!(a<0))return n;r=i-1}}return null};function Xe(t,e,s=0,r=0){let i=null;if(t){i=e[t.sn-e[0].sn+1]||null;const r=t.endDTS-s;r>0&&r<15e-7&&(s+=15e-7)}else 0===s&&0===e[0].start&&(i=e[0]);if(i&&(!t||t.level===i.level)&&0===ze(s,r,i))return i;const n=qe(e,ze.bind(null,s,r));return!n||n===t&&i?i:n}function ze(t=0,e=0,s){if(s.start<=t&&s.start+s.duration>t)return 0;const r=Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return s.start+s.duration-r<=t?1:s.start-r>t&&s.start?-1:0}function Qe(t,e,s){const r=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-r>t}var Je=0,Ze=2,ts=3,es=5,ss=0,rs=1,is=2;class BasePlaylistController{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=v.log.bind(v,`${e}:`),this.warn=v.warn.bind(v,`${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,s){const r=null==e?void 0:e.renditionReports;if(r){let i=-1;for(let s=0;s<r.length;s++){const n=r[s];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){v.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){i=s;break}a===t.substring(0,a.length)&&(i=s)}if(-1!==i){const t=r[i],n=parseInt(t["LAST-MSN"])||(null==e?void 0:e.lastPartSn);let a=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);a>=0&&t>e.partTarget&&(a+=1)}const o=s&&Me(s);return new HlsUrlParameters(n,a>=0?a:void 0,o)}}}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,s){const{details:r,stats:i}=e,n=self.performance.now(),a=i.loading.first?Math.max(0,n-i.loading.first):0;if(r.advancedDateTime=Date.now()-a,r.live||null!=s&&s.live){if(r.reloaded(s),s&&this.log(`live playlist ${t} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),s&&r.fragments.length>0&&Ne(s,r),!this.canLoad||!r.live)return;let a,o,l;if(r.canBlockReload&&r.endSN&&r.advanced){const t=this.hls.config.lowLatencyMode,i=r.lastPartSn,n=r.endSN,h=r.lastPartIndex,d=i===n;-1!==h?(o=d?n+1:i,l=d?t?0:h:h+1):o=n+1;const c=r.age,u=c+r.ageHeader;let f=Math.min(u-r.partTarget,1.5*r.targetduration);if(f>0){if(s&&f>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${f} with playlist age: ${r.age}`),f=0;else{const t=Math.floor(f/r.targetduration);if(o+=t,void 0!==l){l+=Math.round(f%r.targetduration/r.partTarget)}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${c.toFixed(2)}s goal: ${f} skip sn ${t} to part ${l}`)}r.tuneInGoal=f}if(a=this.getDeliveryDirectives(r,e.deliveryDirectives,o,l),t||!d)return void this.loadPlaylist(a)}else(r.canBlockReload||r.canSkipUntil)&&(a=this.getDeliveryDirectives(r,e.deliveryDirectives,o,l));const h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,c=function(t,e=1/0){let s=1e3*t.targetduration;if(t.updated){const r=t.fragments,i=4;if(r.length&&s*i>e){const t=1e3*r[r.length-1].duration;t<s&&(s=t)}}else s/=2;return Math.round(s)}(r,1e3*(r.edge-d));r.updated&&n>this.requestScheduled+c&&(this.requestScheduled=i.loading.start),void 0!==o&&r.canBlockReload?this.requestScheduled=i.loading.first+c-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+c<n?this.requestScheduled=n:this.requestScheduled-n<=0&&(this.requestScheduled+=c);let u=this.requestScheduled-n;u=Math.max(0,u),this.log(`reload live playlist ${t} in ${Math.round(u)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(a),u)}else this.clearTimer()}getDeliveryDirectives(t,e,s,r){let i=Me(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,r=e.part,i=we),new HlsUrlParameters(s,r,i)}checkRetry(t){const e=t.details,s=He(t),r=t.errorAction,{action:i,retryCount:n=0,retryConfig:a}=r||{},o=!!r&&!!a&&(i===es||!r.resolved&&i===Ze);if(o){var l;if(this.requestScheduled=-1,n>=a.maxNumRetry)return!1;if(s&&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=Ye(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,r.resolved=!0}return o}}class EWMA{constructor(t,e=0,s=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_=s}sample(t,e){const s=Math.pow(this.alpha_,t);this.estimate_=e*(1-s)+s*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 EwmaBandWidthEstimator{constructor(t,e,s,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new EWMA(t),this.fast_=new EWMA(e),this.defaultTTFB_=r,this.ttfb_=new EWMA(t)}update(t,e){const{slow_:s,fast_:r,ttfb_:i}=this;s.halfLife!==t&&(this.slow_=new EWMA(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.fast_=new EWMA(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new EWMA(t,i.getEstimate(),i.getTotalWeight()))}sample(t,e){const s=(t=Math.max(t,this.minDelayMs_))/1e3,r=8*e/s;this.fast_.sample(s,r),this.slow_.sample(s,r)}sampleTTFB(t){const e=t/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(s,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(){}}const ns={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},as={};function os(t,e,s,r,i,n){const a=t.audioCodec?t.audioGroups:null,o=null==n?void 0:n.audioCodec,h=null==n?void 0:n.channels,d=h?parseInt(h):o?1/0:2;let c=null;if(null!=a&&a.length)try{c=1===a.length&&a[0]?e.groups[a[0]].channels:a.reduce((t,s)=>{if(s){const r=e.groups[s];if(!r)throw new Error(`Audio track group ${s} not found`);Object.keys(r.channels).forEach(e=>{t[e]=(t[e]||0)+r.channels[e]})}return t},{2:0})}catch(t){return!0}return void 0!==t.videoCodec&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(i,8e6))||!!c&&l(d)&&Object.keys(c).some(t=>parseInt(t)>d)}function ls(t,e,s){const r=t.videoCodec,n=t.audioCodec;if(!r||!n||!s)return Promise.resolve(ns);const a={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)),framerate:t.frameRate||30},o=t.videoRange;"SDR"!==o&&(a.transferFunction=o.toLowerCase());const h=r.split(",").map(t=>({type:"media-source",video:i(i({},a),{},{contentType:Gt(t,"video")})}));return n&&t.audioGroups&&t.audioGroups.forEach(t=>{var s;t&&(null==(s=e.groups[t])||s.tracks.forEach(e=>{if(e.groupId===t){const t=e.channels||"",s=parseFloat(t);l(s)&&s>2&&h.push.apply(h,n.split(",").map(t=>({type:"media-source",audio:{contentType:Gt(t,"audio"),channels:""+s}})))}}))}),Promise.all(h.map(t=>{const e=function(t){const{audio:e,video:s}=t,r=s||e;if(r){const t=r.contentType.split('"')[1];if(s)return`r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${t}_${Math.ceil(s.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${t}`}return""}(t);return as[e]||(as[e]=s.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:h,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:h,decodingInfoResults:[],error:t}))}function hs(t,e){let s=!1,r=[];return t&&(s="SDR"!==t,r=[t]),e&&(r=e.allowedVideoRanges||Pe.slice(0),s=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}(),r=s?r.filter(t=>"SDR"!==t):["SDR"]),{preferHDR:s,allowedVideoRanges:r}}function ds(t,e){v.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function cs(t,e,s){if("attrs"in t){const s=e.indexOf(t);if(-1!==s)return s}for(let r=0;r<e.length;r++){if(us(t,e[r],s))return r}return-1}function us(t,e,s){const{groupId:r,name:i,lang:n,assocLang:a,characteristics:o,default:l}=t,h=t.forced;return(void 0===r||e.groupId===r)&&(void 0===i||e.name===i)&&(void 0===n||e.lang===n)&&(void 0===n||e.assocLang===a)&&(void 0===l||e.default===l)&&(void 0===h||e.forced===h)&&(void 0===o||function(t,e=""){const s=t.split(","),r=e.split(",");return s.length===r.length&&!s.some(t=>-1===r.indexOf(t))}(o,e.characteristics))&&(void 0===s||s(t,e))}function fs(t,e){const{audioCodec:s,channels:r}=t;return!(void 0!==s&&(e.audioCodec||"").substring(0,4)!==s.substring(0,4)||void 0!==r&&r!==(e.channels||"2"))}function gs(t,e,s){for(let r=e;r;r--)if(s(t[r]))return r;for(let r=e+1;r<t.length;r++)if(s(t[r]))return r;return-1}class TaskLoop{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(){}}var ms="NOT_LOADED",ps="APPENDING",ys="PARTIAL",vs="OK";class FragmentTracker{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(c.BUFFER_APPENDED,this.onBufferAppended,this),t.on(c.FRAG_BUFFERED,this.onFragBuffered,this),t.on(c.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(c.BUFFER_APPENDED,this.onBufferAppended,this),t.off(c.FRAG_BUFFERED,this.onFragBuffered,this),t.off(c.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const s=this.activePartLists[e];if(s)for(let e=s.length;e--;){const r=s[e];if(!r)break;const i=r.end;if(r.start<=t&&null!==i&&t<=i)return r}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){const{fragments:s}=this,r=Object.keys(s);for(let i=r.length;i--;){const n=s[r[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,s,r){this.timeRanges&&(this.timeRanges[t]=e);const i=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(r=>{const n=this.fragments[r];if(!n)return;if(i>=n.body.sn)return;if(!n.buffered&&!n.loaded)return void(n.body.type===s&&this.removeFragment(n.body));const a=n.range[t];a&&a.time.some(t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(n.body),s})})}detectPartialFragments(t){const e=this.timeRanges,{frag:s,part:r}=t;if(!e||"initSegment"===s.sn)return;const i=Ts(s),n=this.fragments[i];if(!n||n.buffered&&s.gap)return;const a=!s.relurl;if(Object.keys(e).forEach(t=>{const i=s.elementaryStreams[t];if(!i)return;const o=e[t],l=a||!0===i.partial;n.range[t]=this.getBufferedTimes(s,r,l,o)}),n.loaded=null,Object.keys(n.range).length){n.buffered=!0;(n.body.endList=s.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),Es(n)||this.removeParts(s.sn-1,s.type)}else this.removeFragment(n.body)}removeParts(t,e){const s=this.activePartLists[e];s&&(this.activePartLists[e]=s.filter(e=>e.fragment.sn>=t))}fragBuffered(t,e){const s=Ts(t);let r=this.fragments[s];!r&&e&&(r=this.fragments[s]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(t,e,s,r){const i={time:[],partial:s},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<r.length;t++){const e=r.start(t)-this.bufferPadding,s=r.end(t)+this.bufferPadding;if(l>=e&&o<=s){i.time.push({startPTS:Math.max(n,r.start(t)),endPTS:Math.min(a,r.end(t))});break}if(n<s&&a>e){const e=Math.max(n,r.start(t)),s=Math.min(a,r.end(t));s>e&&(i.partial=!0,i.time.push({startPTS:e,endPTS:s}))}else if(a<=e)break}return i}getPartialFragment(t){let e,s,r,i=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const h=o[l];h&&Es(h)&&(s=h.body.start-a,r=h.body.end+a,t>=s&&t<=r&&(e=Math.min(t-s,r-t),n<=e&&(i=h.body,n=e)))}),i}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Es(e))}getState(t){const e=Ts(t),s=this.fragments[e];return s?s.buffered?Es(s)?ys:vs:ps:ms}isTimeBuffered(t,e,s){let r,i;for(let n=0;n<s.length;n++){if(r=s.start(n)-this.bufferPadding,i=s.end(n)+this.bufferPadding,t>=r&&e<=i)return!0;if(e<=r)return!1}return!1}onFragLoaded(t,e){const{frag:s,part:r}=e;if("initSegment"===s.sn||s.bitrateTest)return;const i=r?null:e,n=Ts(s);this.fragments[n]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:r,timeRanges:i}=e;if("initSegment"===s.sn)return;const n=s.type;if(r){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(r)}this.timeRanges=i,Object.keys(i).forEach(t=>{const e=i[t];this.detectEvictedFragments(t,e,n,r)})}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Ts(t);return!!this.fragments[e]}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}removeFragmentsInRange(t,e,s,r,i){r&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==s||r&&!o.gap||o.start<e&&o.end>t&&(a.buffered||i)&&this.removeFragment(o)})}removeFragment(t){const e=Ts(t);t.stats.loaded=0,t.clearElementaryStreamInfo();const s=this.activePartLists[t.type];if(s){const e=t.sn;this.activePartLists[t.type]=s.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 Es(t){var e,s,r;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(s=t.range.audio)?void 0:s.partial)||(null==(r=t.range.audiovideo)?void 0:r.partial))}function Ts(t){return`${t.type}_${t.level}_${t.sn}`}const Ss={length:0,start:()=>0,end:()=>0};class BufferHelper{static isBuffered(t,e){try{if(t){const s=BufferHelper.getBuffered(t);for(let t=0;t<s.length;t++)if(e>=s.start(t)&&e<=s.end(t))return!0}}catch(t){}return!1}static bufferInfo(t,e,s){try{if(t){const r=BufferHelper.getBuffered(t),i=[];let n;for(n=0;n<r.length;n++)i.push({start:r.start(n),end:r.end(n)});return this.bufferedInfo(i,e,s)}}catch(t){}return{len:0,start:e,end:e,nextStart:void 0}}static bufferedInfo(t,e,s){e=Math.max(0,e),t.sort(function(t,e){const s=t.start-e.start;return s||e.end-t.end});let r=[];if(s)for(let e=0;e<t.length;e++){const i=r.length;if(i){const n=r[i-1].end;t[e].start-n<s?t[e].end>n&&(r[i-1].end=t[e].end):r.push(t[e])}else r.push(t[e])}else r=t;let i,n=0,a=e,o=e;for(let t=0;t<r.length;t++){const l=r[t].start,h=r[t].end;if(e+s>=l&&e<h)a=l,o=h,n=o-e;else if(e+s<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 v.log("failed to get media.buffered",t),Ss}}}class ChunkMetadata{constructor(t,e,s,r=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=s,this.size=r,this.part=i,this.partial=n}}function Ls(t,e){for(let r=0,i=t.length;r<i;r++){var s;if((null==(s=t[r])?void 0:s.cc)===e)return t[r]}return null}function As(t,e){if(t){const s=t.start+e;t.start=t.startPTS=s,t.endPTS=s+t.duration}}function Rs(t,e){const s=e.fragments;for(let e=0,r=s.length;e<r;e++)As(s[e],t);e.fragmentHint&&As(e.fragmentHint,t),e.alignedSliding=!0}function bs(t,e,s){e&&(!function(t,e,s){if(function(t,e,s){return!(!e||!(s.endCC>s.startCC||t&&t.cc<s.startCC))}(t,s,e)){const t=function(t,e){const s=t.fragments,r=e.fragments;if(!r.length||!s.length)return void v.log("No fragments to align");const i=Ls(s,r[0].cc);if(i&&(!i||i.startPTS))return i;v.log("No frag in previous level to align on")}(s,e);t&&l(t.start)&&(v.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),Rs(t.start,e))}}(t,s,e),!s.alignedSliding&&e&&ks(s,e),s.alignedSliding||!e||s.skippedSegments||Ue(e,s))}function ks(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,r=e.fragments;if(!s.length||!r.length)return;let i,n;const a=Math.min(e.endCC,t.endCC);e.startCC<a&&t.startCC<a&&(i=Ls(r,a),n=Ls(s,a)),i&&n||(i=r[Math.floor(r.length/2)],n=Ls(s,i.cc)||s[Math.floor(s.length/2)]);const o=i.programDateTime,l=n.programDateTime;if(!o||!l)return;Rs((l-o)/1e3-(n.start-i.start),t)}const Ds=Math.pow(2,17);class FragmentLoader{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 s=t.url;if(!s)return Promise.reject(new LoadError({type:u.NETWORK_ERROR,details:f.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void l(Ps(t));t.gap=!1}const h=this.loader=t.loader=n?new n(r):new a(r),d=Cs(t),c=We(r.fragLoadPolicy.default),g={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Ds};t.stats=h.stats,h.load(d,g,{onSuccess:(e,s,r,i)=>{this.resetLoader(t,h);let n=e.data;r.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),o({frag:t,part:null,payload:n,networkDetails:i})},onError:(e,r,n,a)=>{this.resetLoader(t,h),l(new LoadError({type:u.NETWORK_ERROR,details:f.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:i({url:s,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:n,stats:a}))},onAbort:(e,s,r)=>{this.resetLoader(t,h),l(new LoadError({type:u.NETWORK_ERROR,details:f.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:r,stats:e}))},onTimeout:(e,s,r)=>{this.resetLoader(t,h),l(new LoadError({type:u.NETWORK_ERROR,details:f.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:r,stats:e}))},onProgress:(s,r,i,n)=>{e&&e({frag:t,part:null,payload:i,networkDetails:n})}})})}loadPart(t,e,s){this.abort();const r=this.config,n=r.fLoader,a=r.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void l(Ps(t,e));const h=this.loader=t.loader=n?new n(r):new a(r),d=Cs(t,e),c=We(r.fragLoadPolicy.default),g={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ds};e.stats=h.stats,h.load(d,g,{onSuccess:(r,i,n,a)=>{this.resetLoader(t,h),this.updateStatsFromPart(t,e);const l={frag:t,part:e,payload:r.data,networkDetails:a};s(l),o(l)},onError:(s,r,n,a)=>{this.resetLoader(t,h),l(new LoadError({type:u.NETWORK_ERROR,details:f.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:i({url:d.url,data:void 0},s),error:new Error(`HTTP Error ${s.code} ${s.text}`),networkDetails:n,stats:a}))},onAbort:(s,r,i)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,h),l(new LoadError({type:u.NETWORK_ERROR,details:f.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:i,stats:s}))},onTimeout:(s,r,i)=>{this.resetLoader(t,h),l(new LoadError({type:u.NETWORK_ERROR,details:f.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:i,stats:s}))}})})}updateStatsFromPart(t,e){const s=t.stats,r=e.stats,i=r.total;if(s.loaded+=r.loaded,i){const r=Math.round(t.duration/e.duration),n=Math.min(Math.round(s.loaded/i),r),a=(r-n)*Math.round(s.loaded/n);s.total=s.loaded+a}else s.total=Math.max(s.loaded,s.total);const n=s.loading,a=r.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 Cs(t,e=null){const s=e||t,r={frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},i=s.byteRangeStartOffset,n=s.byteRangeEndOffset;if(l(i)&&l(n)){var a;let e=i,s=n;if("initSegment"===t.sn&&"AES-128"===(null==(a=t.decryptdata)?void 0:a.method)){const t=n-i;t%16&&(s=n+(16-t%16)),0!==i&&(r.resetIV=!0,e=i-16)}r.rangeStart=e,r.rangeEnd=s}return r}function Ps(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),r={type:u.MEDIA_ERROR,details:f.FRAG_GAP,fatal:!1,frag:t,error:s,networkDetails:null};return e&&(r.part=e),(e||t).stats.aborted=!0,new LoadError(r)}class LoadError extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class AESCrypto{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 FastAESKey{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 AESDecryptor{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),s=new Uint32Array(4);for(let t=0;t<4;t++)s[t]=e.getUint32(4*t);return s}initTable(){const t=this.sBox,e=this.invSBox,s=this.subMix,r=s[0],i=s[1],n=s[2],a=s[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let s=g^g<<1^g<<2^g<<3^g<<4;s=s>>>8^255&s^99,t[f]=s,e[s]=f;const o=u[f],m=u[o],p=u[m];let y=257*u[s]^16843008*s;r[f]=y<<24|y>>>8,i[f]=y<<16|y>>>16,n[f]=y<<8|y>>>24,a[f]=y,y=16843009*p^65537*m^257*o^16843008*f,l[s]=y<<24|y>>>8,h[s]=y<<16|y>>>16,d[s]=y<<8|y>>>24,c[s]=y,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let s=!0,r=0;for(;r<e.length&&s;)s=e[r]===this.key[r],r++;if(s)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),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let y,v;for(a=0;a<n;a++)a<i?y=l[a]=e[a]:(v=y,a%i===0?(v=v<<8|v>>>24,v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v],v^=c[a/i|0]<<24):i>6&&a%i===4&&(v=d[v>>>24]<<24|d[v>>>16&255]<<16|d[v>>>8&255]<<8|d[255&v]),l[a]=y=(l[a-i]^v)>>>0);for(o=0;o<n;o++)a=n-o,v=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?v:f[d[v>>>24]]^g[d[v>>>16&255]]^m[d[v>>>8&255]]^p[d[255&v]],h[o]=h[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,s){const r=this.keySize+6,i=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(s);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(t),y=new Int32Array(p.length);let v,E,T,S,L,A,R,b,k,D,C,P,w,I;const _=this.networkToHostOrderSwap;for(;e<p.length;){for(k=_(p[e]),D=_(p[e+1]),C=_(p[e+2]),P=_(p[e+3]),L=k^i[0],A=P^i[1],R=C^i[2],b=D^i[3],w=4,I=1;I<r;I++)v=o[L>>>24]^l[A>>16&255]^h[R>>8&255]^d[255&b]^i[w],E=o[A>>>24]^l[R>>16&255]^h[b>>8&255]^d[255&L]^i[w+1],T=o[R>>>24]^l[b>>16&255]^h[L>>8&255]^d[255&A]^i[w+2],S=o[b>>>24]^l[L>>16&255]^h[A>>8&255]^d[255&R]^i[w+3],L=v,A=E,R=T,b=S,w+=4;v=n[L>>>24]<<24^n[A>>16&255]<<16^n[R>>8&255]<<8^n[255&b]^i[w],E=n[A>>>24]<<24^n[R>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^i[w+1],T=n[R>>>24]<<24^n[b>>16&255]<<16^n[L>>8&255]<<8^n[255&A]^i[w+2],S=n[b>>>24]<<24^n[L>>16&255]<<16^n[A>>8&255]<<8^n[255&R]^i[w+3],y[e]=_(v^u),y[e+1]=_(S^f),y[e+2]=_(T^g),y[e+3]=_(E^m),u=k,f=D,g=C,m=P,e+=4}return y.buffer}}class Decrypter{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 s=new Uint8Array(t);return this.reset(),this.removePKCS7Padding?function(t){const e=t.byteLength,s=e&&new DataView(t.buffer).getUint8(e-1);return s?G(t,0,e-s):t}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,s){return this.useSoftware?new Promise((r,i)=>{this.softwareDecrypt(new Uint8Array(t),e,s);const n=this.flush();n?r(n.buffer):i(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,s)}softwareDecrypt(t,e,s){const{currentIV:r,currentResult:i,remainderData:n}=this;this.logOnce("JS AES decrypt"),n&&(t=Rt(n,t),this.remainderData=null);const a=this.getValidChunk(t);if(!a.length)return null;r&&(s=r);let o=this.softwareDecrypter;o||(o=this.softwareDecrypter=new AESDecryptor),o.expandKey(e);const l=i;return this.currentResult=o.decrypt(a.buffer,0,s),this.currentIV=G(a,-16).buffer,l||null}webCryptoDecrypt(t,e,s){const r=this.subtle;return this.key===e&&this.fastAesKey||(this.key=e,this.fastAesKey=new FastAESKey(r,e)),this.fastAesKey.expandKey().then(e=>{if(!r)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new AESCrypto(r,new Uint8Array(s)).decrypt(t.buffer,e)}).catch(r=>(v.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,s)))}onWebCryptoError(t,e,s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,s);const r=this.flush();if(r)return r.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(t){let e=t;const s=t.length-t.length%16;return s!==t.length&&(e=G(t,0,s),this.remainderData=G(t,s)),e}logOnce(t){this.logEnabled&&(v.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const ws=function(t){let e="";const s=t.length;for(let r=0;r<s;r++)e+=`[${t.start(r).toFixed(3)}-${t.end(r).toFixed(3)}]`;return e},Is="STOPPED",_s="IDLE",Ms="KEY_LOADING",xs="FRAG_LOADING",Fs="FRAG_LOADING_WAITING_RETRY",Os="WAITING_TRACK",Ns="PARSING",Us="PARSED",Bs="ENDED",$s="ERROR",Gs="WAITING_INIT_PTS",Ks="WAITING_LEVEL";class BaseStreamController extends TaskLoop{constructor(t,e,s,r,i){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Is,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=r,this.log=v.log.bind(v,`${r}:`),this.warn=v.warn.bind(v,`${r}:`),this.hls=t,this.fragmentLoader=new FragmentLoader(t.config),this.keyLoader=s,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Decrypter(t.config),t.on(c.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=Is}_streamEnded(t,e){if(e.live||t.nextStart||!t.end||!this.media)return!1;const s=e.partList;if(null!=s&&s.length){const t=s[s.length-1];return BufferHelper.isBuffered(this.media,t.start+t.duration/2)}const r=e.fragments[e.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(r)}getLevelDetails(){var t;if(this.levels&&null!==this.levelLastLoaded)return null==(t=this.levelLastLoaded)?void 0:t.details}onMediaAttached(t,e){const s=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),s.addEventListener("seeking",this.onvseeking),s.addEventListener("ended",this.onvended);const r=this.config;this.levels&&r.autoStartLoad&&this.state===Is&&this.startLoad(r.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:s,mediaBuffer:r,state:i}=this,n=s?s.currentTime:0,a=BufferHelper.bufferInfo(r||s,n,t.maxBufferHole);if(this.log(`media seeking to ${l(n)?n.toFixed(3):n}, state: ${i}`),this.state===Bs)this.resetLoadingState();else if(e){const s=t.maxFragLookUpTolerance,r=e.start-s,i=e.start+e.duration+s;if(!a.len||i<a.start||r>a.end){const t=n>i;(n<r||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)}}s&&(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(c.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=Is,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,s){this._loadFragForPlayback(t,e,s)}_loadFragForPlayback(t,e,s){this._doFragLoad(t,e,s,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 s=this.state;this.fragContextChanged(t)?(s===xs||!this.fragCurrent&&s===Ns)&&(this.fragmentTracker.removeFragment(t),this.state=_s):("payload"in e&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(c.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(e=>{this.state!==Is&&this.state!==$s&&(this.warn(e),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:s}=this;if(s.getState(t)===ps){const e=t.type,r=this.getFwdBufferInfo(this.mediaBuffer,e),i=Math.max(t.duration,r?r.len:this.config.maxBufferLength);this.reduceMaxBufferLength(i)&&s.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===ys&&s.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,s=null){if(!(t-e))return;const r={startOffset:t,endOffset:e,type:s};this.hls.trigger(c.BUFFER_FLUSHING,r)}_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:s}=this,{payload:r}=e,i=t.decryptdata;if(r&&r.byteLength>0&&null!=i&&i.key&&i.iv&&"AES-128"===i.method){const n=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer).catch(e=>{throw s.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(r=>{const i=self.performance.now();return s.trigger(c.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:n,tdecrypt:i}}),e.payload=r,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(e=>{this.state!==Is&&this.state!==$s&&(this.warn(e),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:e}=this;if(!e)throw new Error("init load aborted, missing levels");const s=t.frag.stats;this.state=_s,t.frag.data=new Uint8Array(t.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.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 s,r,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===de?"level":"track"} ${t.level} (frag:[${(null!=(s=t.startPTS)?s:NaN).toFixed(3)}-${(null!=(r=t.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?ws(BufferHelper.getBuffered(a)):"(detached)"})`),"initSegment"!==t.sn){var o;if(t.type!==ue){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=_s)}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=_s,a&&(!this.loadedmetadata&&t.type==de&&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:s,part:r,partsLoaded:i}=t,n=!i||0===i.length||i.some(t=>!t),a=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount+1,0,r?r.index:-1,!n);e.flush(a)}_handleFragmentLoadProgress(t){}_doFragLoad(t,e,s=null,r){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=Ms,this.fragCurrent=t,a=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(c.KEY_LOADED,t),this.state===Ms&&(this.state=_s),t}),this.hls.trigger(c.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(a=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),s=Math.max(t.start,s||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){const i=n.partList;if(i&&r){s>t.end&&n.fragmentHint&&(t=n.fragmentHint);const o=this.getNextPart(i,t,s);if(o>-1){const l=i[o];let h;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(s.toFixed(3))}`),this.nextLoadPosition=l.start+l.duration,this.state=xs,h=a?a.then(s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,l,e,r)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,l,e,r).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(c.FRAG_LOADING,{frag:t,part:l,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(i,s))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(s.toFixed(3))}`),l(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=xs;const o=this.config.progressive;let h;return h=o&&a?a.then(e=>!e||this.fragContextChanged(null==e?void 0:e.frag)?null:this.fragmentLoader.load(t,r)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,o?r:void 0),a]).then(([t])=>(!o&&t&&r&&r(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(c.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,e,s,r){return new Promise((i,n)=>{var a;const o=[],l=null==(a=s.details)?void 0:a.partList,h=e=>{this.fragmentLoader.loadPart(t,e,r).then(r=>{o[e.index]=r;const n=r.part;this.hls.trigger(c.FRAG_LOADED,r);const a=$e(s,t.sn,e.index+1)||Ge(l,t.sn,e.index+1);if(!a)return i({frag:t,part:n,partsLoaded:o});h(a)}).catch(n)};h(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===f.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(c.ERROR,e)}else this.hls.trigger(c.ERROR,{type:u.OTHER_ERROR,details:f.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==Ns)return void(this.fragCurrent||this.state===Is||this.state===$s||(this.state=_s));const{frag:s,part:r,level:i}=e,n=self.performance.now();s.stats.parsing.end=n,r&&(r.stats.parsing.end=n),this.updateLevelTiming(s,r,i,t.partial)}getCurrentContext(t){const{levels:e,fragCurrent:s}=this,{level:r,sn:i,part:n}=t;if(null==e||!e[r])return this.warn(`Levels object was unset while buffering fragment ${i} of level ${r}. The current chunk will not be buffered.`),null;const a=e[r],o=n>-1?$e(a,i,n):null,l=o?o.fragment:function(t,e,s){if(null==t||!t.details)return null;const r=t.details;let i=r.fragments[e-r.startSN];return i||(i=r.fragmentHint,i&&i.sn===e?i:e<r.startSN&&s&&s.sn===e?s:null)}(a,i,s);return l?(s&&s!==l&&(l.stats=s.stats),{frag:l,part:o,level:a}):null}bufferFragmentData(t,e,s,r,i){var n;if(!t||this.state!==Ns)return;const{data1:a,data2:o}=t;let l=a;if(a&&o&&(l=Rt(a,o)),null==(n=l)||!n.length)return;const h={type:t.type,frag:e,part:s,chunkMeta:r,parent:e.type,data:l};if(this.hls.trigger(c.BUFFER_APPENDING,h),t.dropped&&t.independent&&!s){if(i)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!BufferHelper.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const s=e.currentTime,r=BufferHelper.bufferInfo(e,s,0),i=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*i),a=Math.max(Math.min(t.start-n,r.end-n),s+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){const s=this.getLoadPosition();return l(s)?this.getFwdBufferInfoAtPos(t,s,e):null}getFwdBufferInfoAtPos(t,e,s){const{config:{maxBufferHole:r}}=this,i=BufferHelper.bufferInfo(t,e,r);if(0===i.len&&void 0!==i.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,s);if(n&&i.nextStart<n.end)return BufferHelper.bufferInfo(t,e,Math.max(i.nextStart,r))}return i}getMaxBufferLength(t){const{config:e}=this;let s;return s=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(s,e.maxMaxBufferLength)}reduceMaxBufferLength(t){const e=this.config,s=t||e.maxBufferLength;return e.maxMaxBufferLength>=s&&(e.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${e.maxMaxBufferLength}s`),!0)}getAppendedFrag(t,e=de){const s=this.fragmentTracker.getAppendedFrag(t,de);return s&&"fragment"in s?s.fragment:s}getNextFragment(t,e){const s=e.fragments,r=s.length;if(!r)return null;const{config:i}=this,n=s[0].start;let a;if(e.live){const o=i.initialLiveManifestSize;if(r<o)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${o})`),null;(!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n)&&(a=this.getInitialLiveFragment(e,s),this.startPosition=this.nextLoadPosition=a?this.hls.liveSyncPosition||a.start:t)}else t<=n&&(a=s[0]);if(!a){const s=i.lowLatencyMode?e.partEnd:e.fragmentEnd;a=this.getFragmentAtPosition(t,s,e)}return this.mapToInitFragWhenRequired(a)}isLoopLoading(t,e){const s=this.fragmentTracker.getState(t);return(s===vs||s===ys&&!!t.gap)&&this.nextLoadPosition>e}getNextFragmentLoopLoading(t,e,s,r,i){const n=t.gap,a=this.getNextFragment(this.nextLoadPosition,e);if(null===a)return a;if(t=a,n&&t&&!t.gap&&s.nextStart){const e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,r);if(null!==e&&s.len+e.len>=i)return this.log(`buffer full after gaps in "${r}" 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,s){let r=-1,i=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,r>-1&&s<o.start)break;const l=o.loaded;l?r=-1:(i||o.independent||n)&&o.fragment===e&&(r=a),i=l}return r}loadedEndOfParts(t,e){const s=t[t.length-1];return s&&e>s.start&&s.loaded}getInitialLiveFragment(t,e){const s=this.fragPrevious;let r=null;if(s){if(t.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),r=function(t,e,s){if(null===e||!Array.isArray(t)||!t.length||!l(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;s=s||0;for(let r=0;r<t.length;++r){const i=t[r];if(Qe(e,s,i))return i}return null}(e,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){const i=s.sn+1;if(i>=t.startSN&&i<=t.endSN){const n=e[i-t.startSN];s.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=function(t,e){return qe(t,t=>t.cc<e?1:t.cc>e?-1:0)}(e,s.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(r=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r}getFragmentAtPosition(t,e,s){const{config:r}=this;let{fragPrevious:i}=this,{fragments:n,endSN:a}=s;const{fragmentHint:o}=s,l=r.maxFragLookUpTolerance,h=s.partList,d=!!(r.lowLatencyMode&&null!=h&&h.length&&o);let c;if(d&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),t<e){c=Xe(i,n,t,t>e-l?0:l)}else c=n[n.length-1];if(c){const t=c.sn-s.startSN,e=this.fragmentTracker.getState(c);if((e===vs||e===ys&&c.gap)&&(i=c),i&&c.sn===i.sn&&(!d||h[0].fragment.sn>c.sn)){if(i&&c.level===i.level){const e=n[t+1];c=c.sn<a&&this.fragmentTracker.getState(e)!==vs?e:null}}}return c}synchronizeToLiveEdge(t){const{config:e,media:s}=this;if(!s)return;const r=this.hls.liveSyncPosition,i=s.currentTime,n=t.fragments[0].start,a=t.edge,o=i>=n-e.maxFragLookUpTolerance&&i<=a;if(null!==r&&s.duration>r&&(i<r||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;(!o&&s.readyState<4||i<a-n)&&(this.loadedmetadata||(this.nextLoadPosition=r),s.readyState&&(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${r.toFixed(3)}`),s.currentTime=r))}}alignPlaylists(t,e,s){const r=t.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const i=t.fragments[0].start,n=!e,a=t.alignedSliding&&l(i);if(n||!a&&!i){const{fragPrevious:i}=this;bs(i,s,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: ${r}`),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 s=this.startPosition;if(s<e&&(s=-1),-1===s||-1===this.lastCurrentTime){const r=null!==this.startTimeOffset,i=r?this.startTimeOffset:t.startTimeOffset;null!==i&&l(i)?(s=e+i,i<0&&(s+=t.totalduration),s=Math.min(Math.max(e,s),e+t.totalduration),this.log(`Start time offset ${i} found in ${r?"multivariant":"media"} playlist, adjust startPosition to ${s}`),this.startPosition=s):t.live?s=this.hls.liveSyncPosition||e:this.startPosition=s=0,this.lastCurrentTime=s}this.nextLoadPosition=s}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===Fs)||(this.state=_s)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const s=e.frag;if(!s||s.type!==t||!this.levels)return;var r;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);const i=e.details===f.FRAG_GAP;i&&this.fragmentTracker.fragBuffered(s,!0);const n=e.errorAction,{action:a,retryCount:o=0,retryConfig:l}=n||{};if(n&&a===es&&l){this.resetStartWhenNotLoaded(this.levelLastLoaded);const r=Ye(l,o);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${o+1}/${l.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=Fs}else if(l&&n){if(this.resetFragmentErrors(t),!(o<l.maxNumRetry))return void v.warn(`${e.details} reached or exceeded max retry (${o})`);i||a===ts||(n.resolved=!0)}else(null==n?void 0:n.action)===Ze?this.state=Ks:this.state=$s;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===Ns||this.state===Us){const e=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,e),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len);const i=!r;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===ce&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Is&&(this.state=_s)}afterBufferFlushed(t,e,s){if(!t)return;const r=BufferHelper.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,s),this.state===Bs&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=_s}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,s,r){var i;const n=s.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=r?0:Oe(n,t,a.startPTS,a.endPTS,a.startDTS,a.endDTS);return this.hls.trigger(c.LEVEL_PTS_UPDATED,{details:n,level:s,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===s.fragmentError&&(s.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(e.message),this.hls.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!1,error:e,frag:t,reason:`Found no media in msn ${t.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Us,this.hls.trigger(c.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}}class ChunkCache{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let s;return t.length?(s=1===t.length?t[0]:function(t,e){const s=new Uint8Array(e);let r=0;for(let e=0;e<t.length;e++){const i=t[e];s.set(i,r),r+=i.length}return s}(t,e),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function Hs(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class BaseAudioDemuxer{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,s,r){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,s){}demux(t,e){this.cachedData&&(t=Rt(this.cachedData,t),this.cachedData=null);let s,r=V(t,0),i=r?r.length:0;const n=this._audioTrack,a=this._id3Track,o=r?j(r):void 0,h=t.length;for((null===this.basePTS||0===this.frameIndex&&l(o))&&(this.basePTS=Vs(o,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Te,duration:Number.POSITIVE_INFINITY});i<h;){if(this.canParse(t,i)){const e=this.appendFrame(n,t,i);e?(this.frameIndex++,this.lastPTS=e.sample.pts,i+=e.length,s=i):i=h}else W(t,i)?(r=V(t,i),a.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Te,duration:Number.POSITIVE_INFINITY}),i+=r.length,s=i):i++;if(i===h&&s!==h){const e=G(t,s);this.cachedData?this.cachedData=Rt(this.cachedData,e):this.cachedData=e}}return{audioTrack:n,videoTrack:Hs(),id3Track:a,textTrack:Hs()}}demuxSampleAes(t,e,s){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:Hs(),id3Track:this._id3Track,textTrack:Hs()}}destroy(){}}const Vs=(t,e,s)=>{if(l(t))return 90*t;return 9e4*e+(s?9e4*s.baseTime/s.timescale:0)};function Ys(t,e){return 255===t[e]&&240==(246&t[e+1])}function Ws(t,e){return 1&t[e+1]?7:9}function js(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function qs(t,e){return e+1<t.length&&Ys(t,e)}function Xs(t,e){if(qs(t,e)){const s=Ws(t,e);if(e+s>=t.length)return!1;const r=js(t,e);if(r<=s)return!1;const i=e+r;return i===t.length||qs(t,i)}return!1}function zs(t,e,s,r,i){if(!t.samplerate){const n=function(t,e,s,r){let i,n,a,o;const l=navigator.userAgent.toLowerCase(),h=r,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=((192&e[s+2])>>>6)+1;const g=(60&e[s+2])>>>2;if(g>d.length-1){const e=new Error(`invalid ADTS sampling index:${g}`);return void t.emit(c.ERROR,c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}return a=(1&e[s+2])<<2,a|=(192&e[s+3])>>>6,v.log(`manifest codec:${r}, ADTS type:${i}, samplingIndex:${g}`),/firefox/i.test(l)?g>=6?(i=5,o=new Array(4),n=g-3):(i=2,o=new Array(2),n=g):-1!==l.indexOf("android")?(i=2,o=new Array(2),n=g):(i=5,o=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&g>=6?n=g-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(g>=6&&1===a||/vivaldi/i.test(l))||!r&&1===a)&&(i=2,o=new Array(2)),n=g)),o[0]=i<<3,o[0]|=(14&g)>>1,o[1]|=(1&g)<<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:d[g],channelCount:a,codec:"mp4a.40."+i,manifestCodec:h}}(e,s,r,i);if(!n)return;t.config=n.config,t.samplerate=n.samplerate,t.channelCount=n.channelCount,t.codec=n.codec,t.manifestCodec=n.manifestCodec,v.log(`parsed codec:${t.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function Qs(t){return 9216e4/t}function Js(t,e,s,r,i){const n=r+i*Qs(t.samplerate),a=function(t,e){const s=Ws(t,e);if(e+s<=t.length){const r=js(t,e)-s;if(r>0)return{headerLength:s,frameLength:r}}}(e,s);let o;if(a){const{frameLength:r,headerLength:i}=a,l=i+r,h=Math.max(0,s+l-e.length);h?(o=new Uint8Array(l-i),o.set(e.subarray(s+i,e.length),0)):o=e.subarray(s+i,s+l);const d={unit:o,pts:n};return h||t.samples.push(d),{sample:d,length:l,missing:h}}const l=e.length-s;o=new Uint8Array(l),o.set(e.subarray(s,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let Zs=null;const tr=[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],er=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],sr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],rr=[0,1,1,4];function ir(t,e,s,r,i){if(s+24>e.length)return;const n=nr(e,s);if(n&&s+n.frameLength<=e.length){const a=r+i*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(s,s+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 nr(t,e){const s=t[e+1]>>3&3,r=t[e+1]>>1&3,i=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==s&&0!==i&&15!==i&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*tr[14*(3===s?3-r:3===r?3:4)+i-1],h=er[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=sr[s][r],u=rr[r],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===Zs){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Zs=t?parseInt(t[1]):0}return!!Zs&&Zs<=87&&2===r&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function ar(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function or(t,e){return e+1<t.length&&ar(t,e)}function lr(t,e){if(e+1<t.length&&ar(t,e)){const s=4,r=nr(t,e);let i=s;null!=r&&r.frameLength&&(i=r.frameLength);const n=e+i;return n===t.length||or(t,n)}return!1}const hr=/\/emsg[-/]ID3/i;const dr=(t,e)=>{let s=0,r=5;e+=r;const i=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;r>0;){a[0]=t[e];const o=Math.min(r,8),l=8-o;n[0]=4278190080>>>24+l<<l,i[0]=(a[0]&n[0])>>l,s=s?s<<o|i[0]:i[0],e+=1,r-=o}return s};class AC3Demuxer extends BaseAudioDemuxer{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,s,r){super.resetInitSegment(t,e,s,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,s){const r=cr(t,e,s,this.basePTS,this.frameIndex);if(-1!==r){return{sample:t.samples[t.samples.length-1],length:r,missing:0}}}static probe(t){if(!t)return!1;const e=V(t,0);if(!e)return!1;const s=e.length;return 11===t[s]&&119===t[s+1]&&void 0!==j(e)&&dr(t,s)<16}}function cr(t,e,s,r,i){if(s+8>e.length)return-1;if(11!==e[s]||119!==e[s+1])return-1;const n=e[s+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[s+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(s+l>e.length)return-1;const h=e[s+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(e[s+6]<<8|e[s+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=e[s+5]>>3,g=7&e[s+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=r+i*(1536/a*9e4),y=e.subarray(s,s+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:y,pts:p}),l}class BaseVideoParser{constructor(){this.VideoSample=null}createVideoSample(t,e,s,r){return{key:t,frame:!1,pts:e,dts:s,units:[],debug:r,length:0}}getLastNalUnit(t){var e;let s,r=this.VideoSample;if(r&&0!==r.units.length||(r=t[t.length-1]),null!=(e=r)&&e.units){const t=r.units;s=t[t.length-1]}return s}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const s=e.samples,r=s.length;if(!r)return void e.dropped++;{const e=s[r-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}t.debug.length&&v.log(t.pts+"/"+t.dts+":"+t.debug)}}class ExpGolomb{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,s=t.byteLength-e,r=new Uint8Array(4),i=Math.min(4,e);if(0===i)throw new Error("no bytes available");r.set(t.subarray(s,s+i)),this.word=new DataView(r.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 s=this.word>>>32-e;if(t>32&&v.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?s<<e|this.readBits(e):s}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,s=8,r=8;for(let i=0;i<t;i++)0!==r&&(e=this.readEG(),r=(s+e+256)%256),s=0===r?s:r}readSPS(){let t,e,s,r=0,i=0,n=0,a=0;const o=this.readUByte.bind(this),l=this.readBits.bind(this),h=this.readUEG.bind(this),d=this.readBoolean.bind(this),c=this.skipBits.bind(this),u=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);o();const m=o();if(l(5),c(3),o(),f(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){const t=h();if(3===t&&c(1),f(),f(),c(1),d())for(e=3!==t?8:12,s=0;s<e;s++)d()&&g(s<6?16:64)}f();const p=h();if(0===p)h();else if(1===p)for(c(1),u(),u(),t=h(),s=0;s<t;s++)u();f(),c(1);const y=h(),v=h(),E=l(1);0===E&&c(1),c(1),d()&&(r=h(),i=h(),n=h(),a=h());let T=[1,1];if(d()&&d()){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*(y+1)-2*r-2*i),height:(2-E)*(v+1)*16-(E?2:4)*(n+a),pixelRatio:T}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class AvcVideoParser extends BaseVideoParser{parseAVCPES(t,e,s,r,i){const n=this.parseAVCNALu(t,s.data);let a,o=this.VideoSample,l=!1;s.data=null,o&&n.length&&!t.audFound&&(this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"")),n.forEach(r=>{var n;switch(r.type){case 1:{let e=!1;a=!0;const i=r.data;if(l&&i.length>4){const t=new ExpGolomb(i).readSliceType();2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=o)&&h.frame&&!o.key&&(this.pushAccessUnit(o,t),o=this.VideoSample=null);o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.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,s.pts,s.dts,"")),o.key=!0,o.frame=!0;break;case 6:a=!0,Dt(r.data,1,s.pts,e.samples);break;case 7:{var d,c;a=!0,l=!0;const e=r.data,s=new ExpGolomb(e).readSPS();if(!t.sps||t.width!==s.width||t.height!==s.height||(null==(d=t.pixelRatio)?void 0:d[0])!==s.pixelRatio[0]||(null==(c=t.pixelRatio)?void 0:c[1])!==s.pixelRatio[1]){t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e],t.duration=i;const r=e.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let e=r[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}break}case 8:a=!0,t.pps=[r.data];break;case 9:a=!0,t.audFound=!0,o&&this.pushAccessUnit(o,t),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"");break;case 12:a=!0;break;default:a=!1,o&&(o.debug+="unknown NAL "+r.type+" ")}if(o&&a){o.units.push(r)}}),r&&o&&(this.pushAccessUnit(o,t),this.VideoSample=null)}parseAVCNALu(t,e){const s=e.byteLength;let r=t.naluState||0;const i=r,n=[];let a,o,l,h=0,d=-1,c=0;for(-1===r&&(d=0,c=31&e[0],r=0,h=1);h<s;)if(a=e[h++],r)if(1!==r)if(a)if(1===a){if(o=h-r-1,d>=0){const t={data:e.subarray(d,o),type:c};n.push(t)}else{const s=this.getLastNalUnit(t.samples);s&&(i&&h<=4-i&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-i)),o>0&&(s.data=Rt(s.data,e.subarray(0,o)),s.state=0))}h<s?(l=31&e[h],d=h,c=l,r=0):r=-1}else r=0;else r=3;else r=a?0:2;else r=a?0:1;if(d>=0&&r>=0){const t={data:e.subarray(d,s),type:c,state:r};n.push(t)}if(0===n.length){const s=this.getLastNalUnit(t.samples);s&&(s.data=Rt(s.data,e))}return t.naluState=r,n}}class SampleAesDecrypter{constructor(t,e,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Decrypter(e,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(t,e,s){const r=t[e].unit;if(r.length<=16)return;const i=r.subarray(16,r.length-r.length%16),n=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(n).then(i=>{const n=new Uint8Array(i);r.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,s)})}decryptAacSamples(t,e,s){for(;;e++){if(e>=t.length)return void s();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,s=new Int8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)s.set(t.subarray(e,e+16),r);return s}getAvcDecryptedUnit(t,e){const s=new Uint8Array(e);let r=0;for(let e=32;e<t.length-16;e+=160,r+=16)t.set(s.subarray(r,r+16),e);return t}decryptAvcSample(t,e,s,r,i){const n=Ct(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,s+1,r)})}decryptAvcSamples(t,e,s,r){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,s=0){if(e>=t.length)return void r();const i=t[e].units;for(;!(s>=i.length);s++){const n=i[s];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,s,r,n),this.decrypter.isSync())))return}}}}const ur=188;class TSDemuxer{constructor(t,e,s){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=s,this.videoParser=new AvcVideoParser}static probe(t){const e=TSDemuxer.syncOffset(t);return e>0&&v.warn(`MPEG2-TS detected but first sync word found @ offset ${e}`),-1!==e}static syncOffset(t){const e=t.length;let s=Math.min(940,e-ur)+1,r=0;for(;r<s;){let i=!1,n=-1,a=0;for(let o=r;o<e;o+=ur){if(71!==t[o]||e-o!==ur&&71!==t[o+ur]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(s=Math.min(n+18612,t.length-ur)+1)),i||(i=0===fr(t,o)),i&&a>1&&(0===n&&a>2||o+ur>s))return n}r++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:lt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,s,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=TSDemuxer.createTrack("video"),this._audioTrack=TSDemuxer.createTrack("audio",r),this._id3Track=TSDemuxer.createTrack("id3"),this._txtTrack=TSDemuxer.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,s=!1,r=!1){let i;s||(this.sampleAes=null);const n=this._videoTrack,a=this._audioTrack,o=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,g=a.pid,m=o.pid,p=a.pesData,y=o.pesData,E=null,T=this.pmtParsed,S=this._pmtId,L=t.length;if(this.remainderData&&(L=(t=Rt(this.remainderData,t)).length,this.remainderData=null),L<ur&&!r)return this.remainderData=t,{audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};const A=Math.max(0,TSDemuxer.syncOffset(t));L-=(L-A)%ur,L<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,L,t.buffer.byteLength-L));let R=0;for(let e=A;e<L;e+=ur)if(71===t[e]){const r=!!(64&t[e+1]),c=fr(t,e);let u;if((48&t[e+3])>>4>1){if(u=e+5+t[e+4],u===e+ur)continue}else u=e+4;switch(c){case h:r&&(d&&(i=yr(d))&&this.videoParser.parseAVCPES(n,l,i,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(t.subarray(u,e+ur)),d.size+=e+ur-u);break;case g:if(r){if(p&&(i=yr(p)))switch(a.segmentCodec){case"aac":this.parseAACPES(a,i);break;case"mp3":this.parseMPEGPES(a,i);break;case"ac3":this.parseAC3PES(a,i)}p={data:[],size:0}}p&&(p.data.push(t.subarray(u,e+ur)),p.size+=e+ur-u);break;case m:r&&(y&&(i=yr(y))&&this.parseID3PES(o,i),y={data:[],size:0}),y&&(y.data.push(t.subarray(u,e+ur)),y.size+=e+ur-u);break;case 0:r&&(u+=t[u]+1),S=this._pmtId=gr(t,u);break;case S:{r&&(u+=t[u]+1);const i=mr(t,u,this.typeSupported,s);h=i.videoPid,h>0&&(n.pid=h,n.segmentCodec=i.segmentVideoCodec),g=i.audioPid,g>0&&(a.pid=g,a.segmentCodec=i.segmentAudioCodec),m=i.id3Pid,m>0&&(o.pid=m),null===E||T||(v.warn(`MPEG-TS PMT found at ${e} after unknown PID '${E}'. Backtracking to sync byte @${A} to parse all TS packets.`),E=null,e=A-188),T=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=c}}else R++;if(R>0){const t=new Error(`Found ${R} TS packet/s that do not start with 0x47`);this.observer.emit(c.ERROR,c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message})}n.pesData=d,a.pesData=p,o.pesData=y;const b={audioTrack:a,videoTrack:n,id3Track:o,textTrack:l};return r&&this.extractRemainingSamples(b),b}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:s,id3Track:r,textTrack:i}=t,n=s.pesData,a=e.pesData,o=r.pesData;let l;if(n&&(l=yr(n))?(this.videoParser.parseAVCPES(s,i,l,!0,this._duration),s.pesData=null):s.pesData=n,a&&(l=yr(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l);break;case"ac3":this.parseAC3PES(e,l)}e.pesData=null}else null!=a&&a.size&&v.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=yr(o))?(this.parseID3PES(r,l),r.pesData=null):r.pesData=o}demuxSampleAes(t,e,s){const r=this.demux(t,s,!0,!this.config.progressive),i=this.sampleAes=new SampleAesDecrypter(this.observer,this.config,e);return this.decrypt(r,i)}decrypt(t,e){return new Promise(s=>{const{audioTrack:r,videoTrack:i}=t;r.samples&&"aac"===r.segmentCodec?e.decryptAacSamples(r.samples,0,()=>{i.samples?e.decryptAvcSamples(i.samples,0,0,()=>{s(t)}):s(t)}):i.samples&&e.decryptAvcSamples(i.samples,0,0,()=>{s(t)})})}destroy(){this._duration=0}parseAACPES(t,e){let s=0;const r=this.aacOverFlow;let i,n,a,o=e.data;if(r){this.aacOverFlow=null;const e=r.missing,i=r.sample.unit.byteLength;if(-1===e)o=Rt(r.sample.unit,o);else{const n=i-e;r.sample.unit.set(o.subarray(0,e),n),t.samples.push(r.sample),s=r.missing}}for(i=s,n=o.length;i<n-1&&!qs(o,i);i++);if(i!==s){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 s=new Error(t);if(v.warn(`parsing error: ${t}`),this.observer.emit(c.ERROR,c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!1,levelRetry:e,error:s,reason:t}),!e)return}if(zs(t,this.observer,o,i,this.audioCodec),void 0!==e.pts)a=e.pts;else{if(!r)return void v.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Qs(t.samplerate);a=r.sample.pts+e}}let l,h=0;for(;i<n;){if(l=Js(t,o,i,a,h),i+=l.length,l.missing){this.aacOverFlow=l;break}for(h++;i<n-1&&!qs(o,i);i++);}}parseMPEGPES(t,e){const s=e.data,r=s.length;let i=0,n=0;const a=e.pts;if(void 0!==a)for(;n<r;)if(or(s,n)){const e=ir(t,s,n,a,i);if(!e)break;n+=e.length,i++}else n++;else v.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const s=e.data,r=e.pts;if(void 0===r)return void v.warn("[tsdemuxer]: AC3 PES unknown PTS");const i=s.length;let n,a=0,o=0;for(;o<i&&(n=cr(t,s,o,r,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void v.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=o({},e,{type:this._videoTrack?Le:Te,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function fr(t,e){return((31&t[e+1])<<8)+t[e+2]}function gr(t,e){return(31&t[e+10])<<8|t[e+11]}function mr(t,e,s,r){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=fr(t,e),a=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!r){pr("ADTS AAC");break}case 15:-1===i.audioPid&&(i.audioPid=n);break;case 21:-1===i.id3Pid&&(i.id3Pid=n);break;case 219:if(!r){pr("H.264");break}case 27:-1===i.videoPid&&(i.videoPid=n,i.segmentVideoCodec="avc");break;case 3:case 4:s.mpeg||s.mp3?-1===i.audioPid&&(i.audioPid=n,i.segmentAudioCodec="mp3"):v.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){pr("AC-3");break}case 129:s.ac3?-1===i.audioPid&&(i.audioPid=n,i.segmentAudioCodec="ac3"):v.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===i.audioPid&&a>0){let r=e+5,o=a;for(;o>2;){if(106===t[r])!0!==s.ac3?v.log("AC-3 audio found, not supported in this browser for now"):(i.audioPid=n,i.segmentAudioCodec="ac3");const e=t[r+1]+2;r+=e,o-=e}}break;case 194:case 135:v.warn("Unsupported EC-3 in M2TS found");break;case 36:v.warn("Unsupported HEVC in M2TS found")}e+=a+5}return i}function pr(t){v.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function yr(t){let e,s,r,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]=Rt(o[0],o[1]),o.splice(1,1);e=o[0];if(1===(e[0]<<16)+(e[1]<<8)+e[2]){if(s=(e[4]<<8)+e[5],s&&s>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&&(v.warn(`${Math.round((i-n)/9e4)}s delta between PTS and DTS, align them`),i=n)):n=i),r=e[8];let h=r+9;if(t.size<=h)return null;t.size-=h;const d=new Uint8Array(t.size);for(let t=0,s=o.length;t<s;t++){e=o[t];let s=e.byteLength;if(h){if(h>s){h-=s;continue}e=e.subarray(h),s-=h,h=0}d.set(e,a),a+=s}return s&&(s-=r+3),{data:d,pts:i,dts:n,len:s}}return null}class AAC{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 vr=Math.pow(2,32)-1;class MP4{static init(){let t;for(t in MP4.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:[]},MP4.types)MP4.types.hasOwnProperty(t)&&(MP4.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]),s=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]);MP4.HDLR_TYPES={video:e,audio:s};const r=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]);MP4.STTS=MP4.STSC=MP4.STCO=i,MP4.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),MP4.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),MP4.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),MP4.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]);MP4.FTYP=MP4.box(MP4.types.ftyp,n,o,n,a),MP4.DINF=MP4.box(MP4.types.dinf,MP4.box(MP4.types.dref,r))}static box(t,...e){let s=8,r=e.length;const i=r;for(;r--;)s+=e[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),r=0,s=8;r<i;r++)n.set(e[r],s),s+=e[r].byteLength;return n}static hdlr(t){return MP4.box(MP4.types.hdlr,MP4.HDLR_TYPES[t])}static mdat(t){return MP4.box(MP4.types.mdat,t)}static mdhd(t,e){e*=t;const s=Math.floor(e/(vr+1)),r=Math.floor(e%(vr+1));return MP4.box(MP4.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,s>>24,s>>16&255,s>>8&255,255&s,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(t){return MP4.box(MP4.types.mdia,MP4.mdhd(t.timescale,t.duration),MP4.hdlr(t.type),MP4.minf(t))}static mfhd(t){return MP4.box(MP4.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?MP4.box(MP4.types.minf,MP4.box(MP4.types.smhd,MP4.SMHD),MP4.DINF,MP4.stbl(t)):MP4.box(MP4.types.minf,MP4.box(MP4.types.vmhd,MP4.VMHD),MP4.DINF,MP4.stbl(t))}static moof(t,e,s){return MP4.box(MP4.types.moof,MP4.mfhd(t),MP4.traf(s,e))}static moov(t){let e=t.length;const s=[];for(;e--;)s[e]=MP4.trak(t[e]);return MP4.box.apply(null,[MP4.types.moov,MP4.mvhd(t[0].timescale,t[0].duration)].concat(s).concat(MP4.mvex(t)))}static mvex(t){let e=t.length;const s=[];for(;e--;)s[e]=MP4.trex(t[e]);return MP4.box.apply(null,[MP4.types.mvex,...s])}static mvhd(t,e){e*=t;const s=Math.floor(e/(vr+1)),r=Math.floor(e%(vr+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,s>>24,s>>16&255,s>>8&255,255&s,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return MP4.box(MP4.types.mvhd,i)}static sdtp(t){const e=t.samples||[],s=new Uint8Array(4+e.length);let r,i;for(r=0;r<e.length;r++)i=e[r].flags,s[r+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return MP4.box(MP4.types.sdtp,s)}static stbl(t){return MP4.box(MP4.types.stbl,MP4.stsd(t),MP4.box(MP4.types.stts,MP4.STTS),MP4.box(MP4.types.stsc,MP4.STSC),MP4.box(MP4.types.stsz,MP4.STSZ),MP4.box(MP4.types.stco,MP4.STCO))}static avc1(t){let e,s,r,i=[],n=[];for(e=0;e<t.sps.length;e++)s=t.sps[e],r=s.byteLength,i.push(r>>>8&255),i.push(255&r),i=i.concat(Array.prototype.slice.call(s));for(e=0;e<t.pps.length;e++)s=t.pps[e],r=s.byteLength,n.push(r>>>8&255),n.push(255&r),n=n.concat(Array.prototype.slice.call(s));const a=MP4.box(MP4.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,h=t.pixelRatio[0],d=t.pixelRatio[1];return MP4.box(MP4.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,MP4.box(MP4.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),MP4.box(MP4.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(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 MP4.box(MP4.types.mp4a,MP4.audioStsd(t),MP4.box(MP4.types.esds,MP4.esds(t)))}static mp3(t){return MP4.box(MP4.types[".mp3"],MP4.audioStsd(t))}static ac3(t){return MP4.box(MP4.types["ac-3"],MP4.audioStsd(t),MP4.box(MP4.types.dac3,t.config))}static stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp3(t)):"ac3"===t.segmentCodec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.ac3(t)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp4a(t)):MP4.box(MP4.types.stsd,MP4.STSD,MP4.avc1(t))}static tkhd(t){const e=t.id,s=t.duration*t.timescale,r=t.width,i=t.height,n=Math.floor(s/(vr+1)),a=Math.floor(s%(vr+1));return MP4.box(MP4.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,r>>8&255,255&r,0,0,i>>8&255,255&i,0,0]))}static traf(t,e){const s=MP4.sdtp(t),r=t.id,i=Math.floor(e/(vr+1)),n=Math.floor(e%(vr+1));return MP4.box(MP4.types.traf,MP4.box(MP4.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),MP4.box(MP4.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])),MP4.trun(t,s.length+16+20+8+16+8+8),s)}static trak(t){return t.duration=t.duration||4294967295,MP4.box(MP4.types.trak,MP4.tkhd(t),MP4.mdia(t))}static trex(t){const e=t.id;return MP4.box(MP4.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 s=t.samples||[],r=s.length,i=12+16*r,n=new Uint8Array(i);let a,o,l,h,d,c;for(e+=8+i,n.set(["video"===t.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<r;a++)o=s[a],l=o.duration,h=o.size,d=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return MP4.box(MP4.types.trun,n)}static initSegment(t){MP4.types||MP4.init();const e=MP4.moov(t);return Rt(MP4.FTYP,e)}}MP4.types=void 0,MP4.HDLR_TYPES=void 0,MP4.STTS=void 0,MP4.STSC=void 0,MP4.STCO=void 0,MP4.STSZ=void 0,MP4.VMHD=void 0,MP4.SMHD=void 0,MP4.STSD=void 0,MP4.FTYP=void 0,MP4.DINF=void 0;function Er(t,e,s=1,r=!1){const i=t*e*s;return r?Math.round(i):i}function Tr(t,e=!1){return Er(t,1e3,1/9e4,e)}let Sr,Lr=null,Ar=null;class MP4Remuxer{constructor(t,e,s,r=""){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=s,this.ISGenerated=!1,null===Lr){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Lr=t?parseInt(t[1]):0}if(null===Ar){const t=navigator.userAgent.match(/Safari\/(\d+)/i);Ar=t?parseInt(t[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){v.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){v.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){v.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let e=!1;const s=t.reduce((t,s)=>{const r=s.pts-t;return r<-4294967296?(e=!0,Rr(t,s.pts)):r>0?t:s.pts},t[0].pts);return e&&v.debug("PTS rollover detected"),s}remux(t,e,s,r,i,n,a,o){let l,h,d,c,u,f,g=i,m=i;const p=t.pid>-1,y=e.pid>-1,E=e.samples.length,T=t.samples.length>0,S=a&&E>0||E>1;if((!p||T)&&(!y||S)||this.ISGenerated||a){if(this.ISGenerated){var L,A,R,b;const t=this.videoTrackConfig;!t||e.width===t.width&&e.height===t.height&&(null==(L=e.pixelRatio)?void 0:L[0])===(null==(A=t.pixelRatio)?void 0:A[0])&&(null==(R=e.pixelRatio)?void 0:R[1])===(null==(b=t.pixelRatio)?void 0:b[1])||this.resetInitSegment()}else d=this.generateIS(t,e,i,n);const s=this.isVideoContiguous;let r,a=-1;if(S&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!s&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,a>0){v.warn(`[mp4-remuxer]: Dropped ${a} out of ${E} 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,r=m}else-1===a&&(v.warn(`[mp4-remuxer]: No keyframe found out of ${E} video samples`),f=!1);if(this.ISGenerated){if(T&&S){const s=this.getVideoStartPts(e.samples),r=(Rr(t.samples[0].pts,s)-s)/e.inputTimeScale;g+=Math.max(0,r),m+=Math.max(0,-r)}if(T){if(t.samplerate||(v.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,i,n)),h=this.remuxAudio(t,g,this.isAudioContiguous,n,y||S||o===ce?m:void 0),S){const r=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(v.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,i,n)),l=this.remuxVideo(e,m,s,r)}}else S&&(l=this.remuxVideo(e,m,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=br(s,i,this._initPTS,this._initDTS)),r.samples.length&&(c=kr(r,i,this._initPTS))),{audio:h,video:l,initSegment:d,independent:f,text:c,id3:u}}generateIS(t,e,s,r){const i=t.samples,n=e.samples,a=this.typeSupported,o={},l=this._initPTS;let h,d,c,u=!l||r,f="audio/mp4";if(u&&(h=d=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):MP4.initSegment([t]),metadata:{channelCount:t.channelCount}},u&&(c=t.inputTimeScale,l&&c===l.timescale?u=!1:h=d=i[0].pts-Math.round(c*s))}if(e.sps&&e.pps&&n.length){if(e.timescale=e.inputTimeScale,o.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:MP4.initSegment([e]),metadata:{width:e.width,height:e.height}},u)if(c=e.inputTimeScale,l&&c===l.timescale)u=!1;else{const t=this.getVideoStartPts(n),e=Math.round(c*s);d=Math.min(d,Rr(n[0].dts,t)-e),h=Math.min(h,t-e)}this.videoTrackConfig={width:e.width,height:e.height,pixelRatio:e.pixelRatio}}if(Object.keys(o).length)return this.ISGenerated=!0,u?(this._initPTS={baseTime:h,timescale:c},this._initDTS={baseTime:d,timescale:c}):h=c=void 0,{tracks:o,initPTS:h,timescale:c}}remuxVideo(t,e,s,r){const i=t.inputTimeScale,n=t.samples,a=[],l=n.length,h=this._initPTS;let d,g,m=this.nextAvcDts,p=8,y=this.videoSampleDuration,E=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,S=!1;if(!s||null===m){const t=e*i,r=n[0].pts-Rr(n[0].dts,n[0].pts);Lr&&null!==m&&Math.abs(t-r-m)<15e3?s=!0:m=t-r}const L=h.baseTime*i/h.timescale;for(let t=0;t<l;t++){const e=n[t];e.pts=Rr(e.pts-L,m),e.dts=Rr(e.dts-L,m),e.dts<n[t>0?t-1:t].dts&&(S=!0)}S&&n.sort(function(t,e){const s=t.dts-e.dts,r=t.pts-e.pts;return s||r}),d=n[0].dts,g=n[n.length-1].dts;const A=g-d,R=A?Math.round(A/(l-1)):y||t.inputTimeScale/30;if(s){const t=d-m,s=t>R,r=t<-1;if((s||r)&&(s?v.warn(`AVC: ${Tr(t,!0)} ms (${t}dts) hole between fragments detected at ${e.toFixed(3)}`):v.warn(`AVC: ${Tr(-t,!0)} ms (${t}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||m>=n[0].pts||Lr)){d=m;const e=n[0].pts-t;if(s)n[0].dts=d,n[0].pts=e;else for(let s=0;s<n.length&&!(n[s].dts>e);s++)n[s].dts-=t,n[s].pts-=t;v.log(`Video: Initial PTS/DTS adjusted: ${Tr(e,!0)}/${Tr(d,!0)}, delta: ${Tr(t,!0)} ms`)}}d=Math.max(0,d);let b=0,k=0,D=d;for(let t=0;t<l;t++){const e=n[t],s=e.units,r=s.length;let i=0;for(let t=0;t<r;t++)i+=s[t].data.length;k+=i,b+=r,e.length=i,e.dts<D?(e.dts=D,D+=R/4|0||1):D=e.dts,E=Math.min(e.pts,E),T=Math.max(e.pts,T)}g=n[l-1].dts;const C=k+4*b+8;let P;try{P=new Uint8Array(C)}catch(t){return void this.observer.emit(c.ERROR,c.ERROR,{type:u.MUX_ERROR,details:f.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:C,reason:`fail allocating video mdat ${C}`})}const w=new DataView(P.buffer);w.setUint32(0,C),P.set(MP4.types.mdat,4);let I=!1,_=Number.POSITIVE_INFINITY,M=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,F=Number.NEGATIVE_INFINITY;for(let t=0;t<l;t++){const e=n[t],s=e.units;let o,h=0;for(let t=0,e=s.length;t<e;t++){const e=s[t],r=e.data,i=e.data.byteLength;w.setUint32(p,i),p+=4,P.set(r,p),p+=i,h+=4+i}if(t<l-1)y=n[t+1].dts-e.dts,o=n[t+1].pts-e.pts;else{const s=this.config,a=t>0?e.dts-n[t-1].dts:R;if(o=t>0?e.pts-n[t-1].pts:R,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(s.maxBufferHole*i),n=(r?E+r*i:this.nextAudioPts)-e.pts;n>t?(y=n-a,y<0?y=a:I=!0,v.log(`[mp4-remuxer]: It is approximately ${n/90} ms to the next segment; using duration ${y/90} ms for the last video frame.`)):y=a}else y=a}const d=Math.round(e.pts-e.dts);_=Math.min(_,y),x=Math.max(x,y),M=Math.min(M,o),F=Math.max(F,o),a.push(new Mp4Sample(e.key,y,h,d))}if(a.length)if(Lr){if(Lr<70){const t=a[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(Ar&&F-M<x-_&&R/x<.025&&0===a[0].cts){v.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=d;for(let e=0,s=a.length;e<s;e++){const r=t+a[e].duration,i=t+a[e].cts;if(e<s-1){const t=r+a[e+1].cts;a[e].duration=t-i}else a[e].duration=e?a[e-1].duration:R;a[e].cts=0,t=r}}y=I||!y?R:y,this.nextAvcDts=m=g+y,this.videoSampleDuration=y,this.isVideoContiguous=!0;const O={data1:MP4.moof(t.sequenceNumber++,d,o({},t,{samples:a})),data2:P,startPTS:E/i,endPTS:(T+y)/i,startDTS:d/i,endDTS:m/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,s,r,i){const n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),l=this.getSamplesPerFrame(t),h=l*a,d=this._initPTS,g="mp3"===t.segmentCodec&&this.typeSupported.mpeg,m=[],p=void 0!==i;let y=t.samples,E=g?0:8,T=this.nextAudioPts||-1;const S=e*n,L=d.baseTime*n/d.timescale;if(this.isAudioContiguous=s=s||y.length&&T>0&&(r&&Math.abs(S-T)<9e3||Math.abs(Rr(y[0].pts-L,S)-T)<20*h),y.forEach(function(t){t.pts=Rr(t.pts-L,S)}),!s||T<0){if(y=y.filter(t=>t.pts>=0),!y.length)return;T=0===i?0:r&&!p?Math.max(0,S):y[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,r=T;s<y.length;s++){const i=y[s],a=i.pts,o=a-r,l=Math.abs(1e3*o/n);if(o<=-e*h&&p)0===s&&(v.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*o/n)} ms.`),this.nextAudioPts=T=r=a);else if(o>=e*h&&l<1e4&&p){let e=Math.round(o/h);r=a-e*h,r<0&&(e--,r+=h),0===s&&(this.nextAudioPts=T=r),v.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(r/n).toFixed(3)}s due to ${Math.round(1e3*o/n)} ms gap.`);for(let n=0;n<e;n++){const e=Math.max(r,0);let n=AAC.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);n||(v.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=i.unit.subarray()),y.splice(s,0,{unit:n,pts:e}),r+=h,s++}}i.pts=r,r+=h}}let A,R=null,b=null,k=0,D=y.length;for(;D--;)k+=y[D].unit.byteLength;for(let e=0,r=y.length;e<r;e++){const r=y[e],i=r.unit;let n=r.pts;if(null!==b){m[e-1].duration=Math.round((n-b)/a)}else{if(s&&"aac"===t.segmentCodec&&(n=T),R=n,!(k>0))return;k+=E;try{A=new Uint8Array(k)}catch(t){return void this.observer.emit(c.ERROR,c.ERROR,{type:u.MUX_ERROR,details:f.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:k,reason:`fail allocating audio mdat ${k}`})}if(!g){new DataView(A.buffer).setUint32(0,k),A.set(MP4.types.mdat,4)}}A.set(i,E);const o=i.byteLength;E+=o,m.push(new Mp4Sample(!0,l,o,0)),b=n}const C=m.length;if(!C)return;const P=m[m.length-1];this.nextAudioPts=T=b+a*P.duration;const w=g?new Uint8Array(0):MP4.moof(t.sequenceNumber++,R/a,o({},t,{samples:m}));t.samples=[];const I=R/n,_=T/n,M={data1:w,data2:A,startPTS:I,endPTS:_,startDTS:I,endDTS:_,type:"audio",hasAudio:!0,hasVideo:!1,nb:C};return this.isAudioContiguous=!0,M}remuxEmptyAudio(t,e,s,r){const i=t.inputTimeScale,n=i/(t.samplerate?t.samplerate:i),a=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,h=(null!==a?a:r.startDTS*i)+l,d=r.endDTS*i+l,c=1024*n,u=Math.ceil((d-h)/c),f=AAC.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(v.warn("[mp4-remuxer]: remux empty Audio"),!f)return void v.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<u;t++){const e=h+t*c;g.push({unit:f,pts:e,dts:e})}return t.samples=g,this.remuxAudio(t,e,s,!1)}}function Rr(t,e){let s;if(null===e)return t;for(s=e<t?-8589934592:8589934592;Math.abs(t-e)>4294967296;)t+=s;return t}function br(t,e,s,r){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=Rr(i.pts-s.baseTime*n/s.timescale,e*n)/n,i.dts=Rr(i.dts-r.baseTime*n/r.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function kr(t,e,s){const r=t.samples.length;if(!r)return;const i=t.inputTimeScale;for(let n=0;n<r;n++){const r=t.samples[n];r.pts=Rr(r.pts-s.baseTime*i/s.timescale,e*i)/i}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}class Mp4Sample{constructor(t,e,s,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=s,this.cts=r,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1}}}function Dr(t,e){const s=null==t?void 0:t.codec;if(s&&s.length>4)return s;if(e===A){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return Wt(s,!1)}const t="mp4a.40.5";return v.info(`Parsed audio codec "${s}" or audio object type not handled. Using "${t}"`),t}return v.warn(`Unhandled video codec "${s}"`),"hvc1"===s||"hev1"===s?"hvc1.1.6.L120.90":"av01"===s?"av01.0.04M.08":"avc1.42e01e"}try{Sr=self.performance.now.bind(self.performance)}catch(t){v.debug("Unable to use Performance API on this environment"),Sr=null==P?void 0:P.Date.now}const Cr=[{demux:class MP4Demuxer{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,s,r){const i=this.videoTrack=Hs("video",1),n=this.audioTrack=Hs("audio",1),a=this.txtTrack=Hs("text",1);if(this.id3Track=Hs("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=yt(t);if(o.video){const{id:t,timescale:e,codec:s}=o.video;i.id=t,i.timescale=a.timescale=e,i.codec=s}if(o.audio){const{id:t,timescale:e,codec:s}=o.audio;n.id=t,n.timescale=e,n.codec=s}a.id=lt.text,i.sampleDuration=0,i.duration=n.duration=r}resetContiguity(){this.remainderData=null}static probe(t){return function(t){const e=t.byteLength;for(let s=0;s<e;){const r=ct(t,s);if(r>8&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7])return!0;s=r>1?s+r:e}return!1}(t)}demux(t,e){this.timeOffset=e;let s=t;const r=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Rt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=mt(t,["moof"]);if(s.length<2)return e.remainder=t,e;const r=s[s.length-1];return e.valid=G(t,0,r.byteOffset-8),e.remainder=G(t,r.byteOffset-8),e}(s);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=s;const n=this.extractID3Track(r,e);return i.samples=bt(e,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const t=this.timeOffset,e=this.videoTrack,s=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(e,this.timeOffset);return s.samples=bt(t,e),{videoTrack:e,audioTrack:Hs(),id3Track:r,textTrack:Hs()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const r=mt(t.samples,["emsg"]);r&&r.forEach(t=>{const r=function(t){const e=t[0];let s="",r="",i=0,n=0,a=0,o=0,l=0,d=0;if(0===e){for(;"\0"!==ht(t.subarray(d,d+1));)s+=ht(t.subarray(d,d+1)),d+=1;for(s+=ht(t.subarray(d,d+1)),d+=1;"\0"!==ht(t.subarray(d,d+1));)r+=ht(t.subarray(d,d+1)),d+=1;r+=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,h(a)||(a=Number.MAX_SAFE_INTEGER,v.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));)s+=ht(t.subarray(d,d+1)),d+=1;for(s+=ht(t.subarray(d,d+1)),d+=1;"\0"!==ht(t.subarray(d,d+1));)r+=ht(t.subarray(d,d+1)),d+=1;r+=ht(t.subarray(d,d+1)),d+=1}return{schemeIdUri:s,value:r,timeScale:i,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(d,t.byteLength)}}(t);if(hr.test(r.schemeIdUri)){const t=l(r.presentationTime)?r.presentationTime/r.timeScale:e+r.presentationTimeDelta/r.timeScale;let i=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const n=r.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:Le,duration:i})}})}return s}demuxSampleAes(t,e,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class PassThroughRemuxer{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,s,r){this.audioCodec=e,this.videoCodec=s,this.generateInitSegment(function(t,e){if(!t||!e)return t;const s=e.keyId;s&&e.isCommonEncryption&&mt(t,["moov","trak"]).forEach(t=>{const e=mt(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=mt(e,["enca"]);const i=r.length>0;i||(r=mt(e,["encv"])),r.forEach(t=>{mt(i?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const e=Lt(t);if(e){const t=e.subarray(8,24);t.some(t=>0!==t)||(v.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${nt(t)} -> ${nt(s)}`),e.set(s,8))}})})});return t}(t,r)),this.emitInitSegment=!0}generateInitSegment(t){let{audioCodec:e,videoCodec:s}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const r=this.initData=yt(t);r.audio&&(e=Dr(r.audio,A)),r.video&&(s=Dr(r.video,R));const i={};r.audio&&r.video?i.audiovideo={container:"video/mp4",codec:e+","+s,initSegment:t,id:"main"}:r.audio?i.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:r.video?i.video={container:"video/mp4",codec:s,initSegment:t,id:"main"}:v.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=i}remux(t,e,s,r,i,n){var a,o;let{initPTS:h,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};l(d)||(d=this.lastEndTime=i||0);const u=e.samples;if(null==u||!u.length)return c;const f={initPTS:void 0,timescale:1};let g=this.initData;if(null!=(a=g)&&a.length||(this.generateInitSegment(u),g=this.initData),null==(o=g)||!o.length)return v.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const m=function(t,e){let s=0,r=0,i=0;const n=mt(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=mt(a,["tfhd"])[0],l=e[ct(o,4)];if(!l)continue;const h=l.default,d=ct(o,0)|(null==h?void 0:h.flags);let c=null==h?void 0:h.duration;8&d&&(c=ct(o,2&d?12:8));const u=l.timescale||9e4,f=mt(a,["trun"]);for(let t=0;t<f.length;t++)s=At(f[t]),!s&&c&&(s=c*ct(f[t],4)),l.type===R?r+=s/u:l.type===A&&(i+=s/u)}if(0===r&&0===i){let e=1/0,s=0,r=0;const i=mt(t,["sidx"]);for(let t=0;t<i.length;t++){const n=pt(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);s=Math.max(s,t+n.earliestPresentationTime/n.timescale),r=s-e}}if(r&&l(r))return r}return r||i}(u,g),p=function(t,e){return mt(e,["moof","traf"]).reduce((e,s)=>{const r=mt(s,["tfdt"])[0],i=r[0],n=mt(s,["tfhd"]).reduce((e,s)=>{const n=ct(s,4),a=t[n];if(a){let t=ct(r,4);if(1===i){if(t===at)return v.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=at+1,t+=ct(r,8)}const s=t/(a.timescale||9e4);if(l(s)&&(null===e||s<e))return s}return e},null);return null!==n&&l(n)&&(null===e||n<e)?n:e},null)}(g,u),y=null===p?i:p;(function(t,e,s,r){if(null===t)return!0;const i=Math.max(r,1),n=e-t.baseTime/t.timescale;return Math.abs(n-s)>i}(h,y,i,m)||f.timescale!==h.timescale&&n)&&(f.initPTS=y-i,h&&1===h.timescale&&v.warn("Adjusting initPTS by "+(f.initPTS-h.baseTime)),this.initPTS=h={baseTime:f.initPTS,timescale:1});const E=t?y-h.baseTime/h.timescale:d,T=E+m;!function(t,e,s){mt(e,["moof","traf"]).forEach(e=>{mt(e,["tfhd"]).forEach(r=>{const i=ct(r,4),n=t[i];if(!n)return;const a=n.timescale||9e4;mt(e,["tfdt"]).forEach(t=>{const e=t[0],r=s*a;if(r){let s=ct(t,4);if(0===e)s-=r,s=Math.max(s,0),gt(t,4,s);else{s*=Math.pow(2,32),s+=ct(t,8),s-=r,s=Math.max(s,0);const e=Math.floor(s/(at+1)),i=Math.floor(s%(at+1));gt(t,4,e),gt(t,8,i)}}})})})}(g,u,h.baseTime/h.timescale),m>0?this.lastEndTime=T:(v.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const S=!!g.audio,L=!!g.video;let b="";S&&(b+="audio"),L&&(b+="video");const k={data1:u,startPTS:E,startDTS:E,endPTS:T,endDTS:T,type:b,hasAudio:S,hasVideo:L,nb:1,dropped:0};return c.audio="audio"===k.type?k:void 0,c.video="audio"!==k.type?k:void 0,c.initSegment=f,c.id3=br(s,i,h,h),r.samples.length&&(c.text=kr(r,i,h)),c}}},{demux:TSDemuxer,remux:MP4Remuxer},{demux:class AACDemuxer extends BaseAudioDemuxer{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.observer=t,this.config=e}resetInitSegment(t,e,s,r){super.resetInitSegment(t,e,s,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=V(t,0);let s=(null==e?void 0:e.length)||0;if(lr(t,s))return!1;for(let e=t.length;s<e;s++)if(Xs(t,s))return v.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)&&Ys(t,e)&&js(t,e)<=t.length-e}(t,e)}appendFrame(t,e,s){zs(t,this.observer,e,s,t.manifestCodec);const r=Js(t,e,s,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:MP4Remuxer},{demux:class MP3Demuxer extends BaseAudioDemuxer{resetInitSegment(t,e,s,r){super.resetInitSegment(t,e,s,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:r,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=V(t,0);let s=(null==e?void 0:e.length)||0;if(e&&11===t[s]&&119===t[s+1]&&void 0!==j(e)&&dr(t,s)<=16)return!1;for(let e=t.length;s<e;s++)if(lr(t,s))return v.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return ar(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,s){if(null!==this.basePTS)return ir(t,e,s,this.basePTS,this.frameIndex)}},remux:MP4Remuxer}];Cr.splice(2,0,{demux:AC3Demuxer,remux:MP4Remuxer});class Transmuxer{constructor(t,e,s,r,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=s,this.vendor=r,this.id=i}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,s,r){const i=s.transmuxing;i.executeStart=Sr();let n=new Uint8Array(t);const{currentTransmuxState:a,transmuxConfig:o}=this;r&&(this.currentTransmuxState=r);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:g,timeOffset:m,initSegmentChange:p}=r||a,{audioCodec:y,videoCodec:E,defaultInitPts:T,duration:S,initSegmentData:L}=o,A=function(t,e){let s=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(s=e);return s}(n,e);if(A&&"AES-128"===A.method){const t=this.getDecrypter();if(!t.isSync())return this.decryptionPromise=t.webCryptoDecrypt(n,A.key.buffer,A.iv.buffer).then(t=>{const e=this.push(t,null,s);return this.decryptionPromise=null,e}),this.decryptionPromise;{let e=t.softwareDecrypt(n,A.key.buffer,A.iv.buffer);if(s.part>-1&&(e=t.flush()),!e)return i.executeEnd=Sr(),Pr(s);n=new Uint8Array(e)}}const R=this.needsProbing(h,d);if(R){const t=this.configureTransmuxer(n);if(t)return v.warn(`[transmuxer] ${t.message}`),this.observer.emit(c.ERROR,c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),i.executeEnd=Sr(),Pr(s)}(h||d||p||R)&&this.resetInitSegment(L,y,E,S,e),(h||p||R)&&this.resetInitialTimestamp(T),l||this.resetContiguity();const b=this.transmux(n,A,m,g,s),k=this.currentTransmuxState;return k.contiguous=!0,k.discontinuity=!1,k.trackSwitch=!1,i.executeEnd=Sr(),b}flush(t){const e=t.transmuxing;e.executeStart=Sr();const{decrypter:s,currentTransmuxState:r,decryptionPromise:i}=this;if(i)return i.then(()=>this.flush(t));const n=[],{timeOffset:a}=r;if(s){const e=s.flush();e&&n.push(this.push(e,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l)return e.executeEnd=Sr(),[Pr(t)];const h=o.flush(a);return wr(h)?h.then(e=>(this.flushRemux(n,e,t),n)):(this.flushRemux(n,h,t),n)}flushRemux(t,e,s){const{audioTrack:r,videoTrack:i,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;v.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const h=this.remuxer.remux(r,i,n,a,l,o,!0,this.id);t.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=Sr()}resetInitialTimestamp(t){const{demuxer:e,remuxer:s}=this;e&&s&&(e.resetTimeStamp(t),s.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,s,r,i){const{demuxer:n,remuxer:a}=this;n&&a&&(n.resetInitSegment(t,e,s,r),a.resetInitSegment(t,e,s,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,e,s,r,i){let n;return n=e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,s,r,i):this.transmuxUnencrypted(t,s,r,i),n}transmuxUnencrypted(t,e,s,r){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,s,!1,this.id),chunkMeta:r}}transmuxSampleAes(t,e,s,r,i){return this.demuxer.demuxSampleAes(t,e,s).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,s,r,!1,this.id),chunkMeta:i}))}configureTransmuxer(t){const{config:e,observer:s,typeSupported:r,vendor:i}=this;let n;for(let e=0,s=Cr.length;e<s;e++){var a;if(null!=(a=Cr[e].demux)&&a.probe(t)){n=Cr[e];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,l=this.remuxer,h=n.remux,d=n.demux;l&&l instanceof h||(this.remuxer=new h(s,e,r,i)),o&&o instanceof d||(this.demuxer=new d(s,e,r),this.probe=d.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Decrypter(this.config)),t}}const Pr=t=>({remuxResult:{},chunkMeta:t});function wr(t){return"then"in t&&t.then instanceof Function}class TransmuxConfig{constructor(t,e,s,r,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=s,this.duration=r,this.defaultInitPts=i||null}}class TransmuxState{constructor(t,e,s,r,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=s,this.trackSwitch=r,this.timeOffset=i,this.initSegmentChange=n}}var Ir={exports:{}};!function(t){var e=Object.prototype.hasOwnProperty,s="~";function r(){}function i(t,e,s){this.fn=t,this.context=e,this.once=s||!1}function n(t,e,r,n,a){if("function"!=typeof r)throw new TypeError("The listener must be a function");var o=new i(r,n||t,a),l=s?s+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 r:delete t._events[e]}function o(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),(new r).__proto__||(s=!1)),o.prototype.eventNames=function(){var t,r,i=[];if(0===this._eventsCount)return i;for(r in t=this._events)e.call(t,r)&&i.push(s?r.slice(1):r);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(t)):i},o.prototype.listeners=function(t){var e=s?s+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,n=r.length,a=new Array(n);i<n;i++)a[i]=r[i].fn;return a},o.prototype.listenerCount=function(t){var e=s?s+t:t,r=this._events[e];return r?r.fn?1:r.length:0},o.prototype.emit=function(t,e,r,i,n,a){var o=s?s+t:t;if(!this._events[o])return!1;var l,h,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,r),!0;case 4:return d.fn.call(d.context,e,r,i),!0;case 5:return d.fn.call(d.context,e,r,i,n),!0;case 6:return d.fn.call(d.context,e,r,i,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(t,d[h].fn,void 0,!0),c){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,e);break;case 3:d[h].fn.call(d[h].context,e,r);break;case 4:d[h].fn.call(d[h].context,e,r,i);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(t,e,s){return n(this,t,e,s,!1)},o.prototype.once=function(t,e,s){return n(this,t,e,s,!0)},o.prototype.removeListener=function(t,e,r,i){var n=s?s+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||r&&o.context!==r||a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==e||i&&!o[l].once||r&&o[l].context!==r)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=s?s+t:t,this._events[e]&&a(this,e)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=s,o.EventEmitter=o,t.exports=o}(Ir);var _r=t(Ir.exports);class TransmuxerInterface{constructor(t,e,s,r){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=s,this.onFlush=r;const n=(t,e)=>{(e=e||{}).frag=this.frag,e.id=this.id,t===c.ERROR&&(this.error=e.error),this.hls.trigger(t,e)};this.observer=new _r,this.observer.on(c.FRAG_DECRYPTED,n),this.observer.on(c.ERROR,n);const a=Nt(i.preferManagedMediaSource)||{isTypeSupported:()=>!1},o={mpeg:a.isTypeSupported("audio/mpeg"),mp3:a.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:a.isTypeSupported('audio/mp4; codecs="ac-3"')},l=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(i.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{i.workerPath?(v.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)):(v.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 s=new Error(`${t.message} (${t.filename}:${t.lineno})`);i.enableWorker=!1,v.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(c.ERROR,{type:u.OTHER_ERROR,details:f.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:s})},t.postMessage({cmd:"init",typeSupported:o,vendor:l,id:e,config:JSON.stringify(i)})}catch(t){v.warn(`Error setting up "${e}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,o,i,l,e)}return}}this.transmuxer=new Transmuxer(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,s,r,i,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{transmuxer:u}=this,f=n?n.start:i.start,g=i.decryptdata,m=this.frag,p=!(m&&i.cc===m.cc),y=!(m&&l.level===m.level),E=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),L=!y&&(1===E||0===E&&(1===T||S&&T<=0)),A=self.performance.now();(y||E||0===i.stats.parsing.start)&&(i.stats.parsing.start=A),!n||!T&&L||(n.stats.parsing.start=A);const R=!(m&&(null==(d=i.initSegment)?void 0:d.url)===(null==(c=m.initSegment)?void 0:c.url)),b=new TransmuxState(p,L,o,y,f,R);if(!L||p||R){v.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: ${y}\n contiguous: ${L}\n accurateTimeOffset: ${o}\n timeOffset: ${f}\n initSegmentChange: ${R}`);const t=new TransmuxConfig(s,r,e,a,h);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:b},t instanceof ArrayBuffer?[t]:[]);else if(u){const e=u.push(t,g,l,b);wr(e)?(u.async=!0,e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")})):(u.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 s=e.flush(t);wr(s)||e.async?(wr(s)||(s=Promise.resolve(s)),s.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")})):this.handleFlushResult(s,t)}}transmuxerError(t,e,s){this.hls&&(this.error=t,this.hls.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,chunkMeta:e,fatal:!1,error:t,err:t,reason:s}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}onWorkerMessage(t){const e=t.data,s=this.hls;switch(e.event){case"init":{var r;const t=null==(r=this.workerContext)?void 0:r.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":v[e.data.logType]&&v[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,s.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)}}function Mr(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!xr(t[s].attrs,e[s].attrs))return!1;return!0}function xr(t,e,s){const r=t["STABLE-RENDITION-ID"];return r&&!s?r===e["STABLE-RENDITION-ID"]:!(s||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>t[s]!==e[s])}function Fr(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}class BufferableInstance{constructor(t){this.buffered=void 0;const e=(e,s,r)=>{if((s>>>=0)>r-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${s}) is greater than the maximum bound (${r})`);return t[s][e]};this.buffered={get length(){return t.length},end:s=>e("end",s,t.length),start:s=>e("start",s,t.length)}}}class BufferOperationQueue{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e,s){const r=this.queues[e];r.push(t),1!==r.length||s||this.executeNext(e)}insertAbort(t,e){this.queues[e].unshift(t),this.executeNext(e)}appendBlocker(t){let e;const s=new Promise(t=>{e=t}),r={execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,t),s}executeNext(t){const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(e){v.warn(`[buffer-operation-queue]: Exception executing "${t}" SourceBuffer operation: ${e}`),s.onError(e);const r=this.buffers[t];null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Or=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function Nr(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}const Ur={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Br=function(t){let e=t;return Ur.hasOwnProperty(t)&&(e=Ur[t]),String.fromCharCode(e)},$r=15,Gr=100,Kr={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Hr={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Vr={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Yr={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Wr=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class CaptionsLogger{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const s="function"==typeof e?e():e;v.log(`${this.time} [${t}] ${s}`)}}}const jr=function(t){const e=[];for(let s=0;s<t.length;s++)e.push(t[s].toString(16));return e};class PenState{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(t){const e=["foreground","underline","italics","background","flash"];for(let s=0;s<e.length;s++){const r=e[s];t.hasOwnProperty(r)&&(this[r]=t[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(t){return this.foreground===t.foreground&&this.underline===t.underline&&this.italics===t.italics&&this.background===t.background&&this.flash===t.flash}copy(t){this.foreground=t.foreground,this.underline=t.underline,this.italics=t.italics,this.background=t.background,this.flash=t.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class StyledUnicodeChar{constructor(){this.uchar=" ",this.penState=new PenState}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.copy(e)}setPenState(t){this.penState.copy(t)}equals(t){return this.uchar===t.uchar&&this.penState.equals(t.penState)}copy(t){this.uchar=t.uchar,this.penState.copy(t.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class Row{constructor(t){this.chars=[],this.pos=0,this.currPenState=new PenState,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Gr;t++)this.chars.push(new StyledUnicodeChar);this.logger=t}equals(t){for(let e=0;e<Gr;e++)if(!this.chars[e].equals(t.chars[e]))return!1;return!0}copy(t){for(let e=0;e<Gr;e++)this.chars[e].copy(t.chars[e])}isEmpty(){let t=!0;for(let e=0;e<Gr;e++)if(!this.chars[e].isEmpty()){t=!1;break}return t}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Gr&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Gr)}moveCursor(t){const e=this.pos+t;if(t>1)for(let t=this.pos+1;t<e+1;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=Br(t);this.pos>=Gr?this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<Gr;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let s=0;s<Gr;s++){const r=this.chars[s].uchar;" "!==r&&(e=!1),t.push(r)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class CaptionScreen{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<$r;e++)this.rows.push(new Row(t));this.logger=t}reset(){for(let t=0;t<$r;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let s=0;s<$r;s++)if(!this.rows[s].equals(t.rows[s])){e=!1;break}return e}copy(t){for(let e=0;e<$r;e++)this.rows[e].copy(t.rows[e])}isEmpty(){let t=!0;for(let e=0;e<$r;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+JSON.stringify(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<$r;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,s=this.lastOutputScreen;if(s){const r=s.rows[t].cueStartTime,i=this.logger.time;if(null!==r&&null!==i&&r<i)for(let r=0;r<this.nrRollUpRows;r++)this.rows[e-this.nrRollUpRows+r+1].copy(s.rows[t+r])}}this.currRow=e;const s=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,r=Math.max(e-1,0);s.setCursor(t.indent),t.color=s.chars[r].penState.foreground}const r={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+JSON.stringify(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let s="",r=-1;for(let s=0;s<$r;s++){const i=this.rows[s].getTextString();i&&(r=s+1,t?e.push("Row "+r+": '"+i+"'"):e.push(i.trim()))}return e.length>0&&(s=t?"["+e.join(" | ")+"]":e.join("\n")),s}getTextAndFormat(){return this.rows}}class Cea608Channel{constructor(t,e,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new CaptionScreen(s),this.nonDisplayedMemory=new CaptionScreen(s),this.lastOutputScreen=new CaptionScreen(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const s=Math.floor(t/2)-16,r=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=r[s]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class Cea608Parser{constructor(t,e,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const r=this.logger=new CaptionsLogger;this.channels=[null,new Cea608Channel(t,e,r),new Cea608Channel(t+1,s,r)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,e){this.channels[t].setHandler(e)}addData(t,e){let s,r,i,n=!1;this.logger.time=t;for(let t=0;t<e.length;t+=2)if(r=127&e[t],i=127&e[t+1],0!==r||0!==i){if(this.logger.log(3,"["+jr([e[t],e[t+1]])+"] -> ("+jr([r,i])+")"),s=this.parseCmd(r,i),s||(s=this.parseMidrow(r,i)),s||(s=this.parsePAC(r,i)),s||(s=this.parseBackgroundAttributes(r,i)),!s&&(n=this.parseChars(r,i),n)){const t=this.currentChannel;if(t&&t>0){this.channels[t].insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}s||n||this.logger.log(2,"Couldn't parse cleaned data "+jr([r,i])+" orig: "+jr([e[t],e[t+1]]))}}parseCmd(t,e){const{cmdHistory:s}=this;if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;if(Xr(t,e,s))return qr(null,null,s),this.logger.log(3,"Repeated command ("+jr([t,e])+") is dropped"),!0;const r=20===t||21===t||23===t?1:2,i=this.channels[r];return 20===t||21===t||28===t||29===t?32===e?i.ccRCL():33===e?i.ccBS():34===e?i.ccAOF():35===e?i.ccAON():36===e?i.ccDER():37===e?i.ccRU(2):38===e?i.ccRU(3):39===e?i.ccRU(4):40===e?i.ccFON():41===e?i.ccRDC():42===e?i.ccTR():43===e?i.ccRTD():44===e?i.ccEDM():45===e?i.ccCR():46===e?i.ccENM():47===e&&i.ccEOC():i.ccTO(e-32),qr(t,e,s),this.currentChannel=r,!0}parseMidrow(t,e){let s=0;if((17===t||25===t)&&e>=32&&e<=47){if(s=17===t?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const r=this.channels[s];return!!r&&(r.ccMIDROW(e),this.logger.log(3,"MIDROW ("+jr([t,e])+")"),!0)}return!1}parsePAC(t,e){let s;const r=this.cmdHistory;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;if(Xr(t,e,r))return qr(null,null,r),!0;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?Kr[t]:Vr[t]:1===i?Hr[t]:Yr[t];const n=this.channels[i];return!!n&&(n.setPAC(this.interpretPAC(s,e)),qr(t,e,r),this.currentChannel=i,!0)}interpretPAC(t,e){let s;const r={color:null,italics:!1,indent:null,underline:!1,row:t};return s=e>95?e-96:e-64,r.underline=!(1&~s),s<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((s-16)/2),r}parseChars(t,e){let s,r=null,i=null;if(t>=25?(s=2,i=t-8):(s=1,i=t),i>=17&&i<=19){let t;t=17===i?e+80:18===i?e+112:e+144,this.logger.log(2,"Special char '"+Br(t)+"' in channel "+s),r=[t]}else t>=32&&t<=127&&(r=0===e?[t]:[t,e]);if(r){const s=jr(r);this.logger.log(3,"Char codes = "+s.join(",")),qr(t,e,this.cmdHistory)}return r}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let s;const r={};16===t||24===t?(s=Math.floor((e-32)/2),r.background=Wr[s],e%2==1&&(r.background=r.background+"_semi")):45===e?r.background="transparent":(r.foreground="black",47===e&&(r.underline=!0));const i=t<=23?1:2;return this.channels[i].setBkgData(r),qr(t,e,this.cmdHistory),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}this.cmdHistory={a:null,b:null}}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const s=this.channels[e];s&&s.cueSplitAtTime(t)}}}function qr(t,e,s){s.a=t,s.b=e}function Xr(t,e,s){return s.a===t&&s.b===e}class OutputFilter{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,s){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var zr=function(){if(null!=P&&P.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function s(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const s=e.toLowerCase();return!!~t.indexOf(s)&&s}function r(t){return s(e,t)}function i(t,...e){let s=1;for(;s<arguments.length;s++){const e=arguments[s];for(const s in e)t[s]=e[s]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,c=e,u=n,f=a,g=null,m="",p=!0,y="auto",v="start",E=50,T="middle",S=50,L="middle";Object.defineProperty(o,"id",i({},l,{get:function(){return h},set:function(t){h=""+t}})),Object.defineProperty(o,"pauseOnExit",i({},l,{get:function(){return d},set:function(t){d=!!t}})),Object.defineProperty(o,"startTime",i({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",i({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",i({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",i({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",i({},l,{get:function(){return m},set:function(e){const r=function(e){return s(t,e)}(e);if(!1===r)throw new SyntaxError("An invalid or illegal string was specified.");m=r,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",i({},l,{get:function(){return p},set:function(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",i({},l,{get:function(){return y},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",i({},l,{get:function(){return v},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",i({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",i({},l,{get:function(){return T},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",i({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",i({},l,{get:function(){return L},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");L=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class StringDecoder{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Qr(t){function e(t,e,s,r){return 3600*(0|t)+60*(0|e)+(0|s)+parseFloat(r||0)}const s=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return s?parseFloat(s[2])>59?e(s[2],s[3],0,s[4]):e(s[1],s[2],s[3],s[4]):null}class Settings{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,s){return s?this.has(t)?this.values[t]:e[s]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,s){for(let r=0;r<s.length;++r)if(e===s[r]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const s=parseFloat(e);if(s>=0&&s<=100)return this.set(t,s),!0}return!1}}function Jr(t,e,s,r){const i=r?t.split(r):[t];for(const t in i){if("string"!=typeof i[t])continue;const r=i[t].split(s);if(2!==r.length)continue;e(r[0],r[1])}}const Zr=new zr(0,0,""),ti="middle"===Zr.align?"middle":"center";function ei(t,e,s){const r=t;function i(){const e=Qr(t);if(null===e)throw new Error("Malformed timestamp: "+r);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=i(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+r);t=t.slice(3),n(),e.endTime=i(),n(),function(t,e){const r=new Settings;Jr(t,function(t,e){let i;switch(t){case"region":for(let i=s.length-1;i>=0;i--)if(s[i].id===e){r.set(t,s[i].region);break}break;case"vertical":r.alt(t,e,["rl","lr"]);break;case"line":i=e.split(","),r.integer(t,i[0]),r.percent(t,i[0])&&r.set("snapToLines",!1),r.alt(t,i[0],["auto"]),2===i.length&&r.alt("lineAlign",i[1],["start",ti,"end"]);break;case"position":i=e.split(","),r.percent(t,i[0]),2===i.length&&r.alt("positionAlign",i[1],["start",ti,"end","line-left","line-right","auto"]);break;case"size":r.percent(t,e);break;case"align":r.alt(t,e,["start",ti,"end","left","right"])}},/:/,/\s/),e.region=r.get("region",null),e.vertical=r.get("vertical","");let i=r.get("line","auto");"auto"===i&&-1===Zr.line&&(i=-1),e.line=i,e.lineAlign=r.get("lineAlign","start"),e.snapToLines=r.get("snapToLines",!0),e.size=r.get("size",100),e.align=r.get("align",ti);let n=r.get("position","auto");"auto"===n&&50===Zr.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function si(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class VTTParser{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new StringDecoder,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function s(){let t=e.buffer,s=0;for(t=si(t);s<t.length&&"\r"!==t[s]&&"\n"!==t[s];)++s;const r=t.slice(0,s);return"\r"===t[s]&&++s,"\n"===t[s]&&++s,e.buffer=t.slice(s),r}function r(t){Jr(t,function(t,e){},/:/)}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=s();const r=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==r||!r[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let i=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(i?i=!1:t=s(),e.state){case"HEADER":/:/.test(t)?r(t):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new zr(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{ei(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const s=-1!==t.indexOf("--\x3e");if(!t||s&&(i=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}const ri=/\r\n|\n\r|\n|\r/g,ii=function(t,e,s=0){return t.slice(s,s+e.length)===e},ni=function(t){let e=5381,s=t.length;for(;s;)e=33*e^t.charCodeAt(--s);return(e>>>0).toString()};function ai(t,e,s){return ni(t.toString())+ni(e.toString())+ni(s)}function oi(t,e,s,r,i,n,a){const o=new VTTParser,h=st(new Uint8Array(t)).trim().replace(ri,"\n").split("\n"),d=[],c=e?function(t,e=1){return Er(t,9e4,1/e)}(e.baseTime,e.timescale):0;let u,f="00:00.000",g=0,m=0,p=!0;o.oncue=function(t){const n=s[r];let a=s.ccOffset;const o=(g-c)/9e4;if(null!=n&&n.new&&(void 0!==m?a=s.ccOffset=n.start:function(t,e,s){let r=t[e],i=t[r.prevCC];if(!i||!i.new&&r.new)return t.ccOffset=t.presentationOffset=r.start,void(r.new=!1);for(;null!=(n=i)&&n.new;){var n;t.ccOffset+=r.start-i.start,r.new=!1,r=i,i=t[r.prevCC]}t.presentationOffset=s}(s,r,o)),o){if(!e)return void(u=new Error("Missing initPTS for VTT MPEGTS"));a=o-s.presentationOffset}const l=t.endTime-t.startTime,h=Rr(9e4*(t.startTime+a-m),9e4*i)/9e4;t.startTime=Math.max(h,0),t.endTime=Math.max(h+l,0);const f=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(f)),t.id||(t.id=ai(t.startTime,t.endTime,f)),t.endTime>0&&d.push(t)},o.onparsingerror=function(t){u=t},o.onflush=function(){u?a(u):n(d)},h.forEach(t=>{if(p){if(ii(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach(t=>{ii(t,"LOCAL:")?f=t.slice(6):ii(t,"MPEGTS:")&&(g=parseInt(t.slice(7)))});try{m=function(t){let e=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),i=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(l(e)&&l(s)&&l(r)&&l(i)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return e+=1e3*s,e+=6e4*r,e+=36e5*i,e}(f)/1e3}catch(t){u=t}return}""===t&&(p=!1)}o.parse(t+"\n")}),o.flush()}const li="stpp.ttml.im1t",hi=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,di=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ci={left:"start",center:"center",right:"end",start:"start",end:"end"};function ui(t,e,s,r){const i=mt(new Uint8Array(t),["mdat"]);if(0===i.length)return void r(new Error("Could not parse IMSC1 mdat"));const n=i.map(t=>st(t)),a=function(t,e,s=1,r=!1){return Er(t,e,1/s,r)}(e.baseTime,1,e.timescale);try{n.forEach(t=>s(function(t,e){const s=new DOMParser,r=s.parseFromString(t,"text/xml"),i=r.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((t,e)=>(t[e]=i.getAttribute(`ttp:${e}`)||n[e],t),{}),l="preserve"!==i.getAttribute("xml:space"),h=gi(fi(i,"styling","style")),d=gi(fi(i,"layout","region")),c=fi(i,"body","[begin]");return[].map.call(c,t=>{const s=mi(t,l);if(!s||!t.hasAttribute("begin"))return null;const r=vi(t.getAttribute("begin"),a),i=vi(t.getAttribute("dur"),a);let n=vi(t.getAttribute("end"),a);if(null===r)throw yi(t);if(null===n){if(null===i)throw yi(t);n=r+i}const c=new zr(r-e,n-e,s);c.id=ai(c.startTime,c.endTime,c.text);const u=function(t,e,s){const r="http://www.w3.org/ns/ttml#styling";let i=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&s.hasOwnProperty(a)&&(i=s[a]);return n.reduce((s,n)=>{const a=pi(e,r,n)||pi(t,r,n)||pi(i,r,n);return a&&(s[n]=a),s},{})}(d[t.getAttribute("region")],h[t.getAttribute("style")],h),{textAlign:f}=u;if(f){const t=ci[f];t&&(c.lineAlign=t),c.align=f}return o(c,u),c}).filter(t=>null!==t)}(t,a)))}catch(t){r(t)}}function fi(t,e,s){const r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(s)):[]}function gi(t){return t.reduce((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t},{})}function mi(t,e){return[].slice.call(t.childNodes).reduce((t,s,r)=>{var i;return"br"===s.nodeName&&r?t+"\n":null!=(i=s.childNodes)&&i.length?mi(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function pi(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function yi(t){return new Error(`Could not parse ttml timestamp ${t}`)}function vi(t,e){if(!t)return null;let s=Qr(t);return null===s&&(hi.test(t)?s=function(t,e){const s=hi.exec(t),r=(0|s[4])+(0|s[5])/e.subFrameRate;return 3600*(0|s[1])+60*(0|s[2])+(0|s[3])+r/e.frameRate}(t,e):di.test(t)&&(s=function(t,e){const s=di.exec(t),r=Number(s[1]);switch(s[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/e.frameRate;case"t":return r/e.tickRate}return r}(t,e))),s}function Ei(t){return t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Ti(t,e){return!!t&&t.kind===Ei(e)&&Fr(e,t)}function Si(t,e,s,r){return Math.min(e,r)-Math.max(t,s)}class CapLevelController{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(c.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(c.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(c.MANIFEST_PARSED,this.onManifestParsed,this),t.on(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(c.BUFFER_CODECS,this.onBufferCodecs,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(c.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(c.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(c.MANIFEST_PARSED,this.onManifestParsed,this),t.off(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(c.BUFFER_CODECS,this.onBufferCodecs,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,e){const s=this.hls.levels[e.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.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 s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onLevelsUpdated(t,e){this.timer&&l(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,s=this.getMaxLevel(t.length-1);s!==this.autoLevelCapping&&v.log(`Setting autoLevelCapping to ${s}: ${t[s].height}p@${t[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=s,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 s=e.filter((e,s)=>this.isLevelAllowed(e)&&s<=t);return this.clientRect=null,CapLevelController.getMaxLevelByMediaSize(s,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 s=t.getBoundingClientRect();e.width=s.width,e.height=s.height,e.width||e.height||(e.width=s.right-s.left||t.width||0,e.height=s.bottom-s.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,s){if(null==t||!t.length)return-1;const r=(t,e)=>!e||(t.width!==e.width||t.height!==e.height);let i=t.length-1;const n=Math.max(e,s);for(let e=0;e<t.length;e+=1){const s=t[e];if((s.width>=n||s.height>=n)&&r(s,t[e+1])){i=e;break}}return i}}const Li="[eme]";class EMEController{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=EMEController.CDMCleanupPromise?[EMEController.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=v.debug.bind(v,Li),this.log=v.log.bind(v,Li),this.warn=v.warn.bind(v,Li),this.error=v.error.bind(v,Li),this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(c.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(c.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(c.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(c.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(c.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(c.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(c.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,r=e[t];if(r)return r.licenseUrl;if(t===w.WIDEVINE&&s)return s;throw new Error(`no license server URL configured for key-system "${t}"`)}getServerCertificateUrl(t){const{drmSystems:e}=this.config,s=e[t];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const e=this.hls.levels,s=(t,e,s)=>!!t&&s.indexOf(t)===e,r=e.map(t=>t.audioCodec).filter(s),i=e.map(t=>t.videoCodec).filter(s);return r.length+i.length===0&&i.push("avc1.42e01e"),new Promise((e,s)=>{const n=t=>{const a=t.shift();this.getMediaKeysPromise(a,r,i).then(t=>e({keySystem:a,mediaKeys:t})).catch(e=>{t.length?n(t):s(e instanceof EMEKeyError?e:new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))})};n(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:s}=this.config;if("function"!=typeof s){let t=`Configured requestMediaKeySystemAccess is not a function ${s}`;return null===B&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return s(t,e)}getMediaKeysPromise(t,e,s){const r=function(t,e,s,r){let i;switch(t){case w.FAIRPLAY:i=["cenc","sinf"];break;case w.WIDEVINE:case w.PLAYREADY:i=["cenc"];break;case w.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,s,r){return[{initDataTypes:t,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs="${t}"`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:s.map(t=>({contentType:`video/mp4; codecs="${t}"`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}(i,e,s,r)}(t,e,s,this.config.drmSystemOptions),i=this.keySystemAccessPromises[t];let n=null==i?void 0:i.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(r)}`),n=this.requestMediaKeySystemAccess(t,r);const e=this.keySystemAccessPromises[t]={keySystemAccess:n};return n.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),n.then(s=>{this.log(`Access for key-system "${s.keySystem}" obtained`);const r=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),e.mediaKeys=s.createMediaKeys().then(e=>(this.log(`Media-keys created for "${t}"`),r.then(s=>s?this.setMediaKeysServerCertificate(e,t,s):e))),e.mediaKeys.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),e.mediaKeys})}return n.then(()=>i.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:e,mediaKeys:s}){this.log(`Creating key-system session "${e}" keyId: ${nt(t.keyId||[])}`);const r=s.createSession(),i={decryptdata:t,keySystem:e,mediaKeys:s,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(t){const e=t.decryptdata;if(e.pssh){const s=this.createMediaKeySessionContext(t),r=this.getKeyIdString(e),i="cenc";this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(s,i,e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return nt(t.keyId)}updateKeySession(t,e){var s;const r=t.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${nt((null==(s=t.decryptdata)?void 0:s.keyId)||[])}\n } (data length: ${e?e.byteLength:e})`),r.update(e)}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise((e,s)=>{const r=U(this.config),i=t.map(F).filter(t=>!!t&&-1!==r.indexOf(t));return this.getKeySystemSelectionPromise(i).then(({keySystem:t})=>{const r=N(t);r?e(r):s(new Error(`Unable to find format for key-system "${t}"`))}).catch(s)})}loadKey(t){const e=t.keyInfo.decryptdata,s=this.getKeyIdString(e),r=`(keyId: ${s} format: "${e.keyFormat}" method: ${e.method} uri: ${e.uri})`;this.log(`Starting session for key ${r}`);let i=this.keyIdToKeySessionPromise[s];return i||(i=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(e).then(({keySystem:s,mediaKeys:i})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${r}`),this.attemptSetMediaKeys(s,i).then(()=>{this.throwIfDestroyed();const t=this.createMediaKeySessionContext({keySystem:s,mediaKeys:i,decryptdata:e});return this.generateRequestWithPreferredKeySession(t,"cenc",e.pssh,"playlist-key")}))),i.catch(t=>this.handleError(t))),i}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),t instanceof EMEKeyError?this.hls.trigger(c.ERROR,t.data):this.hls.trigger(c.ERROR,{type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[e];if(!s){const e=F(t.keyFormat),s=e?[e]:U(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=U(this.config)),0===t.length)throw new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}_onMediaEncrypted(t){const{initDataType:e,initData:s}=t;if(this.debug(`"${t.type}" event: init data type: "${e}"`),null===s)return;let r,i;if("sinf"===e&&this.config.drmSystems[w.FAIRPLAY]){const t=ht(new Uint8Array(s));try{const e=k(JSON.parse(t).sinf),s=Lt(new Uint8Array(e));if(!s)return;r=s.subarray(8,24),i=w.FAIRPLAY}catch(t){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{const t=function(t){if(!(t instanceof ArrayBuffer)||t.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},s=new DataView(t),r=s.getUint32(0);if(t.byteLength!==r&&r>44)return null;if(1886614376!==s.getUint32(4))return null;if(e.version=s.getUint32(8)>>>24,e.version>1)return null;e.systemId=nt(new Uint8Array(t,12,16));const i=s.getUint32(28);if(0===e.version){if(r-32<i)return null;e.data=new Uint8Array(t,32,i)}else if(1===e.version){e.kids=[];for(let s=0;s<i;s++)e.kids.push(new Uint8Array(t,32+16*s,16))}return e}(s);if(null===t)return;0===t.version&&t.systemId===O&&t.data&&(r=t.data.subarray(8,24)),i=function(t){if(t===O)return w.WIDEVINE}(t.systemId)}if(!i||!r)return;const n=nt(r),{keyIdToKeySessionPromise:a,mediaKeySessions:o}=this;let l=a[n];for(let t=0;t<o.length;t++){const i=o[t],h=i.decryptdata;if(h.pssh||!h.keyId)continue;const d=nt(h.keyId);if(n===d||-1!==h.uri.replace(/-/g,"").indexOf(n)){l=a[d],delete a[d],h.pssh=new Uint8Array(s),h.keyId=r,l=a[n]=l.then(()=>this.generateRequestWithPreferredKeySession(i,e,s,"encrypted-event-key-match"));break}}l||(l=a[n]=this.getKeySystemSelectionPromise([i]).then(({keySystem:t,mediaKeys:i})=>{var a;this.throwIfDestroyed();const o=new LevelKey("ISO-23001-7",n,null!=(a=N(t))?a:"");return o.pssh=new Uint8Array(s),o.keyId=r,this.attemptSetMediaKeys(t,i).then(()=>{this.throwIfDestroyed();const r=this.createMediaKeySessionContext({decryptdata:o,keySystem:t,mediaKeys:i});return this.generateRequestWithPreferredKeySession(r,e,s,"encrypted-event-no-match")})})),l.catch(t=>this.handleError(t))}_onWaitingForKey(t){this.log(`"${t.type}" event`)}attemptSetMediaKeys(t,e){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const r=Promise.all(s).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(e)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${t}"`),s.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===s.indexOf(t))})}generateRequestWithPreferredKeySession(t,e,s,r){var i,n;const a=null==(i=this.config.drmSystems)||null==(n=i[t.keySystem])?void 0:n.generateRequest;if(a)try{const r=a.call(this.hls,e,s,t);if(!r)throw new Error("Invalid response from configured generateRequest filter");e=r.initDataType,s=t.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}if(null===s)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const l=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${r}": ${l} (init data type: ${e} length: ${s?s.byteLength:null})`);const h=new _r,d=t._onmessage=e=>{const s=t.mediaKeysSession;if(!s)return void h.emit("error",new Error("invalid state"));const{messageType:r,message:i}=e;this.log(`"${r}" message event for session "${s.sessionId}" message size: ${i.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(t,i).catch(t=>{this.handleError(t),h.emit("error",t)}):"license-release"===r?t.keySystem===w.FAIRPLAY&&(this.updateKeySession(t,C("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${r}"`)},c=t._onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void h.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const s=t.keyStatus;h.emit("keyStatus",s),"expired"===s&&(this.warn(`${t.keySystem} expired for key ${l}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",d),t.mediaKeysSession.addEventListener("keystatuseschange",c);const g=new Promise((t,e)=>{h.on("error",e),h.on("keyStatus",s=>{s.startsWith("usable")?t():"output-restricted"===s?e(new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?e(new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${s}"`)):"expired"===s?e(new Error("key expired while generating request")):this.warn(`unhandled key status change "${s}"`)})});return t.mediaKeysSession.generateRequest(e,s).then(()=>{var e;this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${l}`)}).catch(t=>{throw new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>g).catch(e=>{throw h.removeAllListeners(),this.removeSession(t),e}).then(()=>(h.removeAllListeners(),t))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach((e,s)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${nt("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${nt(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e})}fetchServerCertificate(t){const e=this.config,s=new(0,e.loader)(e),r=this.getServerCertificateUrl(t);return r?(this.log(`Fetching server certificate for "${t}"`),new Promise((n,a)=>{const o={responseType:"arraybuffer",url:r},l=e.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,s,r)=>{n(t.data)},onError:(e,s,n,l)=>{a(new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:i({url:o.url,data:void 0},e)},`"${t}" certificate request failed (${r}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,i)=>{a(new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:i,response:{url:o.url,data:void 0}},`"${t}" certificate request timed out (${r})`))},onAbort:(t,e,s)=>{a(new Error("aborted"))}};s.load(o,h,d)})):Promise.resolve()}setMediaKeysServerCertificate(t,e,s){return new Promise((r,i)=>{t.setServerCertificate(s).then(i=>{this.log(`setServerCertificate ${i?"success":"not supported by CDM"} (${null==s?void 0:s.byteLength}) on "${e}"`),r(t)}).catch(t=>{i(new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e){return this.requestLicense(t,new Uint8Array(e)).then(e=>this.updateKeySession(t,new Uint8Array(e)).catch(t=>{throw new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))}unpackPlayReadyKeyMessage(t,e){const s=String.fromCharCode.apply(null,new Uint16Array(e.buffer));if(!s.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const r=(new DOMParser).parseFromString(s,"application/xml"),i=r.querySelectorAll("HttpHeader");if(i.length>0){let e;for(let s=0,r=i.length;s<r;s++){var n,a;e=i[s];const r=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;r&&o&&t.setRequestHeader(r,o)}}const o=r.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return C(atob(l))}setupLicenseXHR(t,e,s,r){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return i.call(this.hls,t,e,s,r)}).catch(n=>{if(!s.decryptdata)throw n;return t.open("POST",e,!0),i.call(this.hls,t,e,s,r)}).then(s=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:s||r}}):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,e){const s=this.config.keyLoadPolicy.default;return new Promise((r,i)=>{const n=this.getLicenseServerUrl(t.keySystem);this.log(`Sending license request to URL: ${n}`);const a=new XMLHttpRequest;a.responseType="arraybuffer",a.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return i(new Error("invalid state"));if(4===a.readyState)if(200===a.status){this._requestLicenseFailureCount=0;let e=a.response;this.log(`License received ${e instanceof ArrayBuffer?e.byteLength:e}`);const s=this.config.licenseResponseCallback;if(s)try{e=s.call(this.hls,a,n,t)}catch(t){this.error(t)}r(e)}else{const o=s.errorRetry,l=o?o.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||a.status>=400&&a.status<500)i(new EMEKeyError({type:u.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:n,data:void 0,code:a.status,text:a.statusText}},`License Request XHR failed (${n}). Status: ${a.status} (${a.statusText})`));else{const s=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${s} attempts left`),this.requestLicense(t,e).then(r,i)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=a,this.setupLicenseXHR(a,n,t,e).then(({xhr:e,licenseChallenge:s})=>{t.keySystem==w.PLAYREADY&&(s=this.unpackPlayReadyKeyMessage(e,s)),e.send(s)})})}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const s=e.media;this.media=s,s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,e=this.mediaKeySessions;t&&(t.removeEventListener("encrypted",this.onMediaEncrypted),t.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},LevelKey.clearKeyUriToKeyIdMap();const s=e.length;EMEController.CDMCleanupPromise=Promise.all(e.map(t=>this.removeSession(t)).concat(null==t?void 0:t.setMediaKeys(null).catch(t=>{this.log(`Could not clear media keys: ${t}`)}))).then(()=>{s&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)}).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)}}removeSession(t){const{mediaKeysSession:e,licenseXhr:s}=t;if(e){this.log(`Remove licenses and keys and close session ${e.sessionId}`),t._onmessage&&(e.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(e.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(t);return r>-1&&this.mediaKeySessions.splice(r,1),e.remove().catch(t=>{this.log(`Could not remove session: ${t}`)}).then(()=>e.close()).catch(t=>{this.log(`Could not close session: ${t}`)})}}}EMEController.CDMCleanupPromise=void 0;class EMEKeyError extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}var Ai,Ri,bi;!function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"}(Ai||(Ai={})),function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"}(Ri||(Ri={})),function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"}(bi||(bi={}));const ki={[bi.OBJECT]:["br","d","ot","tb"],[bi.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[bi.SESSION]:["cid","pr","sf","sid","st","v"],[bi.STATUS]:["bs","rtp"]};class SfItem{constructor(t,e){this.value=void 0,this.params=void 0,Array.isArray(t)&&(t=t.map(t=>t instanceof SfItem?t:new SfItem(t))),this.value=t,this.params=e}}class SfToken{constructor(t){this.description=void 0,this.description=t}}function Di(t,e,s,r){return new Error(`failed to ${t} "${i=e,Array.isArray(i)?JSON.stringify(i):i instanceof Map?"Map{}":i instanceof Set?"Set{}":"object"==typeof i?JSON.stringify(i):String(i)}" as ${s}`,{cause:r});var i}const Ci="Bare Item";const Pi=/[\x00-\x1f\x7f]+/;function wi(t,e,s){return Di("serialize",t,e,s)}function Ii(t){if(!1===ArrayBuffer.isView(t))throw wi(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function _i(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw wi(t,"Integer");return t.toString()}function Mi(t,e){if(t<0)return-Mi(-t,e);const s=Math.pow(10,e);if(Math.abs(t*s%1-.5)<Number.EPSILON){const e=Math.floor(t*s);return(e%2==0?e:e+1)/s}return Math.round(t*s)/s}function xi(t){const e=Mi(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw wi(t,"Decimal");const s=e.toString();return s.includes(".")?s:`${s}.0`}function Fi(t){const e=(s=t).description||s.toString().slice(7,-1);var s;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw wi(e,"Token");return e}function Oi(t){switch(typeof t){case"number":if(!l(t))throw wi(t,Ci);return Number.isInteger(t)?_i(t):xi(t);case"string":return function(t){if(Pi.test(t))throw wi(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return Fi(t);case"boolean":return function(t){if("boolean"!=typeof t)throw wi(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${_i(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return Ii(t);if(t instanceof SfToken)return Fi(t);default:throw wi(t,Ci)}}function Ni(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw wi(t,"Key");return t}function Ui(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${Ni(t)}`:`;${Ni(t)}=${Oi(e)}`).join("")}function Bi(t){return t instanceof SfItem?`${Oi(t.value)}${Ui(t.params)}`:Oi(t)}function $i(t,e={whitespace:!0}){if("object"!=typeof t)throw wi(t,"Dict");const s=t instanceof Map?t.entries():Object.entries(t),r=null!=e&&e.whitespace?" ":"";return Array.from(s).map(([t,e])=>{e instanceof SfItem==!1&&(e=new SfItem(e));let s=Ni(t);var r;return!0===e.value?s+=Ui(e.params):(s+="=",Array.isArray(e.value)?s+=`(${(r=e).value.map(Bi).join(" ")})${Ui(r.params)}`:s+=Bi(e)),s}).join(`,${r}`)}const Gi=t=>Math.round(t),Ki=t=>100*Gi(t/100),Hi={br:Gi,d:Gi,bl:Ki,dl:Ki,mtp:Ki,nor:(t,e)=>(null!=e&&e.baseUrl&&(t=function(t,e){const s=new URL(t),r=new URL(e);if(s.origin!==r.origin)return t;const i=s.pathname.split("/").slice(1),n=r.pathname.split("/").slice(1,-1);for(;i[0]===n[0];)i.shift(),n.shift();for(;n.length;)n.shift(),i.unshift("..");return i.join("/")}(t,e.baseUrl)),encodeURIComponent(t)),rtp:Ki,tb:Gi};function Vi(t,e){const s={};if(null==t||"object"!=typeof t)return s;const r=Object.keys(t).sort(),i=o({},Hi,null==e?void 0:e.formatters),n=null==e?void 0:e.filter;return r.forEach(r=>{if(null!=n&&n(r))return;let a=t[r];const o=i[r];o&&(a=o(a,e)),"v"===r&&1===a||"pr"==r&&1===a||(t=>"number"==typeof t?l(t):null!=t&&""!==t&&!1!==t)(a)&&((t=>"ot"===t||"sf"===t||"st"===t)(r)&&"string"==typeof a&&(a=new SfToken(a)),s[r]=a)}),s}function Yi(t,e={}){return t?function(t,e){return $i(t,e)}(Vi(t,e),o({whitespace:!1},e)):""}function Wi(t,e,s){return o(t,function(t,e={}){if(!t)return{};const s=Object.entries(t),r=Object.entries(ki).concat(Object.entries((null==e?void 0:e.customHeaderMap)||{})),i=s.reduce((t,e)=>{var s;const[i,n]=e,a=(null==(s=r.find(t=>t[1].includes(i)))?void 0:s[0])||bi.REQUEST;return null!=t[a]||(t[a]={}),t[a][i]=n,t},{});return Object.entries(i).reduce((t,[s,r])=>(t[s]=Yi(r,e),t),{})}(e,s))}const ji=/CMCD=[^&#]+/;function qi(t,e,s){const r=function(t,e={}){if(!t)return"";const s=Yi(t,e);return`CMCD=${encodeURIComponent(s)}`}(e,s);if(!r)return t;if(ji.test(t))return t.replace(ji,r);const i=t.includes("?")?"&":"?";return`${t}${i}${r}`}function Xi(t,e,s,r){t&&Object.keys(e).forEach(i=>{const n=t.filter(t=>t.groupId===i).map(t=>{const n=o({},t);return n.details=void 0,n.attrs=new AttrList(n.attrs),n.url=n.attrs.URI=zi(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),n.groupId=n.attrs["GROUP-ID"]=e[i],n.attrs["PATHWAY-ID"]=r,n});t.push(...n)})}function zi(t,e,s,r){const{HOST:i,PARAMS:n,[s]:a}=r;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 Qi=/^age:\s*[\d.]+\s*$/im;class XhrLoader{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 LoadStats,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,s){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=s,this.loadInternal()}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const s=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!this.stats.aborted)return i(s,e.url)}).catch(t=>(s.open("GET",e.url,!0),i(s,e.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(s,e,t)}).catch(t=>{this.callbacks.onError({code:s.status,text:t.message},e,s,r)}):this.openAndSendXhr(s,e,t)}openAndSendXhr(t,e,s){t.readyState||t.open("GET",e.url,!0);const r=e.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:n}=s.loadPolicy;if(r)for(const e in r)t.setRequestHeader(e,r[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),s.timeout=i&&l(i)?i:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:s}=this;if(!t||!e)return;const r=e.readyState,i=this.config;if(!s.aborted&&r>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.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-(s.loading.first-s.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const r=e.status,n="text"!==e.responseType;if(r>=200&&r<300&&(n&&e.response||null!==e.responseText)){s.loading.end=Math.max(self.performance.now(),s.loading.first);const i=n?e.response:e.responseText,a="arraybuffer"===e.responseType?i.byteLength:i.length;if(s.loaded=s.total=a,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first),!this.callbacks)return;const o=this.callbacks.onProgress;if(o&&o(s,t,i,e),!this.callbacks)return;const l={url:e.responseURL,data:i,code:r};this.callbacks.onSuccess(l,s,t,e)}else{const n=i.loadPolicy.errorRetry;je(n,s.retry,!1,{url:t.url,data:void 0,code:r})?this.retry(n):(v.error(`${r} while loading ${t.url}`),this.callbacks.onError({code:r,text:e.statusText},t,e,s))}}}loadtimeout(){var t;const e=null==(t=this.config)?void 0:t.loadPolicy.timeoutRetry;if(je(e,this.stats.retry,!0))this.retry(e);else{var s;v.warn(`timeout while loading ${null==(s=this.context)?void 0:s.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:e,stats:s}=this;this.retryDelay=Ye(t,s.retry),s.retry++,v.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${s.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&&Qi.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}}const Ji=/(\d+)-(\d+)\/(\d+)/;class FetchLoader{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||Zi,this.controller=new self.AbortController,this.stats=new LoadStats}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,s){const r=this.stats;if(r.loading.start)throw new Error("Loader can only be used once.");r.loading.start=self.performance.now();const i=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(o({},t.headers))};t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return s}(t,this.controller.signal),n=s.onProgress,a="arraybuffer"===t.responseType,h=a?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:c}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=s,this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),e.timeout=d&&l(d)?d:c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(r,t,this.response)},e.timeout),self.fetch(this.request).then(i=>{this.response=this.loader=i;const o=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(r,t,this.response)},c-(o-r.loading.start)),!i.ok){const{status:t,statusText:e}=i;throw new FetchError(e||"fetch, bad network response",t,i)}return r.loading.first=o,r.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Ji.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(l(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(i.headers)||r.total,n&&l(e.highWaterMark)?this.loadProgressively(i,r,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),r.loading.end=Math.max(self.performance.now(),r.loading.first);const o=i[h];o&&(r.loaded=r.total=o);const d={url:a.url,data:i,code:a.status};n&&!l(e.highWaterMark)&&n(r,t,i,a),s.onSuccess(d,r,t,a)}).catch(e=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const i=e&&e.code||0,n=e?e.message:null;s.onError({code:i,text:n},t,e?e.details:null,r)})}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,s,r=0,i){const n=new ChunkCache,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&i(e,s,n.flush(),t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h<r||n.dataLength?(n.push(l),n.dataLength>=r&&i(e,s,n.flush(),t)):i(e,s,l,t),o()}).catch(()=>Promise.reject());return o()}}function Zi(t,e){return new self.Request(t.url,e)}class FetchError extends Error{constructor(t,e,s){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=s}}const tn=/\s/,en={newCue(t,e,s,r){const i=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<r.rows.length;u++)if(n=r.rows[u],o=!0,l=0,h="",!n.isEmpty()){var c;for(let t=0;t<n.chars.length;t++)tn.test(n.chars[t].uchar)&&o?l++:(h+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===s&&(s+=1e-4),l>=16?l--:l++;const r=si(h.trim()),f=ai(e,s,r);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new d(e,s,r),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),i.push(a))}return t&&i.length&&(i.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),i.forEach(e=>pe(t,e))),i}},sn=i(i({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:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class AbrController{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:s}=this,{autoLevelEnabled:r,media:i}=s;if(!t||!i)return;const n=performance.now(),a=e?e.stats:t.stats,o=e?e.duration:t.duration,h=n-a.loading.start,d=s.minAutoLevel;if(a.aborted||a.loaded&&a.loaded===a.total||t.level<=d)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||i.paused||!i.playbackRate||!i.readyState)return;const u=s.mainForwardBufferInfo;if(null===u)return;const f=this.bwEstimator.getEstimateTTFB(),g=Math.abs(i.playbackRate);if(h<=Math.max(f,o/(2*g)*1e3))return;const m=u.len/g,p=a.loading.first?a.loading.first-a.loading.start:-1,y=a.loaded&&p>-1,E=this.getBwEstimate(),T=s.levels,S=T[t.level],L=a.total||Math.max(a.loaded,Math.round(o*S.averageBitrate/8));let A=y?h-p:h;A<1&&y&&(A=Math.min(h,8*a.loaded/E));const R=y?1e3*a.loaded/A:0,b=R?(L-a.loaded)/R:8*L/E+f/1e3;if(b<=m)return;const k=R?8*R:E;let D,C=Number.POSITIVE_INFINITY;for(D=t.level-1;D>d;D--){const t=T[D].maxBitrate;if(C=this.getTimeToLoadFrag(f/1e3,k,o*t,!T[D].details),C<m)break}if(C>=b)return;if(C>10*o)return;s.nextLoadLevel=s.nextAutoLevel=D,y?this.bwEstimator.sample(h-Math.min(f,p),a.loaded):this.bwEstimator.sampleTTFB(h);const P=T[D].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>P&&this.resetEstimator(P),this.clearTimer(),v.warn(`[abr] Fragment ${t.sn}${e?" part "+e.index:""} of level ${t.level} is loading too slowly;\n Time to underbuffer: ${m.toFixed(3)} s\n Estimated load time for current fragment: ${b.toFixed(3)} s\n Estimated load time for down switch fragment: ${C.toFixed(3)} s\n TTFB estimate: ${0|p} ms\n Current BW estimate: ${l(E)?0|E:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${D} @ ${0|P} bps`),s.trigger(c.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:a})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(v.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 EwmaBandWidthEstimator(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.FRAG_LOADING,this.onFragLoading,this),t.on(c.FRAG_LOADED,this.onFragLoaded,this),t.on(c.FRAG_BUFFERED,this.onFragBuffered,this),t.on(c.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(c.LEVEL_LOADED,this.onLevelLoaded,this),t.on(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(c.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(c.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.FRAG_LOADING,this.onFragLoading,this),t.off(c.FRAG_LOADED,this.onFragLoaded,this),t.off(c.FRAG_BUFFERED,this.onFragBuffered,this),t.off(c.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(c.LEVEL_LOADED,this.onLevelLoaded,this),t.off(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(c.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(c.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 s=e.frag;if(!this.ignoreFragment(s)){var r;if(!s.bitrateTest)this.fragCurrent=s,this.partCurrent=null!=(r=e.part)?r: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 f.BUFFER_ADD_CODEC_ERROR:case f.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case f.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:s,partCurrent:r}=this;if(t&&s&&t.sn===s.sn&&t.level===s.level){const e=performance.now(),s=r?r.stats:t.stats,i=e-s.loading.start,n=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(i-Math.min(t,n),s.loaded)}else this.bwEstimator.sampleTTFB(i)}break}}}getTimeToLoadFrag(t,e,s,r){return t+s/e+(r?this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{loading:r}=e.stats,i=r.end-r.start;l(i)&&(this.lastLevelLoadSec=i/1e3),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}onFragLoaded(t,{frag:e,part:s}){const r=s?s.stats:e.stats;if(e.type===de&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),e.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const t=s?s.duration:e.duration,i=this.hls.levels[e.level],n=(i.loaded?i.loaded.bytes:0)+r.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:r,frag:e,part:s,id:e.type};this.onFragBuffered(c.FRAG_BUFFERED,t),e.bitrateTest=!1}else this.lastLoadedFragLevel=e.level}}onFragBuffered(t,e){const{frag:s,part:r}=e,i=null!=r&&r.stats.loaded?r.stats:s.stats;if(i.aborted)return;if(this.ignoreFragment(s))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(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==de||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:e}=this.hls,s=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,i=this.findBestLevel(s,e,t,0,r,1,1);if(i>-1)return i;const n=this.hls.firstLevel,a=Math.min(Math.max(n,e),t);return v.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(),s=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&s&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const r=e&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,r)&&e[t].loadError<=e[r].loadError)return t}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this,{maxAutoLevel:r,config:i,minAutoLevel:n}=s,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=i.abrBandWidthFactor,d=i.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,r,l,0,h,d);if(t>=0)return t}let c=a?Math.min(a,i.maxStarvationDelay):i.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,i.maxLoadingDelay):i.maxLoadingDelay)-t,v.info(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,r,l,c,h,d);if(v.info(`[abr] ${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`),u>-1)return u;const f=s.levels[n],g=s.levels[s.loadLevel];return(null==f?void 0:f.bitrate)<(null==g?void 0:g.bitrate)?n:s.loadLevel}getStarvationDelay(){const t=this.hls,e=t.media;if(!e)return 1/0;const s=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,r=t.mainForwardBufferInfo;return(r?r.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,e,s,r,i,n,a){var o;const h=r+i,d=this.lastLoadedFragLevel,c=-1===d?this.hls.firstLevel:d,{fragCurrent:u,partCurrent:f}=this,{levels:g,allAudioTracks:m,loadLevel:p,config:y}=this.hls;if(1===g.length)return 0;const E=g[c],T=!(null==E||null==(o=E.details)||!o.live),S=-1===p||-1===d;let L,A="SDR",R=(null==E?void 0:E.frameRate)||0;const{audioPreference:b,videoPreference:k}=y,D=this.audioTracksByGroup||(this.audioTracksByGroup=function(t){return t.reduce((t,e)=>{let s=t.groups[e.groupId];s||(s=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(e);const r=e.channels||"2";return s.channels[r]=(s.channels[r]||0)+1,s.hasDefault=s.hasDefault||e.default,s.hasAutoSelect=s.hasAutoSelect||e.autoselect,s.hasDefault&&(t.hasDefaultAudio=!0),s.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(m));if(S){if(-1!==this.firstSelection)return this.firstSelection;const r=this.codecTiers||(this.codecTiers=function(t,e,s,r){return t.slice(s,r+1).reduce((t,s)=>{if(!s.codecSet)return t;const r=s.audioGroups;let i=t[s.codecSet];i||(t[s.codecSet]=i={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),i.minBitrate=Math.min(i.minBitrate,s.bitrate);const n=Math.min(s.height,s.width);return i.minHeight=Math.min(i.minHeight,n),i.minFramerate=Math.min(i.minFramerate,s.frameRate),i.maxScore=Math.max(i.maxScore,s.score),i.fragmentError+=s.fragmentError,i.videoRanges[s.videoRange]=(i.videoRanges[s.videoRange]||0)+1,r&&r.forEach(t=>{if(!t)return;const s=e.groups[t];s&&(i.hasDefaultAudio=i.hasDefaultAudio||e.hasDefaultAudio?s.hasDefault:s.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(s.channels).forEach(t=>{i.channels[t]=(i.channels[t]||0)+s.channels[t]}))}),t},{})}(g,D,e,s)),i=function(t,e,s,r,i){const n=Object.keys(t),a=null==r?void 0:r.channels,o=null==r?void 0:r.audioCodec,h=a&&2===parseInt(a);let d=!0,c=!1,u=1/0,f=1/0,g=1/0,m=0,p=[];const{preferHDR:y,allowedVideoRanges:v}=hs(e,i);for(let e=n.length;e--;){const s=t[n[e]];d=s.channels[2]>0,u=Math.min(u,s.minHeight),f=Math.min(f,s.minFramerate),g=Math.min(g,s.minBitrate);const r=v.filter(t=>s.videoRanges[t]>0);r.length>0&&(c=!0,p=r)}u=l(u)?u:0,f=l(f)?f:0;const E=Math.max(1080,u),T=Math.max(30,f);return g=l(g)?g:s,s=Math.max(g,s),c||(e=void 0,p=[]),{codecSet:n.reduce((e,r)=>{const i=t[r];if(r===e)return e;if(i.minBitrate>s)return ds(r,`min bitrate of ${i.minBitrate} > current estimate of ${s}`),e;if(!i.hasDefaultAudio)return ds(r,"no renditions with default or auto-select sound found"),e;if(o&&r.indexOf(o.substring(0,4))%5!=0)return ds(r,`audio codec preference "${o}" not found`),e;if(a&&!h){if(!i.channels[a])return ds(r,`no renditions with ${a} channel sound found (channels options: ${Object.keys(i.channels)})`),e}else if((!o||h)&&d&&0===i.channels[2])return ds(r,"no renditions with stereo sound found"),e;return i.minHeight>E?(ds(r,`min resolution of ${i.minHeight} > maximum of ${E}`),e):i.minFramerate>T?(ds(r,`min framerate of ${i.minFramerate} > maximum of ${T}`),e):p.some(t=>i.videoRanges[t]>0)?i.maxScore<m?(ds(r,`max score of ${i.maxScore} < selected max of ${m}`),e):e&&(Ht(r)>=Ht(e)||i.fragmentError>t[e].fragmentError)?e:(m=i.maxScore,r):(ds(r,`no variants with VIDEO-RANGE of ${JSON.stringify(p)} found`),e)},void 0),videoRanges:p,preferHDR:y,minFramerate:f,minBitrate:g}}(r,A,t,b,k),{codecSet:n,videoRanges:a,minFramerate:o,minBitrate:h,preferHDR:d}=i;L=n,A=d?a[a.length-1]:a[0],R=o,t=Math.max(t,h),v.log(`[abr] picked start tier ${JSON.stringify(i)}`)}else L=null==E?void 0:E.codecSet,A=null==E?void 0:E.videoRange;const C=f?f.duration:u?u.duration:0,P=this.bwEstimator.getEstimateTTFB()/1e3,w=[];for(let o=s;o>=e;o--){var I;const e=g[o],u=o>c;if(!e)continue;if(y.useMediaCapabilities&&!e.supportedResult&&!e.supportedPromise){const s=navigator.mediaCapabilities;"function"==typeof(null==s?void 0:s.decodingInfo)&&os(e,D,A,R,t,b)?(e.supportedPromise=ls(e,D,s),e.supportedPromise.then(t=>{if(!this.hls)return;e.supportedResult=t;const s=this.hls.levels,r=s.indexOf(e);t.error?v.warn(`[abr] MediaCapabilities decodingInfo error: "${t.error}" for level ${r} ${JSON.stringify(t)}`):t.supported||(v.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${r} ${JSON.stringify(t)}`),r>-1&&s.length>1&&(v.log(`[abr] Removing unsupported level ${r}`),this.hls.removeLevel(r)))})):e.supportedResult=ns}if(L&&e.codecSet!==L||A&&e.videoRange!==A||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 m=e.details,k=(f?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||C;let _;_=u?a*t:n*t;const M=C&&r>=2*C&&0===i?g[o].averageBitrate:g[o].maxBitrate,x=this.getTimeToLoadFrag(P,_,M*k,void 0===m);if(_>=M&&(o===d||0===e.loadError&&0===e.fragmentError)&&(x<=P||!l(x)||T&&!this.bitrateTestDelay||x<h)){const t=this.forcedAutoLevel;return o===p||-1!==t&&t===p||(w.length&&v.trace(`[abr] Skipped level(s) ${w.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[w[0]].codecs}" ${g[w[0]].videoRange}; not compatible with "${E.codecs}" ${A}`),v.info(`[abr] switch candidate:${c}->${o} adjustedbw(${Math.round(_)})-bitrate=${Math.round(_-M)} ttfb:${P.toFixed(1)} avgDuration:${k.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${S} codecSet:${L} videoRange:${A} hls.loadLevel:${p}`)),S&&(this.firstSelection=o),o}}return-1}set nextAutoLevel(t){const{maxAutoLevel:e,minAutoLevel:s}=this.hls,r=Math.min(Math.max(t,s),e);this._nextAutoLevel!==r&&(this.nextAutoLevelKey="",this._nextAutoLevel=r)}},bufferController:class BufferController{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(c.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&&v.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this.hls=t;const e="[buffer-controller]";var s;this.appendSource=(s=Nt(t.config.preferManagedMediaSource),"undefined"!=typeof self&&s===self.ManagedMediaSource),this.log=v.log.bind(v,e),this.warn=v.warn.bind(v,e),this.error=v.error.bind(v,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(c.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_PARSED,this.onManifestParsed,this),t.on(c.BUFFER_RESET,this.onBufferReset,this),t.on(c.BUFFER_APPENDING,this.onBufferAppending,this),t.on(c.BUFFER_CODECS,this.onBufferCodecs,this),t.on(c.BUFFER_EOS,this.onBufferEos,this),t.on(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(c.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(c.FRAG_PARSED,this.onFragParsed,this),t.on(c.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(c.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_PARSED,this.onManifestParsed,this),t.off(c.BUFFER_RESET,this.onBufferReset,this),t.off(c.BUFFER_APPENDING,this.onBufferAppending,this),t.off(c.BUFFER_CODECS,this.onBufferCodecs,this),t.off(c.BUFFER_EOS,this.onBufferEos,this),t.off(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(c.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(c.FRAG_PARSED,this.onFragParsed,this),t.off(c.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new BufferOperationQueue(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 s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(t,e){const s=this.media=e.media,r=Nt(this.appendSource);if(s&&r){var i;const t=this.mediaSource=new r;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{s.removeAttribute("src");const r=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||r&&t instanceof r,Nr(s),function(t,e){const s=self.document.createElement("source");s.type="video/mp4",s.src=e,t.appendChild(s)}(s,e),s.load()}catch(t){s.src=e}else s.src=e;s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:s}=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),s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(t.removeAttribute("src"),this.appendSource&&Nr(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(c.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(t=>{this.resetBuffer(t)}),this._initSourceBuffer()}resetBuffer(t){const e=this.sourceBuffer[t];try{var s;if(e)this.removeBufferListeners(t),this.sourceBuffer[t]=void 0,null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(e)}catch(e){this.warn(`onBufferReset ${t}`,e)}}onBufferCodecs(t,e){const s=this.getSourceBufferTypes().length,r=Object.keys(e);if(r.forEach(t=>{if(s){const s=this.tracks[t];if(s&&"function"==typeof s.buffer.changeType){var r;const{id:i,codec:n,levelCodec:a,container:o,metadata:l}=e[t],h=jt(s.codec,s.levelCodec),d=null==h?void 0:h.replace(Or,"$1");let c=jt(n,a);const u=null==(r=c)?void 0:r.replace(Or,"$1");if(c&&d!==u){"audio"===t.slice(0,5)&&(c=Wt(c,this.appendSource));const e=`${o};codecs=${c}`;this.appendChangeType(t,e),this.log(`switching codec ${h} to ${c}`),this.tracks[t]={buffer:s.buffer,codec:n,container:o,levelCodec:a,metadata:l,id:i}}}}else this.pendingTracks[t]=e[t]}),s)return;const i=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==i&&(this.log(`${i} bufferCodec event(s) expected ${r.join(",")}`),this.bufferCodecEventsExpected=i),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(t,e){const{operationQueue:s}=this,r={execute:()=>{const r=this.sourceBuffer[t];r&&(this.log(`changing ${t} sourceBuffer type to ${e}`),r.changeType(e)),s.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};s.append(r,t,!!this.pendingTracks[t])}onBufferAppending(t,e){const{hls:s,operationQueue:r,tracks:i}=this,{data:n,type:a,frag:o,part:l,chunkMeta:h}=e,d=h.buffering[a],g=self.performance.now();d.start=g;const m=o.stats.buffering,p=l?l.stats.buffering:null;0===m.start&&(m.start=g),p&&0===p.start&&(p.start=g);const y=i.audio;let v=!1;"audio"===a&&"audio/mpeg"===(null==y?void 0:y.container)&&(v=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const E=o.start,T={execute:()=>{if(d.executeStart=self.performance.now(),v){const t=this.sourceBuffer[a];if(t){const e=E-t.timestampOffset;Math.abs(e)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${E} (delta: ${e}) sn: ${o.sn})`),t.timestampOffset=E)}}this.appendExecutor(n,a)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();d.executeEnd=d.end=t,0===m.first&&(m.first=t),p&&0===p.first&&(p.first=t);const{sourceBuffer:e}=this,s={};for(const t in e)s[t]=BufferHelper.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(c.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:h,parent:o.type,timeRanges:s})},onError:t=>{const e={type:u.MEDIA_ERROR,parent:o.type,details:f.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:h,error:t,err:t,fatal:!1};if(t.code===DOMException.QUOTA_EXCEEDED_ERR)e.details=f.BUFFER_FULL_ERROR;else{const t=++this.appendErrors[a];e.details=f.BUFFER_APPEND_ERROR,this.warn(`Failed ${t}/${s.config.appendErrorMaxRetry} times to append segment in "${a}" sourceBuffer`),t>=s.config.appendErrorMaxRetry&&(e.fatal=!0)}s.trigger(c.ERROR,e)}};r.append(T,a,!!this.pendingTracks[a])}onBufferFlushing(t,e){const{operationQueue:s}=this,r=t=>({execute:this.removeExecutor.bind(this,t,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(c.BUFFER_FLUSHED,{type:t})},onError:e=>{this.warn(`Failed to remove from ${t} SourceBuffer`,e)}});e.type?s.append(r(e.type),e.type):this.getSourceBufferTypes().forEach(t=>{s.append(r(t),t)})}onFragParsed(t,e){const{frag:s,part:r}=e,i=[],n=r?r.elementaryStreams:s.elementaryStreams;n[b]?i.push("audiovideo"):(n[A]&&i.push("audio"),n[R]&&i.push("video"));0===i.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(()=>{const t=self.performance.now();s.stats.buffering.end=t,r&&(r.stats.buffering.end=t);const e=r?r.stats:s.stats;this.hls.trigger(c.FRAG_BUFFERED,{frag:s,part:r,stats:e,id:s.type})},i)}onFragChanged(t,e){this.trimBuffers()}onBufferEos(t,e){this.getSourceBufferTypes().reduce((t,s)=>{const r=this.sourceBuffer[s];return!r||e.type&&e.type!==s||(r.ending=!0,r.ended||(r.ended=!0,this.log(`${s} sourceBuffer now EOS`))),t&&!(r&&!r.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:s}=this;if(!s||null===e)return;if(!this.getSourceBufferTypes().length)return;const r=t.config,i=s.currentTime,n=e.levelTargetDuration,a=e.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(l(a)&&a>0){const t=Math.max(a,n),e=Math.floor(i/n)*n-t;this.flushBackBuffer(i,n,e)}if(l(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const t=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),e=Math.max(t,n),s=Math.floor(i/n)*n+e;this.flushFrontBuffer(i,n,s)}}flushBackBuffer(t,e,s){const{details:r,sourceBuffer:i}=this;this.getSourceBufferTypes().forEach(n=>{const a=i[n];if(a){const i=BufferHelper.getBuffered(a);if(i.length>0&&s>i.start(0)){if(this.hls.trigger(c.BACK_BUFFER_REACHED,{bufferEnd:s}),null!=r&&r.live)this.hls.trigger(c.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});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(c.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:n})}}})}flushFrontBuffer(t,e,s){const{sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(i=>{const n=r[i];if(n){const r=BufferHelper.getBuffered(n),a=r.length;if(a<2)return;const o=r.start(a-1),l=r.end(a-1);if(s>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(c.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:s,mediaSource:r}=this,i=t.fragments[0].start+t.totalduration,n=s.duration,a=l(r.duration)?r.duration:0;t.live&&e.config.liveDurationInfinity?(r.duration=1/0,this.updateSeekableRange(t)):(i>a&&i>n||!l(n))&&(this.log(`Updating Media Source duration to ${i.toFixed(3)}`),r.duration=i)}updateSeekableRange(t){const e=this.mediaSource,s=t.fragments;if(s.length&&t.live&&null!=e&&e.setLiveSeekableRange){const r=Math.max(0,s[0].start),i=Math.max(r,r+t.totalduration);this.log(`Media Source duration is set to ${e.duration}. Setting seekable range to ${r}-${i}.`),e.setLiveSeekableRange(r,i)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:s}=this,r=Object.keys(s).length;if(r&&(!t||2===r||"audiovideo"in s)){this.createSourceBuffers(s),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(c.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(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}}createSourceBuffers(t){const{sourceBuffer:e,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const i in t)if(!e[i]){var r;const n=t[i];if(!n)throw Error(`source buffer exists for track ${i}, however track does not`);let a=-1===(null==(r=n.levelCodec)?void 0:r.indexOf(","))?n.levelCodec:n.codec;a&&"audio"===i.slice(0,5)&&(a=Wt(a,this.appendSource));const o=`${n.container};codecs=${a}`;this.log(`creating sourceBuffer(${o})`);try{const t=e[i]=s.addSourceBuffer(o),r=i;this.addBufferListener(r,"updatestart",this._onSBUpdateStart),this.addBufferListener(r,"updateend",this._onSBUpdateEnd),this.addBufferListener(r,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(r,"bufferedchange",(t,e)=>{const s=e.removedRanges;null!=s&&s.length&&this.hls.trigger(c.BUFFER_FLUSHED,{type:i})}),this.tracks[i]={buffer:t,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(t){this.error(`error while trying to add sourceBuffer: ${t.message}`),this.hls.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:i,mimeType:o})}}}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:s}=this;s.current(t).onComplete(),s.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){var s;const r=new Error(`${t} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${r}`,e),this.hls.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:r,fatal:!1});const i=this.operationQueue.current(t);i&&i.onError(r)}removeExecutor(t,e,s){const{media:r,mediaSource:i,operationQueue:n,sourceBuffer:a}=this,o=a[t];if(!r||!i||!o)return this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void n.shiftAndExecuteNext(t);const h=l(r.duration)?r.duration:1/0,d=l(i.duration)?i.duration:1/0,c=Math.max(0,e),u=Math.min(s,h,d);u>c&&(!o.ending||o.ended)?(o.ended=!1,this.log(`Removing [${c},${u}] from the ${t} SourceBuffer`),o.remove(c,u)):n.shiftAndExecuteNext(t)}appendExecutor(t,e){const s=this.sourceBuffer[e];if(s)s.ended=!1,s.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:s}=this,r=e.map(t=>s.appendBlocker(t));Promise.all(r).then(()=>{t(),e.forEach(t=>{const e=this.sourceBuffer[t];null!=e&&e.updating||s.shiftAndExecuteNext(t)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(t,e,s){const r=this.sourceBuffer[t];if(!r)return;const i=s.bind(this,t);this.listeners[t].push({event:e,listener:i}),r.addEventListener(e,i)}removeBufferListeners(t){const e=this.sourceBuffer[t];e&&this.listeners[t].forEach(t=>{e.removeEventListener(t.event,t.listener)})}},capLevelController:CapLevelController,errorController:class ErrorController{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=v.log.bind(v,"[info]:"),this.warn=v.warn.bind(v,"[warning]:"),this.error=v.error.bind(v,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(c.ERROR,this.onError,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(c.ERROR,this.onError,this),t.off(c.ERROR,this.onErrorOut,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.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)===de?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(t,e){var s,r;if(e.fatal)return;const i=this.hls,n=e.context;switch(e.details){case f.FRAG_LOAD_ERROR:case f.FRAG_LOAD_TIMEOUT:case f.KEY_LOAD_ERROR:case f.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case f.FRAG_PARSING_ERROR:if(null!=(s=e.frag)&&s.gap)return void(e.errorAction={action:Je,flags:ss});case f.FRAG_GAP:case f.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ze);case f.LEVEL_EMPTY_ERROR:case f.LEVEL_PARSING_ERROR:{var a,o;const t=e.parent===de?e.level:i.loadLevel;e.details===f.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 f.LEVEL_LOAD_ERROR:case f.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.level)));case f.AUDIO_TRACK_LOAD_ERROR:case f.AUDIO_TRACK_LOAD_TIMEOUT:case f.SUBTITLE_LOAD_ERROR:case f.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const t=i.levels[i.loadLevel];if(t&&(n.type===le&&t.hasAudioGroup(n.groupId)||n.type===he&&t.hasSubtitleGroup(n.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.loadLevel),e.errorAction.action=Ze,void(e.errorAction.flags=rs)}return;case f.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=i.levels[i.loadLevel],s=null==t?void 0:t.attrs["HDCP-LEVEL"];s?e.errorAction={action:Ze,flags:is,hdcpLevel:s}:this.keySystemError(e)}return;case f.BUFFER_ADD_CODEC_ERROR:case f.REMUX_ALLOC_ERROR:case f.BUFFER_APPEND_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(r=e.level)?r:i.loadLevel));case f.INTERNAL_EXCEPTION:case f.BUFFER_APPENDING_ERROR:case f.BUFFER_FULL_ERROR:case f.LEVEL_SWITCH_ERROR:case f.BUFFER_STALLED_ERROR:case f.BUFFER_SEEK_OVER_HOLE:case f.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:Je,flags:ss})}e.type===u.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 s=Ve(this.hls.config.playlistLoadPolicy,t),r=this.playlistError++;if(je(s,r,He(t),t.response))return{action:es,flags:ss,retryConfig:s,retryCount:r};const i=this.getLevelSwitchAction(t,e);return s&&(i.retryConfig=s,i.retryCount=r),i}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),r=e.levels[s],{fragLoadPolicy:i,keyLoadPolicy:n}=e.config,a=Ve(t.details.startsWith("key")?n:i,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(r){t.details!==f.FRAG_GAP&&r.fragmentError++;if(je(a,o,He(t),t.response))return{action:es,flags:ss,retryConfig:a,retryCount:o}}const l=this.getLevelSwitchAction(t,s);return a&&(l.retryConfig=a,l.retryCount=o),l}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const r=this.hls.levels[e];if(r){var i,n;const e=t.details;r.loadError++,e===f.BUFFER_APPEND_ERROR&&r.fragmentError++;let l=-1;const{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:u}=s;s.autoLevelEnabled||(s.loadLevel=-1);const g=null==(i=t.frag)?void 0:i.type,m=(g===ce&&e===f.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&(e===f.BUFFER_ADD_CODEC_ERROR||e===f.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:t})=>r.audioCodec!==t),p="video"===t.sourceBufferName&&(e===f.BUFFER_ADD_CODEC_ERROR||e===f.BUFFER_APPEND_ERROR)&&h.some(({codecSet:t,audioCodec:e})=>r.codecSet!==t&&r.audioCodec===e),{type:y,groupId:v}=null!=(n=t.context)?n:{};for(let s=h.length;s--;){const i=(s+d)%h.length;if(i!==d&&i>=c&&i<=u&&0===h[i].loadError){var a,o;const s=h[i];if(e===f.FRAG_GAP&&t.frag){const e=h[i].details;if(e){const s=Xe(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(y===le&&s.hasAudioGroup(v)||y===he&&s.hasSubtitleGroup(v))continue;if(g===ce&&null!=(a=r.audioGroups)&&a.some(t=>s.hasAudioGroup(t))||g===ue&&null!=(o=r.subtitleGroups)&&o.some(t=>s.hasSubtitleGroup(t))||m&&r.audioCodec===s.audioCodec||!m&&r.audioCodec!==s.audioCodec||p&&r.codecSet===s.codecSet)continue}l=i;break}}if(l>-1&&s.loadLevel!==l)return t.levelRetry=!0,this.playlistError=0,{action:Ze,flags:ss,nextAutoLevel:l}}return{action:Ze,flags:rs}}onErrorOut(t,e){var s;switch(null==(s=e.errorAction)?void 0:s.action){case Je:break;case Ze:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===f.FRAG_GAP?/MediaSource readyState: ended/.test(e.error.message)&&(this.warn(`MediaSource ended after "${e.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):e.fatal=!0}e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,s=t.errorAction;if(!s)return;const{flags:r,hdcpLevel:i,nextAutoLevel:n}=s;switch(r){case ss:this.switchLevel(t,n);break;case is:i&&(e.maxHdcpLevel=Ce[Ce.indexOf(i)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)}s.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)}},fpsController:class FPSController{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(c.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(c.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const s=this.hls.config;if(s.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),s.fpsDroppedMonitoringPeriod)}}checkFPS(t,e,s){const r=performance.now();if(e){if(this.lastTime){const t=r-this.lastTime,i=s-this.lastDroppedFrames,n=e-this.lastDecodedFrames,a=1e3*i/t,o=this.hls;if(o.trigger(c.FPS_DROP,{currentDropped:i,currentDecoded:n,totalDroppedFrames:s}),a>0&&i>o.config.fpsDroppedMonitoringThreshold*n){let t=o.currentLevel;v.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===o.autoLevelCapping||o.autoLevelCapping>=t)&&(t-=1,o.trigger(c.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:o.currentLevel}),o.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=s,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)}},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:B,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},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:en,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class SubtitleStreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"[subtitle-stream-controller]",ue),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.LEVEL_LOADED,this.onLevelLoaded,this),t.on(c.ERROR,this.onError,this),t.on(c.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(c.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(c.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(c.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(c.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.LEVEL_LOADED,this.onLevelLoaded,this),t.off(c.ERROR,this.onError,this),t.off(c.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(c.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(c.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(c.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(c.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=_s,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:s,success:r}=e;if(this.fragPrevious=s,this.state=_s,!r)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let n;const a=s.start;for(let t=0;t<i.length;t++)if(a>=i[t].start&&a<=i[t].end){n=i[t];break}const o=s.start+s.duration;n?n.end=o:(n={start:a,end:o},i.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null)}onBufferFlushing(t,e){const{startOffset:s,endOffset:r}=e;if(0===s&&r!==Number.POSITIVE_INFINITY){const t=r-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{for(let s=0;s<e.length;)if(e[s].end<=t)e.shift();else{if(!(e[s].start<t))break;e[s].start=t,s++}}),this.fragmentTracker.removeFragmentsInRange(s,t,ue)}}onFragBuffered(t,e){var s;this.loadedmetadata||e.frag.type!==de||null!=(s=this.media)&&s.buffered.length&&(this.loadedmetadata=!0)}onError(t,e){const s=e.frag;(null==s?void 0:s.type)===ue&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Is&&(this.state=_s))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&Mr(this.levels,e)?this.levels=e.map(t=>new Level(t)):(this.tracksBuffered=[],this.levels=e.map(t=>{const e=new Level(t);return this.tracksBuffered[e.id]=[],e}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ue),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var s;if(this.currentTrackId=e.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var s;const{currentTrackId:r,levels:i}=this,{details:n,id:a}=e;if(!i)return void this.warn(`Subtitle tracks were reset while loading level ${a}`);const o=i[r];if(a>=i.length||a!==r||!o)return;this.log(`Subtitle track ${a} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(n.live||null!=(s=o.details)&&s.live){const t=this.mainDetails;if(n.deltaUpdateFailed||!t)return;const e=t.fragments[0];var h;if(o.details)l=this.alignPlaylists(n,o.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===l&&e&&(l=e.start,Be(n,l));else n.hasProgramDateTime&&t.hasProgramDateTime?(ks(n,t),l=n.fragments[0].start):e&&(l=e.start,Be(n,l))}if(o.details=n,this.levelLastLoaded=o,this.startFragRequested||!this.mainDetails&&n.live||this.setStartPosition(this.mainDetails||n,l),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===_s){Xe(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)}}_handleFragmentLoadComplete(t){const{frag:e,payload:s}=t,r=e.decryptdata,i=this.hls;if(!this.fragContextChanged(e)&&s&&s.byteLength>0&&null!=r&&r.key&&r.iv&&"AES-128"===r.method){const t=performance.now();this.decrypter.decrypt(new Uint8Array(s),r.key.buffer,r.iv.buffer).catch(t=>{throw i.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(s=>{const r=performance.now();i.trigger(c.FRAG_DECRYPTED,{frag:e,payload:s,stats:{tstart:t,tdecrypt:r}})}).catch(t=>{this.warn(`${t.name}: ${t.message}`),this.state=_s})}}doTick(){if(this.media){if(this.state===_s){const{currentTrackId:t,levels:e}=this,s=null==e?void 0:e[t];if(!s||!e.length||!s.details)return;const{config:r}=this,i=this.getLoadPosition(),n=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,r.maxBufferHole),{end:a,len:o}=n,l=this.getFwdBufferInfo(this.media,de),h=s.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+h.levelTargetDuration)return;const d=h.fragments,c=d.length,u=h.edge;let f=null;const g=this.fragPrevious;if(a<u){const t=r.maxFragLookUpTolerance,e=a>u-t?0:t;f=Xe(g,d,Math.max(d[0].start,a),e),!f&&g&&g.start<d[0].start&&(f=d[0])}else f=d[c-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),"initSegment"!==f.sn){const t=d[f.sn-h.startSN-1];t&&t.cc===f.cc&&this.fragmentTracker.getState(t)===ms&&(f=t)}this.fragmentTracker.getState(f)===ms&&this.loadFragment(f,s,a)}}else this.state=_s}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.max(e,t):e}loadFragment(t,e,s){this.fragCurrent=t,"initSegment"===t.sn?this._loadInitSegment(t,e):(this.startFragRequested=!0,super.loadFragment(t,e,s))}get mediaBufferTimeRanges(){return new BufferableInstance(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class SubtitleTrackController extends BasePlaylistController{constructor(t){super(t,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const e=Ee(this.media.textTracks);for(let s=0;s<e.length;s++)if("hidden"===e[s].mode)t=e[s];else if("showing"===e[s].mode){t=e[s];break}const s=this.findTrackForTextTrack(t);this.subtitleTrack!==s&&this.setSubtitleTrack(s)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_PARSED,this.onManifestParsed,this),t.on(c.LEVEL_LOADING,this.onLevelLoading,this),t.on(c.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(c.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(c.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_PARSED,this.onManifestParsed,this),t.off(c.LEVEL_LOADING,this.onLevelLoading,this),t.off(c.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(c.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(c.ERROR,this.onError,this)}onMediaAttached(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);Ee(this.media.textTracks).forEach(t=>{ye(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,groupId:r,details:i}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==r)return void this.warn(`Subtitle track with id:${s} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.subtitleGroups||null,r=this.groupIds;let i=this.currentTrack;if(!s||(null==r?void 0:r.length)!==(null==s?void 0:s.length)||null!=s&&s.some(t=>-1===(null==r?void 0:r.indexOf(t)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!s||-1!==s.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.subtitlePreference;if(!i&&e){this.selectDefaultTrack=!1;const s=cs(e,t);if(s>-1)i=t[s];else{const t=cs(e,this.tracks);i=this.tracks[t]}}let r=this.findTrackId(i);-1===r&&i&&(r=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==s?void 0:s.join(",")}" group-id`),this.hls.trigger(c.SUBTITLE_TRACKS_UPDATED,n),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}else this.shouldReloadPlaylist(i)&&this.setSubtitleTrack(this.trackId)}findTrackId(t){const e=this.tracksInGroup,s=this.selectDefaultTrack;for(let r=0;r<e.length;r++){const i=e[r];if((!s||i.default)&&(s||t)&&(!t||us(i,t)))return r}if(t){for(let s=0;s<e.length;s++){const r=e[s];if(xr(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const r=e[s];if(xr(t.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}findTrackForTextTrack(t){if(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){if(Fr(e[s],t))return s}}return-1}onError(t,e){!e.fatal&&e.context&&(e.context.type!==he||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||this.checkRetry(e))}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const s=this.currentTrack;if(s&&us(t,s))return s;const r=cs(t,this.tracksInGroup);if(r>-1){const t=this.tracksInGroup[r];return this.setSubtitleTrack(r),t}if(s)return null;{const s=cs(t,e);if(s>-1)return e[s]}}}return null}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){const s=e.id,r=e.groupId;let i=e.url;if(t)try{i=t.addDirectives(i)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`Loading subtitle playlist for id ${s}`),this.hls.trigger(c.SUBTITLE_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null})}}toggleTrackModes(){const{media:t}=this;if(!t)return;const e=Ee(t.textTracks),s=this.currentTrack;let r;if(s&&(r=e.filter(t=>Fr(s,t))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(e).forEach(t=>{"disabled"!==t.mode&&t!==r&&(t.mode="disabled")}),r){const t=this.subtitleDisplay?"showing":"hidden";r.mode!==t&&(r.mode=t)}}setSubtitleTrack(t){const e=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(t<-1||t>=e.length||!l(t))return void this.warn(`Invalid subtitle track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,r=e[t]||null;if(this.trackId=t,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(c.SUBTITLE_TRACK_SWITCH,{id:t});const i=!!r.details&&!r.details.live;if(t===this.trackId&&r===s&&i)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:n,groupId:a="",name:o,type:h,url:d}=r;this.hls.trigger(c.SUBTITLE_TRACK_SWITCH,{id:n,groupId:a,name:o,type:h,url:d});const u=this.switchParams(r.url,null==s?void 0:s.details,r.details);this.loadPlaylist(u)}},timelineController:class TimelineController{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(c.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(c.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(c.FRAG_LOADING,this.onFragLoading,this),t.on(c.FRAG_LOADED,this.onFragLoaded,this),t.on(c.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(c.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(c.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(c.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(c.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(c.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(c.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(c.FRAG_LOADING,this.onFragLoading,this),t.off(c.FRAG_LOADED,this.onFragLoaded,this),t.off(c.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(c.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(c.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(c.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(c.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const t=new OutputFilter(this,"textTrack1"),e=new OutputFilter(this,"textTrack2"),s=new OutputFilter(this,"textTrack3"),r=new OutputFilter(this,"textTrack4");this.cea608Parser1=new Cea608Parser(1,t,e),this.cea608Parser2=new Cea608Parser(3,s,r)}}addCues(t,e,s,r,i){let n=!1;for(let t=i.length;t--;){const r=i[t],a=Si(r[0],r[1],e,s);if(a>=0&&(r[0]=Math.min(r[0],e),r[1]=Math.max(r[1],s),n=!0,a/(s-e)>.5))return}if(n||i.push([e,s]),this.config.renderTextTracksNatively){const i=this.captionsTracks[t];this.Cues.newCue(i,e,s,r)}else{const i=this.Cues.newCue(null,e,s,r);this.hls.trigger(c.CUES_PARSED,{type:"captions",cues:i,track:t})}}onInitPtsFound(t,{frag:e,id:s,initPTS:r,timescale:i}){const{unparsedVttFrags:n}=this;"main"===s&&(this.initPTS[e.cc]={baseTime:r,timescale:i}),n.length&&(this.unparsedVttFrags=[],n.forEach(t=>{this.onFragLoaded(c.FRAG_LOADED,t)}))}getExistingTrack(t,e){const{media:s}=this;if(s)for(let r=0;r<s.textTracks.length;r++){const i=s.textTracks[r];if(Ti(i,{name:t,lang:e,attrs:{}}))return i}return null}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:s,media:r}=this,{label:i,languageCode:n}=e[t],a=this.getExistingTrack(i,n);if(a)s[t]=a,ye(s[t]),me(s[t],r);else{const e=this.createTextTrack("captions",i,n);e&&(e[t]=!0,s[t]=e)}}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const s={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=s,this.hls.trigger(c.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(t,e,s){const r=this.media;if(r)return r.addTextTrack(t,e,s)}onMediaAttaching(t,e){this.media=e.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:t}=this;Object.keys(t).forEach(e=>{ye(t[e]),delete t[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const e=t.textTracks;if(e)for(let t=0;t<e.length;t++)ye(e[t])}onSubtitleTracksUpdated(t,e){const s=e.subtitleTracks||[],r=s.some(t=>t.textCodec===li);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Mr(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media,e=t?Ee(t.textTracks):null;if(this.tracks.forEach((t,s)=>{let r;if(e){let s=null;for(let r=0;r<e.length;r++)if(e[r]&&Ti(e[r],t)){s=e[r],e[r]=null;break}s&&(r=s)}if(r)ye(r);else{const e=Ei(t);r=this.createTextTrack(e,t.name,t.lang),r&&(r.mode="disabled")}r&&this.textTracks.push(r)}),null!=e&&e.length){const t=e.filter(t=>null!==t).map(t=>t.label);t.length&&v.warn(`Media element contains unused subtitle tracks: ${t.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const t=this.tracks.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger(c.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const s=`textTrack${e[1]}`,r=this.captionsProperties[s];r&&(r.label=t.name,t.lang&&(r.languageCode=t.lang),r.media=t)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:r,lastCc:i,lastSn:n,lastPartIndex:a}=this;if(this.enabled&&s&&r&&e.frag.type===de){var o,l;const{cc:t,sn:h}=e.frag,d=null!=(o=null==e||null==(l=e.part)?void 0:l.index)?o:-1;h===n+1||h===n&&d===a+1||t===i||(s.reset(),r.reset()),this.lastCc=t,this.lastSn=h,this.lastPartIndex=d}}onFragLoaded(t,e){const{frag:s,payload:r}=e;if(s.type===ue)if(r.byteLength){const t=s.decryptdata,i="stats"in e;if(null==t||!t.encrypted||i){const t=this.tracks[s.level],i=this.vttCCs;i[s.cc]||(i[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),t&&t.textCodec===li?this._parseIMSC1(s,r):this._parseVTTs(e)}}else this.hls.trigger(c.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const s=this.hls;ui(e,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),s.trigger(c.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},e=>{v.log(`Failed to parse IMSC1: ${e}`),s.trigger(c.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})})}_parseVTTs(t){var e;const{frag:s,payload:r}=t,{initPTS:i,unparsedVttFrags:n}=this,a=i.length-1;if(!i[s.cc]&&-1===a)return void n.push(t);const o=this.hls;oi(null!=(e=s.initSegment)&&e.data?Rt(s.initSegment.data,new Uint8Array(r)):r,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,t=>{this._appendCues(t,s.level),o.trigger(c.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},e=>{const i="Missing initPTS for VTT MPEGTS"===e.message;i?n.push(t):this._fallbackToIMSC1(s,r),v.log(`Failed to parse VTT cue: ${e}`),i&&a>s.cc||o.trigger(c.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:e})})}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||ui(e,this.initPTS[t.cc],()=>{s.textCodec=li,this._parseIMSC1(t,e)},()=>{s.textCodec="wvtt"})}_appendCues(t,e){const s=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[e];if(!s||"disabled"===s.mode)return;t.forEach(t=>pe(s,t))}else{const r=this.tracks[e];if(!r)return;const i=r.default?"default":"subtitles"+e;s.trigger(c.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,e){const{frag:s}=e;s.type===ue&&this.onFragLoaded(c.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:r}=this;if(!this.enabled||!s||!r)return;const{frag:i,samples:n}=e;if(i.type!==de||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<n.length;t++){const e=n[t].bytes;if(e){const i=this.extractCea608Data(e);s.addData(n[t].pts,i[0]),r.addData(n[t].pts,i[1])}}}onBufferFlushing(t,{startOffset:e,endOffset:s,endOffsetSubtitles:r,type:i}){const{media:n}=this;if(n&&!(n.currentTime<s)){if(!i||"video"===i){const{captionsTracks:t}=this;Object.keys(t).forEach(r=>ve(t[r],e,s))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==r){const{textTracks:t}=this;Object.keys(t).forEach(s=>ve(t[s],e,r))}}}extractCea608Data(t){const e=[[],[]],s=31&t[0];let r=2;for(let i=0;i<s;i++){const s=t[r++],i=127&t[r++],n=127&t[r++];if(0===i&&0===n)continue;if(!!(4&s)){const t=3&s;0!==t&&1!==t||(e[t].push(i),e[t].push(n))}}return e}},audioStreamController:class AudioStreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"[audio-stream-controller]",ce),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:t}=this;t.on(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.LEVEL_LOADED,this.onLevelLoaded,this),t.on(c.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(c.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(c.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(c.ERROR,this.onError,this),t.on(c.BUFFER_RESET,this.onBufferReset,this),t.on(c.BUFFER_CREATED,this.onBufferCreated,this),t.on(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(c.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(c.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(c.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.LEVEL_LOADED,this.onLevelLoaded,this),t.off(c.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(c.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(c.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(c.ERROR,this.onError,this),t.off(c.BUFFER_RESET,this.onBufferReset,this),t.off(c.BUFFER_CREATED,this.onBufferCreated,this),t.off(c.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(c.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(c.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(c.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(t,{frag:e,id:s,initPTS:r,timescale:i}){if("main"===s){const t=e.cc;this.initPTS[e.cc]={baseTime:r,timescale:i},this.log(`InitPTS for cc: ${t} found from main: ${r}`),this.videoTrackCC=t,this.state===Gs&&this.tick()}}startLoad(t){if(!this.levels)return this.startPosition=t,void(this.state=Is);const e=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),e>0&&-1===t?(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e,this.state=_s):(this.loadedmetadata=!1,this.state=Os),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case _s:this.doTickIdle();break;case Os:{var t;const{levels:e,trackId:s}=this,r=null==e||null==(t=e[s])?void 0:t.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=Gs}break}case Fs:{var e;const t=performance.now(),s=this.retryDate;if(!s||t>=s||null!=(e=this.media)&&e.seeking){const{levels:t,trackId:e}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((null==t?void 0:t[e])||null),this.state=_s}break}case Gs:{const t=this.waitingData;if(t){const{frag:e,part:s,cache:r,complete:i}=t;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=xs;const t={frag:e,part:s,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(t),i&&super._handleFragmentLoadComplete(t)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${e.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const t=this.getLoadPosition(),s=BufferHelper.bufferInfo(this.mediaBuffer,t,this.config.maxBufferHole);ze(s.end,this.config.maxFragLookUpTolerance,e)<0&&(this.log(`Waiting fragment cc (${e.cc}) @ ${e.start} cancelled because another fragment at ${s.end} is needed`),this.clearWaitingFragment())}}else this.state=_s}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=_s)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){const{hls:t,levels:e,media:s,trackId:r}=this,i=t.config;if(!s&&(this.startFragRequested||!i.startFragPrefetch)||null==e||!e[r])return;const n=e[r],a=n.details;if(!a||a.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(a))return void(this.state=Os);const o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,A,ce));const l=this.getFwdBufferInfo(o,ce);if(null===l)return;const{bufferedTrack:h,switchingTrack:d}=this;if(!d&&this._streamEnded(l,a))return t.trigger(c.BUFFER_EOS,{type:"audio"}),void(this.state=Bs);const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,de),f=l.len,g=this.getMaxBufferLength(null==u?void 0:u.len),m=a.fragments,p=m[0].start;let y=this.flushing?this.getLoadPosition():l.end;if(d&&s){const t=this.getLoadPosition();h&&!xr(d.attrs,h.attrs)&&(y=t),a.PTSKnown&&t<p&&(l.end>p||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=p+.05)}if(f>=g&&!d&&y<m[m.length-1].start)return;let v=this.getNextFragment(y,a),E=!1;if(v&&this.isLoopLoading(v,y)&&(E=!!v.gap,v=this.getNextFragmentLoopLoading(v,a,l,de,g)),!v)return void(this.bufferFlushed=!0);const T=u&&v.start>u.end+a.targetduration;if(T||(null==u||!u.len)&&l.len){const t=this.getAppendedFrag(v.start,de);if(null===t)return;if(E||(E=!!t.gap||!!T&&0===u.len),T&&!E||E&&l.nextStart&&l.nextStart<t.end)return}this.loadFragment(v,n,y)}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.min(Math.max(e,t),this.config.maxMaxBufferLength):e}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new Level(t))}onAudioTrackSwitching(t,e){const s=!!e.url;this.trackId=e.id;const{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),s?this.setInterval(100):this.resetTransmuxer(),s?(this.switchingTrack=e,this.state=_s,this.flushAudioIfNeeded(e)):(this.switchingTrack=null,this.bufferedTrack=e,this.state=Is),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(c.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(t,e){var s;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=e);const{levels:r}=this,{details:i,id:n}=e;if(!r)return void this.warn(`Audio tracks were reset while loading level ${n}`);this.log(`Audio track ${n} loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const a=r[n];let o=0;if(i.live||null!=(s=a.details)&&s.live){this.checkLiveUpdate(i);const t=this.mainDetails;if(i.deltaUpdateFailed||!t)return;var l;if(!a.details&&i.hasProgramDateTime&&t.hasProgramDateTime)ks(i,t),o=i.fragments[0].start;else o=this.alignPlaylists(i,a.details,null==(l=this.levelLastLoaded)?void 0:l.details)}a.details=i,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&i.live||this.setStartPosition(this.mainDetails||i,o),this.state!==Os||this.waitForCdnTuneIn(i)||(this.state=_s),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:s,part:r,payload:i}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new TransmuxerInterface(this.hls,ce,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[s.cc],f=null==(e=s.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=r?r.index:-1,n=-1!==e,a=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,i.byteLength,e,n);c.push(i,f,d,"",s,r,h.totalduration,t,a,u)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:s,part:r,cache:new ChunkCache,complete:!1};t.push(new Uint8Array(i)),this.waitingVideoCC=this.videoTrackCC,this.state=Gs}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(t,e){const s=e.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer||null)}onFragBuffered(t,e){const{frag:s,part:r}=e;if(s.type===ce)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==s.sn){this.fragPrevious=s;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(c.AUDIO_TRACK_SWITCHED,i({},t)))}this.fragBufferedComplete(s,r)}else if(!this.loadedmetadata&&s.type===de){const t=this.videoBuffer||this.media;if(t){BufferHelper.getBuffered(t).length&&(this.loadedmetadata=!0)}}}onError(t,e){var s;if(e.fatal)this.state=$s;else switch(e.details){case f.FRAG_GAP:case f.FRAG_PARSING_ERROR:case f.FRAG_DECRYPT_ERROR:case f.FRAG_LOAD_ERROR:case f.FRAG_LOAD_TIMEOUT:case f.KEY_LOAD_ERROR:case f.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(ce,e);break;case f.AUDIO_TRACK_LOAD_ERROR:case f.AUDIO_TRACK_LOAD_TIMEOUT:case f.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Os||(null==(s=e.context)?void 0:s.type)!==le||(this.state=_s);break;case f.BUFFER_APPEND_ERROR:case f.BUFFER_FULL_ERROR:if(!e.parent||"audio"!==e.parent)return;if(e.details===f.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case f.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==R&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==R){this.flushing=!1,this.bufferFlushed=!0,this.state===Bs&&(this.state=_s);const t=this.mediaBuffer||this.media;t&&(this.afterBufferFlushed(t,e,ce),this.tick())}}_handleTransmuxComplete(t){var e;const s="audio",{hls:r}=this,{remuxResult:i,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:l,part:h,level:d}=a,{details:u}=d,{audio:f,text:g,id3:m,initSegment:p}=i;if(!this.fragContextChanged(l)&&u){if(this.state=Ns,this.switchingTrack&&f&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks){const t=l.initSegment||l;this._bufferInitSegment(d,p.tracks,t,n),r.trigger(c.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:p.tracks})}if(f){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=f;h&&(h.elementaryStreams[A]={startPTS:t,endPTS:e,startDTS:s,endDTS:r}),l.setElementaryStreamInfo(A,t,e,s,r),this.bufferFragmentData(f,l,h,n)}if(null!=m&&null!=(e=m.samples)&&e.length){const t=o({id:s,frag:l,details:u},m);r.trigger(c.FRAG_PARSING_METADATA,t)}if(g){const t=o({id:s,frag:l,details:u},g);r.trigger(c.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(l)}_bufferInitSegment(t,e,s,r){if(this.state!==Ns)return;e.video&&delete e.video;const i=e.audio;if(!i)return;i.id="audio";const n=t.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${n}/${i.codec}]`),n&&1===n.split(",").length&&(i.levelCodec=n),this.hls.trigger(c.BUFFER_CODECS,e);const a=i.initSegment;if(null!=a&&a.byteLength){const t={type:"audio",frag:s,part:null,chunkMeta:r,parent:s.type,data:a};this.hls.trigger(c.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,s){const r=this.fragmentTracker.getState(t);var i;if(this.fragCurrent=t,this.switchingTrack||r===ms||r===ys)if("initSegment"===t.sn)this._loadInitSegment(t,e);else if(null!=(i=e.details)&&i.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Gs;const s=this.mainDetails;s&&s.fragments[0].start!==e.details.fragments[0].start&&ks(e.details,s)}else this.startFragRequested=!0,super.loadFragment(t,e,s);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){const{media:e,bufferedTrack:s}=this,r=null==s?void 0:s.attrs,i=t.attrs;e&&r&&(r.CHANNELS!==i.CHANNELS||s.name!==t.name||s.lang!==t.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(t){const{hls:e}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(c.AUDIO_TRACK_SWITCHED,i({},t))}},audioTrackController:class AudioTrackController extends BasePlaylistController{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_PARSED,this.onManifestParsed,this),t.on(c.LEVEL_LOADING,this.onLevelLoading,this),t.on(c.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(c.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(c.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_PARSED,this.onManifestParsed,this),t.off(c.LEVEL_LOADING,this.onLevelLoading,this),t.off(c.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(c.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(c.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:s,groupId:r,details:i}=e,n=this.tracksInGroup[s];if(!n||n.groupId!==r)return void this.warn(`Audio track with id:${s} and group:${r} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),s===this.trackId&&this.playlistLoaded(s,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const s=e.audioGroups||null,r=this.groupIds;let i=this.currentTrack;if(!s||(null==r?void 0:r.length)!==(null==s?void 0:s.length)||null!=s&&s.some(t=>-1===(null==r?void 0:r.indexOf(t)))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>!s||-1!==s.indexOf(t.groupId));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!i&&e){const s=cs(e,t,fs);if(s>-1)i=t[s];else{const t=cs(e,this.tracks);i=this.tracks[t]}}let r=this.findTrackId(i);-1===r&&i&&(r=this.findTrackId(null));const a={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==s?void 0:s.join(",")}`),this.hls.trigger(c.AUDIO_TRACKS_UPDATED,a);const o=this.trackId;if(-1!==r&&-1===o)this.setAudioTrack(r);else if(t.length&&-1===o){var n;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(n=this.groupIds)?void 0:n.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}else this.shouldReloadPlaylist(i)&&this.setAudioTrack(this.trackId)}onError(t,e){!e.fatal&&e.context&&(e.context.type!==le||e.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(e.context.groupId)||(this.requestScheduled=-1,this.checkRetry(e)))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const r=this.currentTrack;if(r&&us(t,r,fs))return r;const i=cs(t,this.tracksInGroup,fs);if(i>-1){const t=this.tracksInGroup[i];return this.setAudioTrack(i),t}if(r){let r=e.loadLevel;-1===r&&(r=e.firstAutoLevel);const i=function(t,e,s,r,i){const n=e[r],a=e.reduce((t,e,s)=>{const r=e.uri;return(t[r]||(t[r]=[])).push(s),t},{})[n.uri];a.length>1&&(r=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=gs(e,r,e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;const r=e.audioGroups,n=s.filter(t=>!r||-1!==r.indexOf(t.groupId));return cs(t,n,i)>-1});return d>-1?d:gs(e,r,e=>{const r=e.audioGroups,n=s.filter(t=>!r||-1!==r.indexOf(t.groupId));return cs(t,n,i)>-1})}(t,e.levels,s,r,fs);if(-1===i)return null;e.nextLoadLevel=i}if(t.channels||t.audioCodec){const e=cs(t,s);if(e>-1)return s[e]}}}return null}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn(`Invalid audio track id: ${t}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,r=e[t],n=r.details&&!r.details.live;if(t===this.trackId&&r===s&&n)return;if(this.log(`Switching to audio-track ${t} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=t,this.currentTrack=r,this.hls.trigger(c.AUDIO_TRACK_SWITCHING,i({},r)),n)return;const a=this.switchParams(r.url,null==s?void 0:s.details,r.details);this.loadPlaylist(a)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const r=e[s];if((!this.selectDefaultTrack||r.default)&&(!t||us(t,r,fs)))return s}if(t){const{name:s,lang:r,assocLang:i,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(us({name:s,lang:r,assocLang:i,characteristics:n,audioCodec:a,channels:o},e[t],fs))return t}for(let s=0;s<e.length;s++){const r=e[s];if(xr(t.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return s}for(let s=0;s<e.length;s++){const r=e[s];if(xr(t.attrs,r.attrs,["LANGUAGE"]))return s}}return-1}loadPlaylist(t){const e=this.currentTrack;if(this.shouldLoadPlaylist(e)&&e){super.loadPlaylist();const s=e.id,r=e.groupId;let i=e.url;if(t)try{i=t.addDirectives(i)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}this.log(`loading audio-track playlist ${s} "${e.name}" lang:${e.lang} group:${r}`),this.clearTimer(),this.hls.trigger(c.AUDIO_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null})}}},emeController:EMEController,cmcdController:class CMCDController{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=t=>{try{this.apply(t,{ot:Ai.MANIFEST,su:!this.initialized})}catch(t){v.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const e=t.frag,s=this.hls.levels[e.level],r=this.getObjectType(e),i={d:1e3*e.duration,ot:r};r!==Ai.VIDEO&&r!==Ai.AUDIO&&r!=Ai.MUXED||(i.br=s.bitrate/1e3,i.tb=this.getTopBandwidth(r)/1e3,i.bl=this.getBufferLength(r)),this.apply(t,i)}catch(t){v.warn("Could not generate segment CMCD data.",t)}},this.hls=t;const e=this.config=t.config,{cmcd:s}=e;null!=s&&(e.pLoader=this.createPlaylistLoader(),e.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||function(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const s=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?s:3&s|8).toString(16)})}}}(),this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(c.MEDIA_DETACHED,this.onMediaDetached,this),t.on(c.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(c.MEDIA_DETACHED,this.onMediaDetached,this),t.off(c.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,e){var s,r;this.audioBuffer=null==(s=e.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(r=e.tracks.video)?void 0:r.buffer}createData(){var t;return{v:1,sf:Ri.HLS,sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){o(e,this.createData());const s=e.ot===Ai.INIT||e.ot===Ai.VIDEO||e.ot===Ai.MUXED;this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const{includeKeys:r}=this;r&&(e=Object.keys(e).reduce((t,s)=>(r.includes(s)&&(t[s]=e[s]),t),{})),this.useHeaders?(t.headers||(t.headers={}),Wi(t.headers,e)):t.url=qi(t.url,e)}getObjectType(t){const{type:e}=t;return"subtitle"===e?Ai.TIMED_TEXT:"initSegment"===t.sn?Ai.INIT:"audio"===e?Ai.AUDIO:"main"===e?this.hls.audioTracks.length?Ai.VIDEO:Ai.MUXED:void 0}getTopBandwidth(t){let e,s=0;const r=this.hls;if(t===Ai.AUDIO)e=r.audioTracks;else{const t=r.maxAutoLevel,s=t>-1?t+1:r.levels.length;e=r.levels.slice(0,s)}for(const t of e)t.bitrate>s&&(s=t.bitrate);return s>0?s:NaN}getBufferLength(t){const e=this.hls.media,s=t===Ai.AUDIO?this.audioBuffer:this.videoBuffer;if(!s||!e)return NaN;return 1e3*BufferHelper.bufferInfo(s,e.currentTime,this.config.maxBufferHole).len}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,s=t||this.config.loader;return class CmcdPlaylistLoader{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,r){e(t),this.loader.load(t,s,r)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,s=t||this.config.loader;return class CmcdFragmentLoader{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,r){e(t),this.loader.load(t,s,r)}}}},contentSteeringController:class ContentSteeringController{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=v.log.bind(v,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(c.MANIFEST_PARSED,this.onManifestParsed,this),t.on(c.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(c.MANIFEST_PARSED,this.onManifestParsed,this),t.off(c.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:s}=e;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:s}=e;if((null==s?void 0:s.action)===Ze&&s.flags===rs){const t=this.levels;let r=this.pathwayPriority,i=this.pathwayId;if(e.context){const{groupId:s,pathwayId:r,type:n}=e.context;s&&t?i=this.getPathwayForGroupId(s,n,i):r&&(i=r)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!r&&t&&(r=t.reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==i),s.resolved||v.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${i} levels: ${t?t.length:t} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const s=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),e=this.getLevelsForPathway(s),this.pathwayId=s}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 s=this.penalizedPathways,r=performance.now();Object.keys(s).forEach(t=>{r-s[t]>3e5&&delete s[t]});for(let r=0;r<t.length;r++){const i=t[r];if(i in s)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,Ke(e),this.hls.trigger(c.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,s){const r=this.getLevelsForPathway(s).concat(this.levels||[]);for(let s=0;s<r.length;s++)if(e===le&&r[s].hasAudioGroup(t)||e===he&&r[s].hasSubtitleGroup(t))return r[s].pathwayId;return s}clonePathways(t){const e=this.levels;if(!e)return;const s={},r={};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 AttrList(t.attrs);e["PATHWAY-ID"]=i;const n=e.AUDIO&&`${e.AUDIO}_clone_${i}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${i}`;n&&(s[e.AUDIO]=n,e.AUDIO=n),o&&(r[e.SUBTITLES]=o,e.SUBTITLES=o);const l=zi(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new Level({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++)h.addGroupId("audio",`${t.audioGroups[e]}_clone_${i}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)h.addGroupId("text",`${t.subtitleGroups[e]}_clone_${i}`);return h});e.push(...o),Xi(this.audioTracks,s,a,i),Xi(this.subtitleTracks,r,a,i)})}loadSteeringManifest(t){const e=this.hls.config,s=e.loader;let r;this.loader&&this.loader.destroy(),this.loader=new s(e);try{r=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==r.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);r.searchParams.set("_HLS_pathway",this.pathwayId),r.searchParams.set("_HLS_throughput",""+t)}const i={responseType:"json",url:r.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,s,i)=>{this.log(`Loaded steering manifest: "${r}"`);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,r).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${a}`)}this.scheduleRefresh(this.uri||s.url),o&&this.clonePathways(o);const h={steeringManifest:n,url:r.toString()};this.hls.trigger(c.STEERING_MANIFEST_LOADED,h),l&&this.updatePathwayPriority(l)},onError:(t,e,s,r)=>{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){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(i=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,i)},onTimeout:(t,e,s)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${r}`),this.loader.load(i,o,l)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const s=null==(e=this.hls)?void 0:e.media;!s||s.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}}});function rn(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(rn):Object.keys(t).reduce((e,s)=>(e[s]=rn(t[s]),e),{}):t}function nn(t){const e=t.loader;if(e!==FetchLoader&&e!==XhrLoader)v.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=FetchLoader,t.progressive=!0,t.enableSoftwareAES=!0,v.log("[config]: Progressive streaming enabled, using FetchLoader"))}}let an;class LevelController extends BasePlaylistController{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(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(c.LEVEL_LOADED,this.onLevelLoaded,this),t.on(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(c.FRAG_BUFFERED,this.onFragBuffered,this),t.on(c.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(c.LEVEL_LOADED,this.onLevelLoaded,this),t.off(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(c.FRAG_BUFFERED,this.onFragBuffered,this),t.off(c.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 s=this.hls.config.preferManagedMediaSource,r=[],i={},n={};let a=!1,o=!1,l=!1;e.levels.forEach(t=>{var e,h;const d=t.attrs;let{audioCodec:c,videoCodec:u}=t;-1!==(null==(e=c)?void 0:e.indexOf("mp4a.40.34"))&&(an||(an=/chrome|firefox/i.test(navigator.userAgent)),an&&(t.audioCodec=c=void 0)),c&&(t.audioCodec=c=Wt(c,s)),0===(null==(h=u)?void 0:h.indexOf("avc1"))&&(u=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}(u));const{width:f,height:g,unknownCodecs:m}=t;if(a||(a=!(!f||!g)),o||(o=!!u),l||(l=!!c),null!=m&&m.length||c&&!Bt(c,"audio",s)||u&&!Bt(u,"video",s))return;const{CODECS:p,"FRAME-RATE":y,"HDCP-LEVEL":v,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=d,L=`${`${E||"."}-`}${t.bitrate}-${T}-${y}-${p}-${S}-${v}`;if(i[L])if(i[L].uri===t.url||t.attrs["PATHWAY-ID"])i[L].addGroupId("audio",d.AUDIO),i[L].addGroupId("text",d.SUBTITLES);else{const e=n[L]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const s=new Level(t);i[L]=s,r.push(s)}else{const e=new Level(t);i[L]=e,n[L]=1,r.push(e)}}),this.filterAndSortMediaOptions(r,e,a,o,l)}filterAndSortMediaOptions(t,e,s,r,i){let n=[],a=[],o=t;if((s||r)&&i&&(o=o.filter(({videoCodec:t,videoRange:e,width:s,height:r})=>{return(!!t||!(!s||!r))&&(!!(i=e)&&Pe.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(c.ERROR,{type:u.MEDIA_ERROR,details:f.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||Bt(e.audioCodec,"audio",t)),on(n)}e.subtitles&&(a=e.subtitles,on(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(s&&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 Pe.indexOf(t.videoRange)-Pe.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const s=Kt(t.videoCodec),r=Kt(e.videoCodec);if(s!==r)return r-s}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const s=Ht(t.codecSet),r=Ht(e.codecSet);if(s!==r)return r-s}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let h=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){h=l[t];break}this._levels=o;for(let t=0;t<o.length;t++)if(o[t]===h){var d;this._firstLevel=t;const e=h.bitrate,s=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${o.length} level(s) found, first bitrate: ${e}`),void 0===(null==(d=this.hls.userConfig)?void 0:d.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>s&&s===sn.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const g=i&&!r,m={levels:o,audioTracks:n,subtitleTracks:a,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:i,video:r,altAudio:!g&&n.some(t=>!!t.url)};this.hls.trigger(c.MANIFEST_PARSED,m),(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 s=new Error("invalid level idx"),r=t<0;if(this.hls.trigger(c.ERROR,{type:u.OTHER_ERROR,details:f.LEVEL_SWITCH_ERROR,level:t,fatal:r,error:s,reason:s.message}),r)return;t=Math.min(t,e.length-1)}const s=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs["PATHWAY-ID"]:void 0,n=e[t],a=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=n,s===t&&n.details&&r&&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 ${s}${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(c.LEVEL_SWITCHING,o);const l=n.details;if(!l||l.live){const t=this.switchParams(n.uri,null==r?void 0:r.details,l);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===oe&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(void 0!==e&&e.type===de){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const s=this._levels[e.level];null!=s&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(t,e){var s;const{level:r,details:i}=e,n=this._levels[r];var a;if(!n)return this.warn(`Invalid level index ${r}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(i.deltaUpdateFailed=!0));r===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(r,e,n.details)):null!=(s=e.deliveryDirectives)&&s.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){let r=s.uri;if(t)try{r=t.addDirectives(r)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}const i=s.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:""} ${r}`),this.clearTimer(),this.hls.trigger(c.LEVEL_LOADING,{url:r,level:e,pathwayId:s.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 s=this._levels.filter((e,s)=>s!==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));Ke(s),this._levels=s,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(c.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(c.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function on(t){const e={};t.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}class KeyLoader{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const s in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[s].loader;if(r){var e;if(t&&t!==(null==(e=r.context)?void 0:e.frag.type))return;r.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=f.KEY_LOAD_ERROR,s,r,i){return new LoadError({type:u.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:i,error:s,networkDetails:r})}loadClear(t,e){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:r}=t;for(let t=0;t<e.length;t++){const i=e[t];if(r<=i.cc&&("initSegment"===s||"initSegment"===i.sn||s<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 s,r;e&&t.setKeyFormat(e);const i=t.decryptdata;if(!i){const s=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,f.KEY_LOAD_ERROR,s))}const n=i.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,f.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let a=this.keyUriToKeyInfo[n];if(null!=(s=a)&&s.decryptdata.key)return i.key=a.decryptdata.key,Promise.resolve({frag:t,keyInfo:a});var o;if(null!=(r=a)&&r.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,f.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t,e){const s={frag:e,keyInfo:t};if(this.emeController&&this.config.emeEnabled){const e=this.emeController.loadKey(s);if(e)return(t.keyLoadPromise=e.then(e=>(t.mediaKeySessionContext=e,s))).catch(e=>{throw t.keyLoadPromise=null,e})}return Promise.resolve(s)}loadKeyHTTP(t,e){const s=this.config,r=new(0,s.loader)(s);return e.keyLoader=t.loader=r,t.keyLoadPromise=new Promise((n,a)=>{const o={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(t,e,s,r)=>{const{frag:i,keyInfo:o,url:l}=s;if(!i.decryptdata||o!==this.keyUriToKeyInfo[l])return a(this.createKeyLoadError(i,f.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),r));o.decryptdata.key=i.decryptdata.key=new Uint8Array(t.data),i.keyLoader=null,o.loader=null,n({frag:i,keyInfo:o})},onError:(t,s,r,n)=>{this.resetLoader(s),a(this.createKeyLoadError(e,f.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),r,i({url:o.url,data:void 0},t)))},onTimeout:(t,s,r)=>{this.resetLoader(s),a(this.createKeyLoadError(e,f.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(t,s,r)=>{this.resetLoader(s),a(this.createKeyLoadError(e,f.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};r.load(o,h,d)})}resetLoader(t){const{frag:e,keyInfo:s,url:r}=t,i=s.loader;e.keyLoader===i&&(e.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[r],i&&i.destroy()}}function ln(){return self.SourceBuffer||self.WebKitSourceBuffer}function hn(){if(!Nt())return!1;const t=ln();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}class GapController{constructor(t,e,s,r){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=s,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(t,e){const{config:s,media:r,stalled:i}=this;if(null===r)return;const{currentTime:n,seeking:a}=r,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;v.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(r.paused&&!a||r.ended||0===r.playbackRate||!BufferHelper.getBuffered(r).length)return void(this.nudgeRetry=0);const h=BufferHelper.bufferInfo(r,n,0),d=h.nextStart||0;if(a){const t=h.len>2,s=!d||e&&e.start<=n||d-n>2&&!this.fragmentTracker.getPartialFragment(n);if(t||s)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var c;if(!(h.len>0)&&!d)return;const t=Math.max(d,h.start||0)-n,e=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,s=(null==e||null==(c=e.details)?void 0:c.live)?2*e.details.targetduration:2,i=this.fragmentTracker.getPartialFragment(n);if(t>0&&(t<=s||i))return void(r.paused||this._trySkipBufferHole(i))}const u=self.performance.now();if(null===i)return void(this.stalled=u);const f=u-i;if(!a&&f>=250&&(this._reportStall(h),!this.media))return;const g=BufferHelper.bufferInfo(r,n,s.maxBufferHole);this._tryFixBufferStall(g,f)}_tryFixBufferStall(t,e){const{config:s,fragmentTracker:r,media:i}=this;if(null===i)return;const n=i.currentTime,a=r.getPartialFragment(n);if(a){if(this._trySkipBufferHole(a)||!this.media)return}(t.len>s.maxBufferHole||t.nextStart&&t.nextStart-n<s.maxBufferHole)&&e>1e3*s.highBufferWatchdogPeriod&&(v.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(t){const{hls:e,media:s,stallReported:r}=this;if(!r&&s){this.stallReported=!0;const r=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(t)})`);v.warn(r.message),e.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:t.len})}}_trySkipBufferHole(t){const{config:e,hls:s,media:r}=this;if(null===r)return 0;const i=r.currentTime,n=BufferHelper.bufferInfo(r,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&&r.readyState<3,h=a-i;if(h>0&&(o||l)){if(h>e.maxBufferHole){const{fragmentTracker:e}=this;let s=!1;if(0===i){const t=e.getAppendedFrag(0,de);t&&a<t.end&&(s=!0)}if(!s){const s=t||e.getAppendedFrag(i,de);if(s){let t=!1,r=s.end;for(;r<a;){const s=e.getPartialFragment(r);if(!s){t=!0;break}r+=s.duration}if(t)return 0}}}const n=Math.max(a+.05,i+.1);if(v.warn(`skipping hole, adjusting currentTime from ${i} to ${n}`),this.moved=!0,this.stalled=null,r.currentTime=n,t&&!t.gap){const e=new Error(`fragment loaded with buffer holes, seeking from ${i} to ${n}`);s.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:e,reason:e.message,frag:t})}return n}}return 0}_tryNudgeBuffer(){const{config:t,hls:e,media:s,nudgeRetry:r}=this;if(null===s)return;const i=s.currentTime;if(this.nudgeRetry++,r<t.nudgeMaxRetry){const n=i+(r+1)*t.nudgeOffset,a=new Error(`Nudging 'currentTime' from ${i} to ${n}`);v.warn(a.message),s.currentTime=n,e.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_NUDGE_ON_STALL,error:a,fatal:!1})}else{const s=new Error(`Playhead still not moving while enough data buffered @${i} after ${t.nudgeMaxRetry} nudges`);v.error(s.message),e.trigger(c.ERROR,{type:u.MEDIA_ERROR,details:f.BUFFER_STALLED_ERROR,error:s,fatal:!0})}}}class StreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"[stream-controller]",de),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(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(c.MANIFEST_LOADING,this.onManifestLoading,this),t.on(c.MANIFEST_PARSED,this.onManifestParsed,this),t.on(c.LEVEL_LOADING,this.onLevelLoading,this),t.on(c.LEVEL_LOADED,this.onLevelLoaded,this),t.on(c.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(c.ERROR,this.onError,this),t.on(c.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(c.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(c.BUFFER_CREATED,this.onBufferCreated,this),t.on(c.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(c.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(c.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(c.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(c.MANIFEST_LOADING,this.onManifestLoading,this),t.off(c.MANIFEST_PARSED,this.onManifestParsed,this),t.off(c.LEVEL_LOADED,this.onLevelLoaded,this),t.off(c.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(c.ERROR,this.onError,this),t.off(c.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(c.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(c.BUFFER_CREATED,this.onBufferCreated,this),t.off(c.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(c.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(c.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(t){if(this.levels){const{lastCurrentTime:e,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=s.startLevel;-1===t&&(s.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=s.firstAutoLevel),s.nextLoadLevel=t,this.level=s.loadLevel,this.loadedmetadata=!1}e>0&&-1===t&&(this.log(`Override startPosition with lastCurrentTime @${e.toFixed(3)}`),t=e),this.state=_s,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Is}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Ks:{const{levels:t,level:e}=this,s=null==t?void 0:t[e],r=null==s?void 0:s.details;if(r&&(!r.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(r))break;this.state=_s;break}if(this.hls.nextLoadLevel!==this.level){this.state=_s;break}break}case Fs:{var t;const e=self.performance.now(),s=this.retryDate;if(!s||e>=s||null!=(t=this.media)&&t.seeking){const{levels:t,level:e}=this,s=null==t?void 0:t[e];this.resetStartWhenNotLoaded(s||null),this.state=_s}}}this.state===_s&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:r}=this;if(null===e||!r&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const i=t.nextLoadLevel;if(null==s||!s[i])return;const n=s[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(c.BUFFER_EOS,t),void(this.state=Bs)}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===Ks||l.live&&this.levelLastLoaded!==n)return this.level=i,void(this.state=Ks);const h=a.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>a.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:a.end;let f=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&this.fragmentTracker.getState(f)!==vs){var g;const t=(null!=(g=this.backtrackFragment)?g:f).sn-l.startSN,e=l.fragments[t-1];e&&f.cc===e.cc&&(f=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&a.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,u)){if(!f.gap){const t=this.audioOnly&&!this.altAudio?A:R,e=(t===R?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,de)}f=this.getNextFragmentLoopLoading(f,l,a,de,d)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,n,u))}loadFragment(t,e,s){const r=this.fragmentTracker.getState(t);this.fragCurrent=t,r===ms||r===ys?"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,s)):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,de)}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 s;const r=this.getAppendedFrag(e.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.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],r=this.fragLastKbps;s=r&&this.fragCurrent?this.fragCurrent.duration*e.maxBitrate/(1e3*r)+1:0}else s=0;const n=this.getBufferedFrag(e.currentTime+s);if(n){const t=this.followingBufferedFrag(n);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,r=Math.max(n.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,s*(this.couldBacktrack?.5:.125)),s*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,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 Ms:case xs:case Fs:case Ns:case Us:this.state=_s}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.altAudio?"video":null)}onMediaAttached(t,e){super.onMediaAttached(t,e);const s=e.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),s.addEventListener("playing",this.onvplaying),s.addEventListener("seeked",this.onvseeked),this.gapController=new GapController(this.config,s,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;l(e)&&this.log(`Media seeked to ${e.toFixed(3)}`);const s=this.getMainFwdBufferInfo();null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${s?s.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(c.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 s=!1,r=!1;e.levels.forEach(t=>{const e=t.audioCodec;e&&(s=s||-1!==e.indexOf("mp4a.40.2"),r=r||-1!==e.indexOf("mp4a.40.5"))}),this.audioCodecSwitch=s&&r&&!function(){var t;const e=ln();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:s}=this;if(!s||this.state!==_s)return;const r=s[e.level];(!r.details||r.details.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(r.details))&&(this.state=Ks)}onLevelLoaded(t,e){var s;const{levels:r}=this,i=e.level,n=e.details,a=n.totalduration;if(!r)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=r[i],l=this.fragCurrent;!l||this.state!==xs&&this.state!==Fs||l.level!==e.level&&l.loader&&this.abortCurrentFrag();let h=0;if(n.live||null!=(s=o.details)&&s.live){var d;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)}if(o.details=n,this.levelLastLoaded=o,this.hls.trigger(c.LEVEL_UPDATED,{details:n,level:i}),this.state===Ks){if(this.waitForCdnTuneIn(n))return;this.state=_s}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(t){var e;const{frag:s,part:r,payload:i}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const a=n[s.level],o=a.details;if(!o)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=s.initSegment)?void 0:e.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,de,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=-1!==f,m=new ChunkMetadata(s.level,s.sn,s.stats.chunkCount,i.byteLength,f,g),p=this.initPTS[s.cc];u.push(i,d,c,l,s,r,o.totalduration,h,m,p)}onAudioTrackSwitching(t,e){const s=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;s&&(t.trigger(c.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(c.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const s=e.id,r=!!this.hls.audioTracks[s].url;if(r){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=r,this.tick()}onBufferCreated(t,e){const s=e.tracks;let r,i,n=!1;for(const t in s){const e=s[t];if("main"===e.id){if(i=t,r=e,"video"===t){const e=s[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&r?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:s,part:r}=e;if(s&&s.type!==de)return;if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${r?" p: "+r.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Us&&(this.state=_s));const i=r?r.stats:s.stats;this.fragLastKbps=Math.round(8*i.total/(i.buffering.end-i.loading.first)),"initSegment"!==s.sn&&(this.fragPrevious=s),this.fragBufferedComplete(s,r)}onError(t,e){var s;if(e.fatal)this.state=$s;else switch(e.details){case f.FRAG_GAP:case f.FRAG_PARSING_ERROR:case f.FRAG_DECRYPT_ERROR:case f.FRAG_LOAD_ERROR:case f.FRAG_LOAD_TIMEOUT:case f.KEY_LOAD_ERROR:case f.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(de,e);break;case f.LEVEL_LOAD_ERROR:case f.LEVEL_LOAD_TIMEOUT:case f.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ks||(null==(s=e.context)?void 0:s.type)!==oe||(this.state=_s);break;case f.BUFFER_APPEND_ERROR:case f.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;if(e.details===f.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case f.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}checkBuffer(){const{media:t,gapController:e}=this;if(t&&e&&t.readyState){if(this.loadedmetadata||!BufferHelper.getBuffered(t).length){const t=this.state!==_s?this.fragCurrent:null;e.poll(this.lastCurrentTime,t)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=_s,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==A||this.audioOnly&&!this.altAudio){const t=(e===R?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(t,e,de),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 s=this.startPosition;if(s>=0&&e<s){if(t.seeking)return void this.log(`could not seek to ${s}, already seeking at ${e}`);const r=BufferHelper.getBuffered(t),i=(r.length?r.start(0):0)-s;i>0&&(i<this.config.maxBufferHole||i<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${i} to match buffer start`),s+=i,this.startPosition=s),this.log(`seek to target start position ${s} from current time ${e}`),t.currentTime=s}}_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(s=>{const{hls:r}=this;if(!s||this.fragContextChanged(t))return;e.fragmentError=0,this.state=_s,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(),r.trigger(c.FRAG_LOADED,s),t.bitrateTest=!1})}_handleTransmuxComplete(t){var e;const s="main",{hls:r}=this,{remuxResult:i,chunkMeta:n}=t,a=this.getCurrentContext(n);if(!a)return void this.resetWhenMissingContext(n);const{frag:o,part:h,level:d}=a,{video:u,text:f,id3:g,initSegment:m}=i,{details:p}=d,y=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o))this.fragmentTracker.removeFragment(o);else{if(this.state=Ns,m){if(null!=m&&m.tracks){const t=o.initSegment||o;this._bufferInitSegment(d,m.tracks,t,n),r.trigger(c.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:s,tracks:m.tracks})}const t=m.initPTS,e=m.timescale;l(t)&&(this.initPTS[o.cc]={baseTime:t,timescale:e},r.trigger(c.INIT_PTS_FOUND,{frag:o,id:s,initPTS:t,timescale:e}))}if(u&&p&&"initSegment"!==o.sn){const t=p.fragments[o.sn-1-p.startSN],e=o.sn===p.startSN,s=!t||o.cc>t.cc;if(!1!==i.independent){const{startPTS:t,endPTS:r,startDTS:i,endDTS:a}=u;if(h)h.elementaryStreams[u.type]={startPTS:t,endPTS:r,startDTS:i,endDTS:a};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!s&&(this.couldBacktrack=!0),u.dropped&&u.independent){const i=this.getMainFwdBufferInfo(),n=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,l=u.firstKeyFramePTS?u.firstKeyFramePTS:t;if(!e&&n<l-this.config.maxBufferHole&&!s)return void this.backtrack(o);s&&(o.gap=!0),o.setElementaryStreamInfo(u.type,o.start,r,o.start,a,!0)}else e&&t>2&&(o.gap=!0);o.setElementaryStreamInfo(u.type,t,r,i,a),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,h,n,e||s)}else{if(!e&&!s)return void this.backtrack(o);o.gap=!0}}if(y){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=y;h&&(h.elementaryStreams[A]={startPTS:t,endPTS:e,startDTS:s,endDTS:r}),o.setElementaryStreamInfo(A,t,e,s,r),this.bufferFragmentData(y,o,h,n)}if(p&&null!=g&&null!=(e=g.samples)&&e.length){const t={id:s,frag:o,details:p,samples:g.samples};r.trigger(c.FRAG_PARSING_METADATA,t)}if(p&&f){const t={id:s,frag:o,details:p,samples:f.samples};r.trigger(c.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,s,r){if(this.state!==Ns)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 s=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(e&&(e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==i.metadata.channelCount&&-1===s.indexOf("firefox")&&(e="mp4a.40.5")),e&&-1!==e.indexOf("mp4a.40.5")&&-1!==s.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(c.BUFFER_CODECS,e),Object.keys(e).forEach(t=>{const i=e[t].initSegment;null!=i&&i.byteLength&&this.hls.trigger(c.BUFFER_APPENDING,{type:t,data:i,frag:s,part:null,chunkMeta:r,parent:s.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,de)}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=_s}checkFragmentChanged(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const s=t.currentTime;if(BufferHelper.isBuffered(t,s)?e=this.getAppendedFrag(s):BufferHelper.isBuffered(t,s+.1)&&(e=this.getAppendedFrag(s+.1)),e){this.backtrackFragment=null;const t=this.fragPlaying,s=e.level;t&&e.sn===t.sn&&t.level===s||(this.fragPlaying=e,this.hls.trigger(c.FRAG_CHANGED,{frag:e}),t&&t.level===s||this.hls.trigger(c.LEVEL_SWITCHED,{level:s}))}}}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,s=this.currentFrag;if(s&&l(e)&&l(s.programDateTime)){const t=s.programDateTime+1e3*(e-s.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 Hls{static get version(){return"1.5.8"}static isMSESupported(){return hn()}static isSupported(){return function(){if(!hn())return!1;const t=Nt();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(Gt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(Gt(e,"audio"))))}()}static getMediaSource(){return Nt()}static get Events(){return c}static get ErrorTypes(){return u}static get ErrorDetails(){return f}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:sn}static set DefaultConfig(t){Hls.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 _r,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){y(t,"debug","log","info","warn","error");try{p.log(`Debug logs enabled for "${e}" in hls.js version 1.5.8`)}catch(t){p=m}}else p=m}(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 s=rn(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const i=`${"level"===t?"playlist":t}LoadPolicy`,n=void 0===e[i],a=[];r.forEach(r=>{const o=`${t}Loading${r}`,l=e[o];if(void 0!==l&&n){a.push(o);const t=s[i].default;switch(e[i]={default:t},r){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}}),a.length&&v.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${i}": ${JSON.stringify(e[i])}`)}),i(i({},s),e)}(Hls.DefaultConfig,t);this.userConfig=t,e.progressive&&nn(e);const{abrController:s,bufferController:r,capLevelController:n,errorController:a,fpsController:o}=e,l=new a(this),h=this.abrController=new s(this),d=this.bufferController=new r(this),u=this.capLevelController=new n(this),f=new o(this),g=new PlaylistLoader(this),E=new ID3TrackController(this),T=e.contentSteeringController,S=T?new T(this):null,L=this.levelController=new LevelController(this,S),A=new FragmentTracker(this),R=new KeyLoader(this.config),b=this.streamController=new StreamController(this,A,R);u.setStreamController(b),f.setStreamController(b);const k=[g,L,b];S&&k.splice(1,0,S),this.networkControllers=k;const D=[h,d,u,f,E,A];this.audioTrackController=this.createController(e.audioTrackController,k);const C=e.audioStreamController;C&&k.push(new C(this,A,R)),this.subtitleTrackController=this.createController(e.subtitleTrackController,k);const P=e.subtitleStreamController;P&&k.push(new P(this,A,R)),this.createController(e.timelineController,D),R.emeController=this.emeController=this.createController(e.emeController,D),this.cmcdController=this.createController(e.cmcdController,D),this.latencyController=this.createController(LatencyController,D),this.coreComponents=D,k.push(l);const w=l.onErrorOut;"function"==typeof w&&this.on(c.ERROR,w,l)}createController(t,e){if(t){const s=new t(this);return e&&e.push(s),s}return null}on(t,e,s=this){this._emitter.on(t,e,s)}once(t,e,s=this){this._emitter.once(t,e,s)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,s=this,r){this._emitter.off(t,e,s,r)}listeners(t){return this._emitter.listeners(t)}emit(t,e,s){return this._emitter.emit(t,e,s)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(v.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const s=t===c.ERROR;this.trigger(c.ERROR,{type:u.OTHER_ERROR,details:f.INTERNAL_EXCEPTION,fatal:s,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){v.log("destroy"),this.trigger(c.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){v.log("attachMedia"),this._media=t,this.trigger(c.MEDIA_ATTACHING,{media:t})}detachMedia(){v.log("detachMedia"),this.trigger(c.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const e=this.media,r=this.url,i=this.url=s.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,v.log(`loadSource:${i}`),e&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(c.MANIFEST_LOADING,{url:t})}startLoad(t=-1){v.log(`startLoad(${t})`),this.started=!0,this.networkControllers.forEach(e=>{e.startLoad(t)})}stopLoad(){v.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(){v.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){v.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){v.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){v.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){v.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){v.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){v.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&&(v.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return Ce.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 s=t.length;for(let r=0;r<s;r++)if(t[r].maxBitrate>=e)return r;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:s}=this;let r;if(r=-1===e&&null!=t&&t.length?t.length-1:e,s)for(let e=r;e--;){const r=t[e].attrs["HDCP-LEVEL"];if(r&&r<=s)return e}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}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}}Hls.defaultConfig=void 0;const dn="hls:attached",cn="hls:buffer_check";var un=Object.freeze({__proto__:null,ATTACHED:dn,BUFFER_CHECK_TICK:cn});function fn(t){const e=function(){const t="undefined"!=typeof document&&"undefined"!=typeof window,e=t?navigator.userAgent:"",s=/iP(hone|od)/i.test(e)&&!/iPad/.test(e)&&!/IEMobile/i.test(e),r=/Android/.test(e)&&!/Firefox/.test(e),i=/^((?!chrome|android).)*safari/i.test(e),n=/chrome|crios/i.test(e)&&!/opr|opera|chromium|edg|ucbrowser|googlebot/i.test(e),a=/firefox|fxios/i.test(e)&&!/seamonkey/i.test(e),o=/edg/i.test(e),l=/opr|opera/i.test(e),h=/SamsungBrowser/.test(e),d=h&&/SMART-TV/.test(e);return{controls:!s,video:function(e){return t&&document.createElement("video").canPlayType(e)},lang:t&&window.navigator.language,android:r,iphone:s,safari:i,edge:o,opera:l,chrome:n,firefox:a,ios:t&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,samsung:h,samsung_tv:h&&d,touch:"ontouchstart"in window,tizen:"tizen"in window,webOS:"webos"in window}}();switch(t){case"com.widevine.alpha":return e.chrome||e.firefox||e.edge||e.opera;case"org.w3.clearkey":return e.chrome||e.firefox;case"com.apple.fps.1_0":return e.safari;case"com.microsoft.playready":return e.edge}}const gn="application/vnd.apple.mpegURL",mn=[gn,"application/x-mpegurl"],pn=document.createElement("video").canPlayType(gn);function yn(t){const{pathname:e}=function(t){const e=document.createElement("a");return e.href=t,e}(t);return e.endsWith(".m3u8")}const vn=window&&window.Hls||Hls,En="viewenter",Tn="src",Sn="qualities",Ln="flowplayer:error";function An(t,e){const s=function(){try{return localStorage.getItem("flowplayer/debug")}catch(t){return""}}(),r=(r,...i)=>{try{const n=(null==e?void 0:e.debug)||s;n&&t.match(n)&&console.log(`flowplayer/${t} -- ${r}`,...i)}catch(t){console.warn(t)}};return r.log=r,r}var Rn;!function(t){t[t.FRAGMENT_ERRORS=0]="FRAGMENT_ERRORS",t[t.STALE_MANIFEST=1]="STALE_MANIFEST"}(Rn||(Rn={}));const bn=An("hls:failover");class FailoverLoaderController{constructor(){this.playlistCounts={},this.fragmentFailures={},this.ttlMilliseconds=3e3}setHls(t){this.hls=t}reset(){return this.playlistCounts={},this.fragmentFailures={},this}failover(t){var e,s;this.reset();const r=this.hls;if(!r)return;const i=r.levelController,n=r.streamController,a=i.steering;if(!i||!n||!a)return;const o=i.currentLevel;if(!o)return;const l=a.levels.filter(t=>t.pathwayId!==o.pathwayId);l.length&&(null===(e=r.media)||void 0===e||e.dispatchEvent(new CustomEvent("hls/failover",{detail:{reason:t,from:null===(s=o.details)||void 0===s?void 0:s.url}})),i._levels=n.levels=l)}currentLevel(){var t;return null===(t=this.hls)||void 0===t?void 0:t.levels[this.hls.currentLevel]}nextTTL(){var t;const e=Date.now()+this.ttlMilliseconds,s=this.currentLevel();if(!s)return e;const r=null===(t=s.details)||void 0===t?void 0:t.averagetargetduration;return r?Date.now()+500*r:e}ensurePlaylistUpdating(t,e){this.playlistCounts[t]||(this.playlistCounts[t]={checksum:e,count:0,ttl:this.nextTTL()});const s=this.playlistCounts[t];Date.now()<s.ttl||(s.count=s.checksum===e?s.count+1:0,s.ttl=this.nextTTL(),s.checksum=e,s.count<3||(bn(`${t} / no change in ${s.count} tries`,this.playlistCounts),this.failover(Rn.STALE_MANIFEST)))}trackFragmentError(t){const e=this.fragmentFailures[t]||0;this.fragmentFailures[t]=e+1,this.fragmentFailures[t]>2&&this.failover(Rn.FRAGMENT_ERRORS)}createPlaylistLoader(t){const e=this;return class extends Hls.DefaultConfig.loader{load(s,r,i){const n=i.onSuccess;i.onSuccess=({data:r,url:i},...a)=>{"manifest"===(null==s?void 0:s.type)&&(t.manifest=r),e.ensurePlaylistUpdating(i,r),n({data:r,url:i},...a)},super.load(s,r,i)}}}createFragmentLoader(){const t=this;return class extends Hls.DefaultConfig.loader{load(e,s,r){const i=r.onError;r.onError=e=>{t.trackFragmentError(e.url),i(...arguments)},super.load(e,s,r)}}}}const kn={Unknown:"00-00",MediaUnknown:"01-00",MediaUnavailable:"01-01",MediaUnsupportedVideoFormat:"01-02",MediaUnsupportedAudioFormat:"01-03",MediaBitrateExceeded:"01-04",MediaBufferOverread:"01-05",MediaIntegerOverflow:"01-06",MediaQuotaExceeded:"01-07",MediaInvalidCompositionDuration:"01-08",MediaInvalidCompositionSourceDuration:"01-09",MediaInvalidCompositionSourceStartTime:"01-10",MediaMalformedDepth:"01-11",PlaybackUnknown:"02-00",PlaybackVideoBufferUnderRun:"02-01",PlaybackAudioBufferUnderRun:"02-02",PlaybackVideoBufferingTimeout:"02-03",PlaybackAudioBufferingTimeout:"02-04",PlaybackManifestParseError:"02-05",PlaybackVideoDecodeError:"02-06",PlaybackAudioDecodeError:"02-07",PlaybackDroppedFramesExceeded:"02-08",PlaybackPlayheadExceedsDuration:"02-09",PlaybackUnsupportedDevice:"02-10",PlaybackManifestLoadError:"02-11",PlaybackManifestLoadTimeout:"02-12",PlaybackManifestParsingError:"02-13",PlaybackManifestIncompatibleCodecs:"02-14",PlaybackLevelEmptyError:"02-15",PlaybackLevelLoadError:"02-16",PlaybackLevelLoadTimeout:"02-17",PlaybackLevelSwitchError:"02-18",PlaybackAudioTrackLoadError:"02-19",PlaybackAudioTrackLoadTimeout:"02-20",PlaybackFragLoadError:"02-21",PlaybackFragLoadTimeout:"02-22",PlaybackFragDecryptError:"02-23",PlaybackFragParsingError:"02-24",PlaybackFragGap:"02-25",PlaybackRemuxAllocError:"02-26",PlaybackBufferAddCodecError:"02-27",PlaybackBufferIncompatibleCodecs:"02-28",PlaybackBufferAppendError:"02-29",PlaybackBufferStalledError:"02-30",PlaybackBufferFullError:"02-31",PlaybackBufferSeekOverHole:"02-32",PlaybackBufferNudgeOnStall:"02-33",PlaybackInternalException:"02-34",PlaybackInternalAborted:"02-35",PlaybackManifestLoaderFailure:"02-36",PlaybackSegmentBaseLoaderError:"02-37",PlaybackTimeSyncFailed:"02-38",PlaybackFragmentLoaderFailure:"02-39",PlaybackAppendError:"02-40",PlaybackRemoveError:"02-41",PlaybackDataUpdateFailed:"02-42",PlaybackManifestNoStreams:"02-43",PlaybackUnknownManifestType:"02-44",PlaybackDashInsufficientSegmentInfo:"02-45",PlaybackDashNoRepresentations:"02-46",PlaybackDashNoAdaptationSets:"02-47",PlaybackDashNoInitSegment:"02-48",PlaybackDashUnsupportedContainerFormat:"02-49",PlaybackDashKeySystemMismatch:"02-50",PlaybackMultipleKeyIDs:"02-51",PlaybackDashConflictingKeyIDs:"02-52",PlaybackRestrictedStreams:"02-53",PlaybackHlsMasterAndMediaTags:"02-54",PlaybackRepresentationIdConflict:"02-55",PlaybackHlsUnsupportedKeyFormats:"02-56",PlaybackManifestNoVariants:"02-57",PlaybackHlsUndeclaredVariables:"02-58",PlaybackAes128InvalidKeyLength:"02-59",PlaybackDashConflictingAes128Keys:"02-60",PlaybackDashUnsupportedAes128Encryption:"02-61",PlaybackManifestPatchMismatch:"02-62",PlaybackEmptyMediaPlaylist:"02-63",PlaybackNonContiguousCompositionTrack:"02-64",PlaybackDecoderNotFound:"02-65",PlaybackDecoderTemporarilyUnavailable:"02-66",PlaybackIncompatibleAsset:"02-67",PlaybackNoCompatibleExternalDisplay:"02-69",PlaybackOutOfMemory:"02-70",PlaybackToneMappingFailed:"02-71",PlaybackVideoCompositorFailed:"02-72",NetworkUnknown:"03-00",NetworkNoInternet:"03-01",NetworkRequestTimeout:"03-02",NetworkUnableToResolveHost:"03-03",NetworkResourceNotFound:"03-04",NetworkExpiredUrl:"03-05",NetworkUrlResolutionFailed:"03-06",NetworkDownloadErrorIdManifest:"03-07",NetworkDownloadErrorIdSidx:"03-08",NetworkDownloadErrorIdContent:"03-09",NetworkDownloadErrorIdInitialization:"03-10",NetworkDownloadErrorIdXlink:"03-11",NetworkHttpRequestFailed:"03-12",NetworkMaxRetriesExceeded:"03-13",NetworkSegmentMissing:"03-14",NetworkHttp400BadRequest:"03-400",NetworkHttp401Unauthorized:"03-401",NetworkHttp402PaymentRequired:"03-402",NetworkHttp403Forbidden:"03-403",NetworkHttp404NotFound:"03-404",NetworkHttp405MethodNotAllowed:"03-405",NetworkHttp406NotAcceptable:"03-406",NetworkHttp407ProxyAuthenticationRequired:"03-407",NetworkHttp408RequestTimeout:"03-408",NetworkHttp409Conflict:"03-409",NetworkHttp410Gone:"03-410",NetworkHttp411LengthRequired:"03-411",NetworkHttp412PreconditionFailed:"03-412",NetworkHttp413PayloadTooLarge:"03-413",NetworkHttp414URITooLong:"03-414",NetworkHttp415UnsupportedMediaType:"03-415",NetworkHttp416RangeNotSatisfiable:"03-416",NetworkHttp417ExpectationFailed:"03-417",NetworkHttp418ImATeapot:"03-418",NetworkHttp421MisdirectedRequest:"03-421",NetworkHttp422UnprocessableEntity:"03-422",NetworkHttp423Locked:"03-423",NetworkHttp424FailedDependency:"03-424",NetworkHttp425TooEarly:"03-425",NetworkHttp426UpgradeRequired:"03-426",NetworkHttp428PreconditionRequired:"03-428",NetworkHttp429TooManyRequests:"03-429",NetworkHttp431RequestHeaderFieldsTooLarge:"03-431",NetworkHttp451UnavailableForLegalReasons:"03-451",NetworkHttp500InternalServerError:"03-500",NetworkHttp501NotImplemented:"03-501",NetworkHttp502BadGateway:"03-502",NetworkHttp503ServiceUnavailable:"03-503",NetworkHttp504GatewayTimeout:"03-504",NetworkHttp505HTTPVersionNotSupported:"03-505",NetworkHttp506VariantAlsoNegotiates:"03-506",NetworkHttp507InsufficientStorage:"03-507",NetworkHttp508LoopDetected:"03-508",NetworkHttp510NotExtended:"03-510",NetworkHttp511NetworkAuthenticationRequired:"03-511",ContentProtectionUnknown:"04-00",ContentProtectionConcurrentStreamLimitExceeded:"04-01",ContentProtectionEntitlementRefused:"04-02",ContentProtectionLicenseExpired:"04-03",ContentProtectionBadLicenseRequest:"04-04",ContentProtectionLicenseServerTimeout:"04-05",ContentProtectionInsufficientHDCPSupport:"04-06",ContentProtectionGeoRestricted:"04-07",ContentProtectionParentalControlRestricted:"04-08",ContentProtectionCDNUnauthorized:"04-09",ContentProtectionInvalidAccessToken:"04-10",ContentProtectionKeySystemNoKeys:"04-11",ContentProtectionKeySystemNoAccess:"04-12",ContentProtectionKeySystemNoSession:"04-13",ContentProtectionKeySystemNoConfiguredLicense:"04-14",ContentProtectionKeySystemCertificateRequestFailed:"04-15",ContentProtectionKeySystemCertificateUpdateFailed:"04-16",ContentProtectionKeySystemSessionUpdateFailed:"04-17",ContentProtectionKeySystemStatusOutputRestricted:"04-18",ContentProtectionKeySystemStatusInternalError:"04-19",ContentProtectionKeyLoadError:"04-20",ContentProtectionKeyLoadTimeout:"04-21",ContentProtectionCapabilityMediaKeysError:"04-22",ContentProtectionManifestKeySystemUnknown:"04-23",ContentProtectionKeySystemUnavailable:"04-24",ContentProtectionCDMCreationFailed:"04-25",ContentProtectionCDMAttachFailed:"04-26",ContentProtectionCDMServerCertificateRejected:"04-27",ContentProtectionCDMSessionCreationFailed:"04-28",ContentProtectionCDMLicenseRequestFailed:"04-29",ContentProtectionCDMLicenseResponseRejected:"04-30",ContentProtectionManifestMissingDRMInfo:"04-31",ContentProtectionLicenseServerMissing:"04-32",ContentProtectionOfflineSessionRemoved:"04-33",ContentProtectionInitDataTransformationError:"04-34",ContentProtectionServerCertificateRequestFailed:"04-35",ContentProtectionInsufficientHDCPVersion:"04-36",ContentProtectionHDCPVersionCheckFailed:"04-37",AdsUnknown:"08-00",AdsVastParseError:"08-100",AdsInvalidVastSchema:"08-101",AdsVastVersionNotSupported:"08-102",AdsUnexpectedAdType:"08-200",AdsCreativeLinearityMismatch:"08-201",AdsCreativeDurationMismatch:"08-202",AdsCreativeSizeMismatch:"08-203",AdsWrapperVastError:"08-300",AdsVastResponseRedirectTimeout:"08-301",AdsWrapperLimitReached:"08-302",AdsVastResponseEmpty:"08-303",AdsLinearAdDisplayError:"08-400",AdsMediaFileNotFound:"08-401",AdsMediaFileUnavailable:"08-402",AdsUnsupportedMimeType:"08-403",AdsUnableToDisplayMediaFile:"08-405",AdsMezzanineFileMissing:"08-406",AdsMezzanineFileDownloaded:"08-407",AdsRejectedAd:"08-408",AdsInteractiveCreativeError:"08-409",AdsVerificationNodeExecutionError:"08-410",AdsNonLinearAdDisplayError:"08-500",AdsNonLinearAdSizeMismatch:"08-501",AdsNonLinearAdFetchError:"08-502",AdsNonLinearUnsupportedType:"08-503",AdsCompanionAdDisplayError:"08-600",AdsCompanionAdSizeMismatch:"08-601",AdsRequiredCompanionAdError:"08-602",AdsCompanionAdFetchError:"08-603",AdsUndefinedVastError:"08-900",AdsUnknownVpaidError:"08-901",AdsVastDocumentEmpty:"08-999"},Dn=Object.fromEntries(Object.entries(kn).map(([t,e])=>[e,t])),Cn=[1e7]+""+-1e3+-4e3+-8e3+-1e11,Pn="on",wn="off";class FlowplayerError extends Error{static getErrorKey(t){return t in Dn?Dn[t]:Dn["00-00"]}constructor(t,e,s={}){super(t),this.message=t,this.flowplayerErrorCode=e,this.config=s,this.id="undefined"==typeof crypto?"":Cn.replace(/[018]/g,t=>(t^crypto.getRandomValues(new Uint8Array(1))[0]&15>>t/4).toString(16)),this.isFatal=!!s.isFatal,this.errorKey=FlowplayerError.getErrorKey(this.flowplayerErrorCode)||"unknown"}toJSON(){return{message:this.message,flowplayer_error_code:this.flowplayerErrorCode,id:this.id,root_error_id:this.config.rootErrorId,resource:this.config.resource,is_fatal:this.isFatal,is_retry:!!this.config.isRetry}}}const In="audio:tracks";const _n="tracks:text:all";const Mn="is-loaded",xn="is-loading",Fn="is-waiting",On="is-in-viewport",Nn=An("hls");function Un(t){switch(t){case f.KEY_SYSTEM_NO_KEYS:return kn.ContentProtectionKeySystemNoKeys;case f.KEY_SYSTEM_NO_ACCESS:return kn.ContentProtectionKeySystemNoAccess;case f.KEY_SYSTEM_NO_SESSION:return kn.ContentProtectionKeySystemNoSession;case f.KEY_SYSTEM_NO_CONFIGURED_LICENSE:return kn.ContentProtectionKeySystemNoConfiguredLicense;case f.KEY_SYSTEM_LICENSE_REQUEST_FAILED:return kn.ContentProtectionCDMLicenseRequestFailed;case f.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED:return kn.ContentProtectionServerCertificateRequestFailed;case f.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED:return kn.ContentProtectionKeySystemCertificateUpdateFailed;case f.KEY_SYSTEM_SESSION_UPDATE_FAILED:return kn.ContentProtectionKeySystemSessionUpdateFailed;case f.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return kn.ContentProtectionKeySystemStatusOutputRestricted;case f.KEY_SYSTEM_STATUS_INTERNAL_ERROR:return kn.ContentProtectionKeySystemStatusInternalError;case f.MANIFEST_LOAD_ERROR:return kn.PlaybackManifestLoadError;case f.MANIFEST_LOAD_TIMEOUT:return kn.PlaybackManifestLoadTimeout;case f.MANIFEST_PARSING_ERROR:return kn.PlaybackManifestParsingError;case f.MANIFEST_INCOMPATIBLE_CODECS_ERROR:return kn.PlaybackManifestIncompatibleCodecs;case f.LEVEL_EMPTY_ERROR:return kn.PlaybackLevelEmptyError;case f.LEVEL_LOAD_ERROR:return kn.PlaybackLevelLoadError;case f.LEVEL_LOAD_TIMEOUT:return kn.PlaybackLevelLoadTimeout;case f.LEVEL_PARSING_ERROR:return kn.PlaybackManifestParsingError;case f.LEVEL_SWITCH_ERROR:return kn.PlaybackLevelSwitchError;case f.AUDIO_TRACK_LOAD_ERROR:return kn.PlaybackAudioTrackLoadError;case f.AUDIO_TRACK_LOAD_TIMEOUT:return kn.PlaybackAudioTrackLoadTimeout;case f.SUBTITLE_LOAD_ERROR:return kn.NetworkDownloadErrorIdContent;case f.SUBTITLE_TRACK_LOAD_TIMEOUT:return kn.NetworkRequestTimeout;case f.FRAG_LOAD_ERROR:return kn.PlaybackFragLoadError;case f.FRAG_LOAD_TIMEOUT:return kn.PlaybackFragLoadTimeout;case f.FRAG_DECRYPT_ERROR:return kn.PlaybackFragDecryptError;case f.FRAG_PARSING_ERROR:return kn.PlaybackFragParsingError;case f.FRAG_GAP:return kn.PlaybackFragGap;case f.REMUX_ALLOC_ERROR:return kn.PlaybackRemuxAllocError;case f.KEY_LOAD_ERROR:return kn.ContentProtectionKeyLoadError;case f.KEY_LOAD_TIMEOUT:return kn.ContentProtectionKeyLoadTimeout;case f.BUFFER_ADD_CODEC_ERROR:return kn.PlaybackBufferAddCodecError;case f.BUFFER_INCOMPATIBLE_CODECS_ERROR:return kn.PlaybackBufferIncompatibleCodecs;case f.BUFFER_APPEND_ERROR:return kn.PlaybackBufferAppendError;case f.BUFFER_APPENDING_ERROR:return kn.PlaybackAppendError;case f.BUFFER_STALLED_ERROR:return kn.PlaybackBufferStalledError;case f.BUFFER_FULL_ERROR:return kn.PlaybackBufferFullError;case f.BUFFER_SEEK_OVER_HOLE:return kn.PlaybackBufferSeekOverHole;case f.BUFFER_NUDGE_ON_STALL:return kn.PlaybackBufferNudgeOnStall;case f.INTERNAL_EXCEPTION:return kn.PlaybackInternalException;case f.INTERNAL_ABORTED:return kn.PlaybackInternalAborted;case f.UNKNOWN:default:return kn.Unknown}}function Bn(t,e,s){const r={},i={error_type:e.type,resource:e.url||t.original_src,isFatal:e.fatal};return e.fatal?(e.type===s.ErrorTypes.MEDIA_ERROR&&(i.showErrorUI=!1,r.retry=Pn,r.retryTimeout=0),[s.ErrorTypes.KEY_SYSTEM_ERROR,s.ErrorTypes.MUX_ERROR,s.ErrorTypes.OTHER_ERROR].includes(e.type)&&(r.retry=wn),Object.assign(i,{retryOpts:r})):(r.retry=wn,Object.assign(i,{retryOpts:r}))}function $n(t,e){e.on(vn.Events.ERROR,function(e,s){var r;0!=t.reaper&&(!function(t,e,s){t.emit(Ln,{error:new FlowplayerError(e.error.message,Un(e.details),Bn(t,e,s))})}(t,s,vn),s.fatal&&([vn.ErrorTypes.NETWORK_ERROR,vn.ErrorTypes.MEDIA_ERROR].includes(s.type)||null===(r=t.hls)||void 0===r||r.destroy()))})}const Gn="is-chromecast-playing";function Kn(t,e){const s=t.seekable;if("object"!=typeof t.opts||0==s.length)return{head:0,tail:0};const r=function(t){var e;const s=t.seekable;return s.length?t.hasState(Gn)||!(null===(e=t.hls)||void 0===e?void 0:e.liveSyncPosition)?s.end(s.length-1):t.hls.liveSyncPosition:0}(t),i=e||t.live_state.dvr_window;return{head:r,tail:"number"!=typeof i||r-i<0?s.start(0):r-i}}function Hn(t,e){var s;!t.hasState(Mn)&&t.setState(xn,!0),null===(s=t.hls)||void 0===s||s.startLoad(e)}function Vn(t){t.on("remotesession:started",()=>{t.hls&&(t.hls.stopLoad(),delete t.opts.start_time)}),t.on("remotesession:ended",e=>{var s;if(!t.hls)return;if(!t.opts.live)return Hn(t,e.detail.currentTime);e.preventDefault();const r=function(t){const e=t.currentTime,s=Kn(t);return{progress:Math.min(100,Math.max(0,(e-s.tail)/(s.head-s.tail)*100)),is_live:e-s.head>=-10}}(t).progress,i=t.hls;null===(s=t.hls)||void 0===s||s.once(vn.Events.LEVEL_LOADED,()=>{if(t.hls!==i)return;const e=t.live_state.dvr_window||0,s=(null==i?void 0:i.liveSyncPosition)||t.seekable.end(0);if(t.hasState("no-timeline")||isNaN(r))return t.currentTime=s;t.currentTime=s-e*((100-r)/100)}),Hn(t)})}var Yn;function Wn(t,e){if("object"==typeof t&&"object"==typeof e&&"number"==typeof t.bitrate&&"number"==typeof e.bitrate)return t.bitrate<e.bitrate}function jn(t){const e=t.map((t,e)=>Object.assign(t,{level:e})).sort((t,e)=>e.width-t.width);return t.length>1&&t.every(t=>void 0!==t.bitrate)&&e.push({name:"AUTO",level:-1,width:0,height:0}),e}function qn(t,e,s,r,i){let n;t.once(Hls.Events.LEVEL_LOADING,function(){e.emit("content:loadstart")}),t.on(vn.Events.MANIFEST_PARSED,function(t,n){const a=jn(n.levels);e.emit(Sn,a),e.emit("parse:video:tracks",{url:i.src,manifest:r.manifest}),function(t,e,s){if(!t.hls)return;Nn("Initializer::maybe_start_load_with_quality (start_quality, preload): (%d, %s)",e.start_quality,e.preload),void 0!==e.start_quality&&s.length&&(Yn.HIGH&e.start_quality&&(t.hls.startLevel=s[0].level),Yn.LOW&e.start_quality&&(t.hls.startLevel=s[s.length-1].level),Yn.MEDIUM&e.start_quality&&(t.hls.startLevel=s[Math.ceil(s.length/2)-1].level));(function(t,e){var s,r,i,n,a,o;if(!e.hls)return;if(null===(s=t.hls)||void 0===s?void 0:s.adaptive_buffer_control){const s=10,r=10,i=!0!==t.hls.adaptive_buffer_control&&t.hls.adaptive_buffer_control.initial_buffer_length?t.hls.adaptive_buffer_control.initial_buffer_length:s;!function(t,e){var s;const r=500,i=null===(s=t.hls)||void 0===s?void 0:s.config.maxBufferLength;let n=!1;const a=setInterval(()=>{t.emit(cn)},r),o=()=>{n||t.currentTime>e&&(n=!0,t.hls&&i&&(t.hls.config.maxBufferLength=i))};t.on(Tn,()=>{clearInterval(a),t.off(cn,o)}),t.on(cn,o)}(e,!0!==(null===(n=t.hls)||void 0===n?void 0:n.adaptive_buffer_control)&&t.hls.adaptive_buffer_control.restore_buffer_player_time_threshold?null===(a=t.hls)||void 0===a?void 0:a.adaptive_buffer_control.restore_buffer_player_time_threshold:r),Xn(t,e,{maxBufferLength:i,maxBufferSize:null===(o=t.hls)||void 0===o?void 0:o.maxBufferSize})}else Xn(t,e,{maxBufferLength:null===(r=t.hls)||void 0===r?void 0:r.maxBufferLength,maxBufferSize:null===(i=t.hls)||void 0===i?void 0:i.maxBufferSize})})(e,t),("none"!==e.preload||e.autoplay&&t.hasState(On))&&!t.hls.config.autoStartLoad&&Hn(t,e.start_time||-1)}(e,s,a.slice(0,-1))}),t.on(vn.Events.LEVEL_SWITCHING,(s,r)=>{if(t.nextLoadLevel===n)return;n=t.nextLoadLevel;const i=t.levels[t.currentLevel],a=t.levels[r.level];e.emit("qualitychange",{before:i,after:a,plugin:"hls",automatic:t.autoLevelEnabled,downscale:Wn(a,i)})})}function Xn(t,e,s){if(!e.hls)return;const r=(null==s?void 0:s.maxBufferSize)||1024,i=(null==s?void 0:s.maxBufferLength)||30;Nn("Setting maxBufferSize to %d",r),e.hls.config.maxBufferSize=r,"metadata"===t.preload&&Nn("preload === metadata, setting maxBufferLength to 1sec"),e.hls.config.maxBufferLength="metadata"===t.preload?1:i,e.once("playing",()=>{Nn("Playback started, set maxBufferLenght to %d",i),e.hls&&(e.hls.config.maxBufferLength=i)})}!function(t){t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=4]="HIGH"}(Yn||(Yn={}));function zn(t,e,s,r,i){!function(t,e){t.on(Hls.Events.AUDIO_TRACKS_UPDATED,function(t,s){e.emit(In,s.audioTracks)}),t.on(Hls.Events.AUDIO_TRACK_SWITCHING,function(t,s){e.emit("audio:update",s)}),t.on(Hls.Events.MANIFEST_PARSED,function(t,s){s.audioTracks&&e.emit(In,s.audioTracks)})}(t,r),function(t,e){t.on(Hls.Events.NON_NATIVE_TEXT_TRACKS_FOUND,(s,r)=>{t.subtitleTracks.length||e.emit(_n,r)}),t.on(Hls.Events.SUBTITLE_TRACKS_UPDATED,(t,s)=>{e.emit(_n,{tracks:s.subtitleTracks.map(t=>Object.assign({},{subtitleTrack:t}))})}),t.on(Hls.Events.CUES_PARSED,(t,s)=>{e.emit("cues:parsed",s)})}(t,r),$n(r,t),qn(t,r,e,s,i),function(t,e){t.on(Hls.Events.FRAG_PARSING_METADATA,function(t,s){e.emit("ssai:hls:metadata",s)})}(t,r),function(t,e){t.on(Hls.Events.BUFFER_CREATED,(t,s)=>{const r=s.tracks.video||s.tracks.audiovideo;if(!r)return e.emit("audioonlysource");const i=null==r?void 0:r.metadata.height,n=null==r?void 0:r.metadata.width;!e.opt("ratio")&&i&&n&&e.setOpts({ratio:n+":"+i})})}(t,r),function(t,e,s){const r="live"in s==0;e.on(vn.Events.LEVEL_LOADED,function(s,i){var n,a,o,l,h;r&&t.setOpts({live:null===(n=null==i?void 0:i.details)||void 0===n?void 0:n.live});const d=null===(o=null===(a=e.levels[i.level])||void 0===a?void 0:a.details)||void 0===o?void 0:o.fragments;if(!d)return;const c=(null===(l=d[1])||void 0===l?void 0:l.start)||0,u=e.liveSyncPosition||(null===(h=d[d.length-1])||void 0===h?void 0:h.end)||0;t.emit("dvr/window",u-c)})}(r,t,e)}function Qn(t,e,s){!function(t){t.on("audio:set",function(e){var s,r;const i=null===(s=e.data)||void 0===s?void 0:s.id;"number"==typeof i&&i!=(null===(r=null==t?void 0:t.hls)||void 0===r?void 0:r.audioTrack)&&setTimeout(function(){(null==t?void 0:t.hls)&&(t.hls.audioTrack=i)},0)})}(t),function(t,e){t.on("src",function(){t.hls&&(t.hls.destroy(),delete t.hls,e.manifest=void 0)}),t.on("reap",function(){var e;null===(e=t.hls)||void 0===e||e.destroy()})}(t,e),function(t){const e={media_recovers:0,audio_swaps:0};let s=0;t.on("error",e=>{var r,i,n;t.hls&&(null===(r=null==t?void 0:t.error)||void 0===r?void 0:r.code)===MediaError.MEDIA_ERR_DECODE&&(e.preventDefault(),++s,t.emit(Ln,{error:new FlowplayerError(null!==(n=null===(i=null==t?void 0:t.error)||void 0===i?void 0:i.message)&&void 0!==n?n:"An error occurred while decoding the media.",kn.PlaybackVideoDecodeError,{isFatal:!0,showErrorUI:s>=5,retryOpts:{retry:s<5?Pn:wn,retryTimeout:0}})}))}),t.on("canplay",()=>s=0),t.on("retry",s=>{var r,i,n,a;if(!t.hls)return;s.preventDefault();const o=s.detail.error,l=o.config;return o.flowplayerErrorCode===kn.PlaybackVideoDecodeError?(t.hls.config.autoStartLoad=!0,t.hls.recoverMediaError(),t.setState(Fn,!1)):l.error_type?l.error_type===vn.ErrorTypes.NETWORK_ERROR?(t.hls.config.autoStartLoad=!0,(null===(r=t.normalizedSrc)||void 0===r?void 0:r.src)&&t.hls.loadSource(t.original_src),!t.paused||t.hasState("is-playing")?(t.setState(Fn,!0),t.togglePlay(!0)):(t.setState(Fn,!1),t.emit("retry/done"))):l.error_type===vn.ErrorTypes.MEDIA_ERROR?(Nn(`recovering from ${l.error_type}`),e.media_recovers+5e3>Date.now()&&0==e.audio_swaps?(null===(i=t.hls)||void 0===i||i.swapAudioCodec(),Nn(`calling swapAudioCodec() : {count=${e.audio_swaps}}`),e.audio_swaps++,e.media_recovers=Date.now(),null===(n=t.hls)||void 0===n||n.recoverMediaError(),t.setState(Fn,!1)):(e.media_recovers=Date.now(),e.audio_swaps=0,null===(a=t.hls)||void 0===a||a.recoverMediaError(),t.setState(Fn,!1))):void 0:void 0})}(t),Vn(t),function(t,e){t.on(["beforeplay",En],s=>{if(!(!t.hls||t.hls.config.autoStartLoad||t.hasState("is-casting")||t.hasState(Mn)||"none"!==e.preload||s.type===En&&!e.autoplay))return t.hls.levels.length?Hn(t,e.start_time||-1):void t.hls.once(vn.Events.MANIFEST_PARSED,()=>{setTimeout(()=>{Hn(t,e.start_time||-1)},0)})}),t.on("quality:set",function(e){var s;if(!t.hls)return;const r=null===(s=e.data)||void 0===s?void 0:s.level;"number"==typeof r&&(t.hls.levels[r]||-1===r?t.hls.nextLevel=r:console.error(new Error("skipping invalid quality: "+e.data)))}),t.on("tracks:video:select",function(e){var s,r;const i=e.detail.track,n=null===(s=t.tracks)||void 0===s?void 0:s.find(t=>t.selected&&t!==i),a=t.hls;if(!n||!i||!a)return;n.selected=!1;const o=null===(r=i.data)||void 0===r?void 0:r.slice(0).map(t=>(t.details=void 0,t));a.stopLoad(),a.levelController._levels=a.streamController.levels=o,a.currentLevel=-1,t.emit(Sn,jn(o)),t.hasState("is-starting")&&!t.hasState(xn)||a.startLoad()});const s=t.opt("start_time");s&&t.once("loadedmetadata",function(){t.currentTime=s})}(t,s)}function Jn(t,e){if(t.drm&&"https:"!==location.protocol&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname){const s=new FlowplayerError("drm is unavailable in http contexts",kn.ContentProtectionKeySystemUnavailable,{resource:t.src,isFatal:!0,retryOpts:{retry:wn}});return e.emit(Ln,{error:s}),!1}return!0}function Zn(t,e,s,r){if(!t.reaper||!(null==s?void 0:s.src))return;if(t.hls&&t.hls.destroy(),!Jn(s,t))return;const i=function(t,e,s,r){var i,n,a,o,l,h,d,c;const u=new FailoverLoaderController,f=function(t){return Object.assign(Object.assign({autoStartLoad:!1,levelLoadingMaxRetry:1},t.hls),{startPosition:t.start_time||-1})}(t);f.renderTextTracksNatively=!1,f.captionsTextTrack1Label=null!==(n=null===(i=null==t?void 0:t.hls)||void 0===i?void 0:i.captionsTextTrack1Label)&&void 0!==n?n:"CC1",f.captionsTextTrack2Label=null!==(o=null===(a=null==t?void 0:t.hls)||void 0===a?void 0:a.captionsTextTrack2Label)&&void 0!==o?o:"CC2",f.captionsTextTrack3Label=null!==(h=null===(l=null==t?void 0:t.hls)||void 0===l?void 0:l.captionsTextTrack3Label)&&void 0!==h?h:"CC3",f.captionsTextTrack4Label=null!==(c=null===(d=null==t?void 0:t.hls)||void 0===d?void 0:d.captionsTextTrack4Label)&&void 0!==c?c:"CC4",f.pLoader=u.createPlaylistLoader(e),f.fLoader=u.createFragmentLoader();const g=s.hls=new vn(f);return u.setHls(g),g.subtitleDisplay=!1,g.attachMedia(s),g.loadSource(r.src),setTimeout(()=>s.emit(dn,{hls:s.hls})),g}(e,r,t,s);zn(i,e,r,t,s)}var ta;const ea=((ta=class HLS{init(t,e,s){Qn(s,this,t)}onload(t,e,s,r){s.normalizedSrc=r,Zn(s,t,r,this)}wants(t,e,s){return Hls.isSupported()&&function({src:t="",type:e="",drm:s},r){const i=null==r?void 0:r.hls,n=Boolean(null==i?void 0:i.native);return(!pn||!n)&&!(s&&!Object.keys(s).find(t=>fn(t)))&&(!(!e||!mn.includes(e))||yn(t))}(e,s)}}).pluginName="hls",ta.events=un,ta.version=Hls.version,ta.failover={Reasons:Rn},ta);return function(t,e){if("object"==typeof exports&&"undefined"!=typeof module)return e;if(null===document.currentScript)return e;"flowplayer"in t||(t.flowplayer={extensions:[]});const s=t.flowplayer;return"function"==typeof s?(s(e),e):(Array.isArray(s.extensions)||(s.extensions=[]),~s.extensions.indexOf(e)||s.extensions.push(e),e)}(window,ea)});
|