@flowplayer/player 3.8.1 → 3.9.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/flowplayer.css +1 -1
- package/package.json +1 -1
- package/plugins/ads.js +2 -2
- package/plugins/analytics.js +1 -1
- package/plugins/dash.js +4 -4
- package/plugins/drm.js +1 -1
- package/plugins/health.js +1 -1
- package/plugins/hls.js +1 -1
- package/plugins/ovp.js +1 -1
- package/plugins/preview.js +1 -1
- package/plugins/qul.js +1 -1
- package/plugins/subtitles.js +1 -1
- package/plugins/tizen.js +1 -1
- package/plugins/webos.js +1 -1
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";var t={};function e(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 s(t){for(var s=1;s<arguments.length;s++){var i=null!=arguments[s]?arguments[s]:{};s%2?e(Object(i),!0).forEach((function(e){r(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function r(t,e,s){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===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)}(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function i(){return(i=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)}!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}({get exports(){return t},set exports(e){t=e}});const n=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)};let a=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.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}({}),o=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}({}),l=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 h=function(){},d={trace:h,debug:h,log:h,warn:h,info:h,error:h};let c=d;function u(t,...e){e.forEach((function(e){c[e]=t[e]?t[e].bind(t):function(t){const e=self.console[t];return e?e.bind(self.console,`[${t}] >`):h}(e)}))}const f=c,g=/^(\d+)x(\d+)$/,m=/(.+?)=(".*?"|.*?)(?:,|$)/g;class AttrList{constructor(t){"string"==typeof t&&(t=AttrList.parseAttrList(t));for(const e in t)t.hasOwnProperty(e)&&("X-"===e.substring(0,2)&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(e)),this[e]=t[e])}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=g.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(m.lastIndex=0;null!==(e=m.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 p(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]){f.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=i(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"]);n(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(n(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&&n(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 y="audio",T="video",E="audiovideo";class BaseSegment{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[y]:null,[T]:null,[E]:null},this.baseurl=t}setByteRange(t,e){const s=t.split("@",2),r=[];1===s.length?r[0]=e?e.byteRangeEndOffset:0:r[0]=parseInt(s[1]),r[1]=parseInt(s[0])+r[0],this._byteRange=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=t.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.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 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(!n(this.programDateTime))return null;const t=n(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[y]=null,t[T]=null,t[E]=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.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&&n(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 v(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function S(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=v(i)):s=function(t){const e=L(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(i)}}return s}function L(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}var A={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},R="org.w3.clearkey",b="com.apple.streamingkeydelivery",D="com.microsoft.playready",k="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function I(t){switch(t){case b:return A.FAIRPLAY;case D:return A.PLAYREADY;case k:return A.WIDEVINE;case R:return A.CLEARKEY}}var C="edef8ba979d64acea3c827dcd51d21ed";function w(t){switch(t){case A.FAIRPLAY:return b;case A.PLAYREADY:return D;case A.WIDEVINE:return k;case A.CLEARKEY:return R}}function _(t){const{drmSystems:e,widevineLicenseUrl:s}=t,r=e?[A.FAIRPLAY,A.WIDEVINE,A.PLAYREADY,A.CLEARKEY].filter(t=>!!e[t]):[];return!r[A.WIDEVINE]&&s&&r.push(A.WIDEVINE),r}const P="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function M(t,e,s){return Uint8Array.prototype.slice?t.slice(e,s):new Uint8Array(Array.prototype.slice.call(t,e,s))}const x=(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,F=(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,O=(t,e)=>{const s=e;let r=0;for(;x(t,e);){r+=10;r+=N(t,e+6),F(t,e+10)&&(r+=10),e+=r}if(r>0)return t.subarray(s,s+r)},N=(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},U=(t,e)=>x(t,e)&&N(t,e+6)+10<=t.length-e,B=t=>t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,$=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=N(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}},G=t=>{let e=0;const s=[];for(;x(t,e);){const r=N(t,e+6);e+=10;const i=e+r;for(;e+8<i;){const r=$(t.subarray(e)),i=K(r);i&&s.push(i),e+=r.size+10}F(t,e)&&(e+=10)}return s},K=t=>"PRIV"===t.type?H(t):"W"===t.type[0]?Y(t):V(t),H=t=>{if(t.size<2)return;const e=q(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}},V=t=>{if(t.size<2)return;if("TXXX"===t.type){let e=1;const s=q(t.data.subarray(e),!0);e+=s.length+1;const r=q(t.data.subarray(e));return{key:t.type,info:s,data:r}}const e=q(t.data.subarray(1));return{key:t.type,data:e}},Y=t=>{if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=q(t.data.subarray(e),!0);e+=s.length+1;const r=q(t.data.subarray(e));return{key:t.type,info:s,data:r}}const e=q(t.data);return{key:t.type,data:e}},W=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)}},q=(t,e=!1)=>{const s=X();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 j;function X(){return j||void 0===self.TextDecoder||(j=new self.TextDecoder("utf-8")),j}const z=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},Q=Math.pow(2,32)-1,J=[].push,Z={video:1,audio:2,id3:3,text:4};function tt(t){return String.fromCharCode.apply(null,t)}function et(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function st(t,e){const s=rt(t,e);return s<0?4294967296+s:s}function rt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function it(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 nt(t,e){const s=[];if(!e.length)return s;const r=t.byteLength;for(let i=0;i<r;){const n=st(t,i),a=n>1?i+n:r;if(tt(t.subarray(i+4,i+8))===e[0])if(1===e.length)s.push(t.subarray(i+8,a));else{const r=nt(t.subarray(i+8,a),e.slice(1));r.length&&J.apply(s,r)}i=a}return s}function at(t){const e=[],s=t[0];let r=8;const i=st(t,r);r+=4;r+=0===s?8:16,r+=2;let n=t.length+0;const a=et(t,r);r+=2;for(let s=0;s<a;s++){let s=r;const a=st(t,s);s+=4;const o=2147483647&a;if(1===(2147483648&a)>>>31)return f.warn("SIDX has hierarchical references (not supported)"),null;const l=st(t,s);s+=4,e.push({referenceSize:o,subsegmentDuration:l,info:{duration:l/i,start:n,end:n+o-1}}),n+=o,s+=4,r=s}return{earliestPresentationTime:0,timescale:i,version:s,referencesCount:a,references:e}}function ot(t){const e=[],s=nt(t,["moov","trak"]);for(let t=0;t<s.length;t++){const r=s[t],i=nt(r,["tkhd"])[0];if(i){let t=i[0],s=0===t?12:20;const n=st(i,s),a=nt(r,["mdia","mdhd"])[0];if(a){t=a[0],s=0===t?12:20;const i=st(a,s),o=nt(r,["mdia","hdlr"])[0];if(o){const t=tt(o.subarray(8,12)),s={soun:y,vide:T}[t];if(s){const t=nt(r,["mdia","minf","stbl","stsd"])[0];let a;t&&(a=tt(t.subarray(12,16))),e[n]={timescale:i,type:s},e[s]={timescale:i,id:n,codec:a}}}}}}return nt(t,["moov","mvex","trex"]).forEach(t=>{const s=st(t,4),r=e[s];r&&(r.default={duration:st(t,12),flags:st(t,20)})}),e}function lt(t){const e=nt(t,["schm"])[0];if(e){const s=tt(e.subarray(4,8));if("cbcs"===s||"cenc"===s)return nt(t,["schi","tenc"])[0]}return f.error("[eme] missing 'schm' box"),null}function ht(t){const e=st(t,0);let s=8;1&e&&(s+=4),4&e&&(s+=4);let r=0;const i=st(t,4);for(let n=0;n<i;n++){if(256&e){r+=st(t,s),s+=4}512&e&&(s+=4),1024&e&&(s+=4),2048&e&&(s+=4)}return r}function dt(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}function ct(t,e){const s=[],r=e.samples,i=e.timescale,n=e.id;let a=!1;return nt(r,["moof"]).map(o=>{const l=o.byteOffset-8;nt(o,["traf"]).map(o=>{const h=nt(o,["tfdt"]).map(t=>{const e=t[0];let s=st(t,4);return 1===e&&(s*=Math.pow(2,32),s+=st(t,8)),s/i})[0];return void 0!==h&&(t=h),nt(o,["tfhd"]).map(h=>{const d=st(h,4),c=16777215&st(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=st(h,p),p+=4),f&&(g=st(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)),nt(o,["trun"]).map(n=>{const o=n[0],h=16777215&st(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 E=0;const v=0!=(1024&h),S=0!=(2048&h);let L=0;const A=st(n,4);let R=8;d&&(c=st(n,R),R+=4),f&&(R+=4);let b=c+l;for(let l=0;l<A;l++){if(m?(p=st(n,R),R+=4):p=u,y?(E=st(n,R),R+=4):E=g,v&&(R+=4),S&&(L=0===o?st(n,R):rt(n,R),R+=4),e.type===T){let e=0;for(;e<E;){const n=st(r,b);if(b+=4,ut(a,r[b])){ft(r.subarray(b,b+n),a?2:1,t+L/i,s)}b+=n,e+=n+4}}t+=p/i}}))})})}),s}function ut(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function ft(t,e,s,r){const i=gt(t);let n=0;n+=e;let a=0,o=0,l=!1,h=0;for(;n<i.length;){a=0;do{if(n>=i.length)break;h=i[n++],a+=h}while(255===h);o=0;do{if(n>=i.length)break;h=i[n++],o+=h}while(255===h);const t=i.length-n;if(!l&&4===a&&n<i.length){l=!0;if(181===i[n++]){const t=et(i,n);if(n+=2,49===t){const t=st(i,n);if(n+=4,1195456820===t){const t=i[n++];if(3===t){const e=i[n++],o=31&e,l=64&e,h=l?2+3*o:0,d=new Uint8Array(h);if(l){d[0]=e;for(let t=1;t<h;t++)d[t]=i[n++]}r.push({type:t,payloadType:a,pts:s,bytes:d})}}}}}else if(5===a&&o<t){if(l=!0,o>16){const t=[];for(let e=0;e<16;e++){const s=i[n++].toString(16);t.push(1==s.length?"0"+s:s),3!==e&&5!==e&&7!==e&&9!==e||t.push("-")}const e=o-16,l=new Uint8Array(e);for(let t=0;t<e;t++)l[t]=i[n++];r.push({payloadType:a,pts:s,uuid:t.join(""),userData:q(l),userDataBytes:l})}}else if(o<t)n+=o;else if(o>t)break}}function gt(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 mt(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 pt={};class LevelKey{static clearKeyUriToKeyIdMap(){pt={}}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 b:case k:case D:case R: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||f.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=S(this.uri);if(e)switch(this.keyFormat){case k:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case D:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mt(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=v(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=pt[this.uri];if(!t){const e=Object.keys(pt).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),pt[this.uri]=t}this.keyId=t}return this}}const yt=/\{\$([a-zA-Z0-9-_]+)\}/g;function Tt(t){return yt.test(t)}function Et(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]=vt(t,n))}}function vt(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(yt,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 St(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 Lt(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}"`))}const At={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}};function Rt(t,e){return MediaSource.isTypeSupported(`${e||"video"}/mp4;codecs="${t}"`)}const bt=/#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,Dt=/#EXT-X-MEDIA:(.*)/g,kt=/^#EXT(?:INF|-X-TARGETDURATION):/m,It=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Ct=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)/.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 convertAVC1ToAVCOTI(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}static resolve(e,s){return t.buildAbsoluteURL(s,e,{alwaysNormalize:!0})}static isMediaPlaylist(t){return kt.test(t)}static parseMasterPlaylist(t,e){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Tt(t)},r=[];let i;for(bt.lastIndex=0;null!=(i=bt.exec(t));)if(i[1]){var n;const t=new AttrList(i[1]);Et(s,t,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=vt(s,i[2]),o={attrs:t,bitrate:t.decimalInteger("AVERAGE-BANDWIDTH")||t.decimalInteger("BANDWIDTH"),name:t.NAME,url:M3U8Parser.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Pt((t.CODECS||"").split(/[ ,]+/).filter(t=>t),o),o.videoCodec&&-1!==o.videoCodec.indexOf("avc1")&&(o.videoCodec=M3U8Parser.convertAVC1ToAVCOTI(o.videoCodec)),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);Et(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=wt(r,e,s);t.encrypted&&t.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(t)):f.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":{const t=new AttrList(r);Et(s,t,["NAME","VALUE","QUERYPARAM"]),St(s,t,e)}break;case"CONTENT-STEERING":{const t=new AttrList(r);Et(s,t,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:M3U8Parser.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=_t(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(Dt.lastIndex=0;null!==(r=Dt.exec(t));){const t=new AttrList(r[1]),n=t.TYPE;if(n){const r=a[n],l=i[n]||[];i[n]=l,Et(s,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const h={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",instreamId:t["INSTREAM-ID"],name:t.NAME||t.LANGUAGE||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:t.LANGUAGE,url:t.URI?M3U8Parser.resolve(t.URI,e):""};if(null!=r&&r.length){const t=M3U8Parser.findGroup(r,h.groupId)||r[0];Mt(h,t,"audioCodec"),Mt(h,t,"textCodec")}l.push(h)}}return i}static parseLevelPlaylist(t,e,s,r,a,o){const l=new LevelDetails(e),h=l.fragments;let d,c,u,g=null,m=0,p=0,y=0,T=0,E=null,v=new Fragment(r,e),S=-1,L=!1;for(It.lastIndex=0,l.m3u8=t,l.hasVariableRefs=Tt(t);null!==(d=It.exec(t));){L&&(L=!1,v=new Fragment(r,e),v.start=y,v.sn=m,v.cc=T,v.level=s,g&&(v.initSegment=g,v.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null));const t=d[1];if(t){v.duration=parseFloat(t);const e=(" "+d[2]).slice(1);v.title=e||null,v.tagList.push(e?["INF",t,e]:["INF",t])}else if(d[3]){if(n(v.duration)){v.start=y,u&&Ot(v,u,l),v.sn=m,v.level=s,v.cc=T,v.urlId=a,h.push(v);const t=(" "+d[3]).slice(1);v.relurl=vt(l,t),xt(v,E),E=v,y+=v.duration,m++,p=0,L=!0}}else if(d[4]){const t=(" "+d[4]).slice(1);E?v.setByteRange(t,E):v.setByteRange(t)}else if(d[5])v.rawProgramDateTime=(" "+d[5]).slice(1),v.tagList.push(["PROGRAM-DATE-TIME",v.rawProgramDateTime]),-1===S&&(S=h.length);else{if(d=d[0].match(Ct),!d){f.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),a=(" "+d[c+1]).slice(1),y=d[c+2]?(" "+d[c+2]).slice(1):"";switch(t){case"PLAYLIST-TYPE":l.type=a.toUpperCase();break;case"MEDIA-SEQUENCE":m=l.startSN=parseInt(a);break;case"SKIP":{const t=new AttrList(a);Et(l,t,["RECENTLY-REMOVED-DATERANGES"]);const e=t.decimalInteger("SKIPPED-SEGMENTS");if(n(e)){l.skippedSegments=e;for(let t=e;t--;)h.unshift(null);m+=e}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(l.recentlyRemovedDateranges=s.split("\t"));break}case"TARGETDURATION":l.targetduration=Math.max(parseInt(a),1);break;case"VERSION":l.version=parseInt(a);break;case"EXTM3U":break;case"ENDLIST":l.live=!1;break;case"#":(a||y)&&v.tagList.push(y?[a,y]:[a]);break;case"DISCONTINUITY":T++,v.tagList.push(["DIS"]);break;case"GAP":v.gap=!0,v.tagList.push([t]);break;case"BITRATE":v.tagList.push([t,a]);break;case"DATERANGE":{const t=new AttrList(a);Et(l,t,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Et(l,t,t.clientAttrs);const e=new DateRange(t,l.dateRanges[t.ID]);e.isValid||l.skippedSegments?l.dateRanges[e.id]=e:f.warn(`Ignoring invalid DATERANGE tag: "${a}"`),v.tagList.push(["EXT-X-DATERANGE",a]);break}case"DEFINE":{const t=new AttrList(a);Et(l,t,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in t?Lt(l,t,o):St(l,t,e)}break;case"DISCONTINUITY-SEQUENCE":T=parseInt(a);break;case"KEY":{const t=wt(a,e,l);if(t.isSupported()){if("NONE"===t.method){u=void 0;break}u||(u={}),u[t.keyFormat]&&(u=i({},u)),u[t.keyFormat]=t}else f.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${a}"`);break}case"START":l.startTimeOffset=_t(a);break;case"MAP":{const t=new AttrList(a);if(Et(l,t,["BYTERANGE","URI"]),v.duration){const i=new Fragment(r,e);Ft(i,t,s,u),g=i,v.initSegment=g,g.rawProgramDateTime&&!v.rawProgramDateTime&&(v.rawProgramDateTime=g.rawProgramDateTime)}else Ft(v,t,s,u),g=v,L=!0;break}case"SERVER-CONTROL":{const t=new AttrList(a);l.canBlockReload=t.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=t.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&t.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=t.optionalFloat("PART-HOLD-BACK",0),l.holdBack=t.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const t=new AttrList(a);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=l.partList;t||(t=l.partList=[]);const s=p>0?t[t.length-1]:void 0,r=p++,i=new AttrList(a);Et(l,i,["BYTERANGE","URI"]);const n=new Part(i,v,e,r,s);t.push(n),v.duration+=n.duration;break}case"PRELOAD-HINT":{const t=new AttrList(a);Et(l,t,["URI"]),l.preloadHint=t;break}case"RENDITION-REPORT":{const t=new AttrList(a);Et(l,t,["URI"]),l.renditionReports=l.renditionReports||[],l.renditionReports.push(t);break}default:f.warn("line parsed but not handled: "+d)}}}E&&!E.relurl?(h.pop(),y-=E.duration,l.partList&&(l.fragmentHint=E)):l.partList&&(xt(v,E),v.cc=T,l.fragmentHint=v,u&&Ot(v,u,l));const A=h.length,R=h[0],b=h[A-1];if(y+=l.skippedSegments*l.targetduration,y>0&&A&&b){l.averagetargetduration=y/A;const t=b.sn;l.endSN="initSegment"!==t?t:0,l.live||(b.endList=!0),R&&(l.startCC=R.cc)}else l.endSN=0,l.startCC=0;return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,l.endCC=T,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),l}}function wt(t,e,s){var r,i;const n=new AttrList(t);Et(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&&f.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 _t(t){const e=new AttrList(t).decimalFloatingPoint("TIME-OFFSET");return n(e)?e:null}function Pt(t,e){["video","audio","text"].forEach(s=>{const r=t.filter(t=>function(t,e){const s=At[e];return!!s&&!0===s[t.slice(0,4)]}(t,s));if(r.length){const i=r.filter(t=>0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0));e[s+"Codec"]=i.length>0?i[0]:r[0],t=t.filter(t=>-1===r.indexOf(t))}}),e.unknownCodecs=t}function Mt(t,e,s){const r=e[s];r&&(t[s]=r)}function xt(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),n(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Ft(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 Ot(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 Nt="manifest",Ut="level",Bt="audioTrack",$t="subtitleTrack",Gt="main",Kt="audio",Ht="subtitle";function Vt(t){const{type:e}=t;switch(e){case Bt:return Kt;case $t:return Ht;default:return Gt}}function Yt(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(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(a.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:Nt,url:s,deliveryDirectives:null})}onLevelLoading(t,e){const{id:s,level:r,url:i,deliveryDirectives:n}=e;this.load({id:s,level:r,responseType:"text",type:Ut,url:i,deliveryDirectives:n})}onAudioTrackLoading(t,e){const{id:s,groupId:r,url:i,deliveryDirectives:n}=e;this.load({id:s,groupId:r,level:null,responseType:"text",type:Bt,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:$t,url:i,deliveryDirectives:n})}load(t){var e;const s=this.hls.config;let r,n=this.getInternalLoader(t);if(n){const e=n.context;if(e&&e.url===t.url)return void f.trace("[playlist-loader]: playlist request ongoing");f.log("[playlist-loader]: aborting previous loader for type: "+t.type),n.abort()}if(r=t.type===Nt?s.manifestLoadPolicy.default:i({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),null!=(e=t.deliveryDirectives)&&e.part){let e;if(t.type===Ut&&null!==t.level?e=this.hls.levels[t.level].details:t.type===Bt&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===$t&&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=i({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={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)}};n.load(t,o,l)}handleMasterPlaylist(t,e,s,r){const i=this.hls,n=t.data,o=Yt(t,s),l=M3U8Parser.parseMasterPlaylist(n,o);if(l.playlistParsingError)return void this.handleManifestParsingError(t,s,l.playlistParsingError,r,e);const{contentSteering:h,levels:d,sessionData:c,sessionKeys:u,startTimeOffset:g,variableList:m}=l;this.variableList=m;const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":T}=M3U8Parser.parseMasterPlaylistMedia(n,o,l);if(p.length){p.some(t=>!t.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(f.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new AttrList({}),bitrate:0,url:""}))}i.trigger(a.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:y,captions:T,contentSteering:h,url:o,stats:e,networkDetails:r,sessionData:c,sessionKeys:u,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(t,e,s,r,i){const o=this.hls,{id:l,level:h,type:d}=s,c=Yt(t,s),u=n(l)?l:0,f=n(h)?h:u,g=Vt(s),m=M3U8Parser.parseLevelPlaylist(t.data,c,f,g,u,this.variableList);if(d===Nt){const t={attrs:new AttrList({}),bitrate:0,details:m,name:"",url:c};o.trigger(a.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:c,stats:e,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=m,this.handlePlaylistLoaded(m,t,e,s,r,i)}handleManifestParsingError(t,e,s,r,i){this.hls.trigger(a.ERROR,{type:o.NETWORK_ERROR,details:l.MANIFEST_PARSING_ERROR,fatal:e.type===Nt,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:r,stats:i})}handleNetworkError(t,e,r=!1,i,n){let h=`A network ${r?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===Ut?h+=`: ${t.level} id: ${t.id}`:t.type!==Bt&&t.type!==$t||(h+=` id: ${t.id} group-id: "${t.groupId}"`);const d=new Error(h);f.warn("[playlist-loader]: "+h);let c=l.UNKNOWN,u=!1;const g=this.getInternalLoader(t);switch(t.type){case Nt:c=r?l.MANIFEST_LOAD_TIMEOUT:l.MANIFEST_LOAD_ERROR,u=!0;break;case Ut:c=r?l.LEVEL_LOAD_TIMEOUT:l.LEVEL_LOAD_ERROR,u=!1;break;case Bt:c=r?l.AUDIO_TRACK_LOAD_TIMEOUT:l.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case $t:c=r?l.SUBTITLE_TRACK_LOAD_TIMEOUT:l.SUBTITLE_LOAD_ERROR,u=!1}g&&this.resetInternalLoader(t.type);const m={type:o.NETWORK_ERROR,details:c,fatal:u,url:t.url,loader:g,context:t,error:d,networkDetails:e,stats:n};if(i){const r=(null==e?void 0:e.url)||t.url;m.response=s({url:r,data:void 0},i)}this.hls.trigger(a.ERROR,m)}handlePlaylistLoaded(t,e,s,r,i,n){const h=this.hls,{type:d,level:c,id:u,groupId:f,deliveryDirectives:g}=r,m=Yt(e,r),p=Vt(r),y="number"==typeof r.level&&p===Gt?c:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void h.trigger(a.ERROR,{type:o.NETWORK_ERROR,details:l.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 T=t.playlistParsingError;if(T)h.trigger(a.ERROR,{type:o.NETWORK_ERROR,details:l.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:T,reason:T.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)),d){case Nt:case Ut:h.trigger(a.LEVEL_LOADED,{details:t,level:y||0,id:u||0,stats:s,networkDetails:i,deliveryDirectives:g});break;case Bt:h.trigger(a.AUDIO_TRACK_LOADED,{details:t,id:u||0,groupId:f||"",stats:s,networkDetails:i,deliveryDirectives:g});break;case $t:h.trigger(a.SUBTITLE_TRACK_LOADED,{details:t,id:u||0,groupId:f||"",stats:s,networkDetails:i,deliveryDirectives:g})}}}function Wt(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 qt(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){f.debug("[texttrack-utils]: "+s);const r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,t.addCue(r)}"disabled"===s&&(t.mode=s)}function jt(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 Xt(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)}var zt="org.id3",Qt="com.apple.quicktime.HLS",Jt="https://aomedia.org/emsg/ID3";function Zt(){if("undefined"!=typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const te=(()=>{const t=Zt();try{new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function ee(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(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(jt(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 Wt(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=Zt();for(let t=0;t<i.length;t++){const e=i[t].type;if(e===Jt&&!s||!r)continue;const a=G(i[t].data);if(a){const s=i[t].pts;let r=s+i[t].duration;r>te&&(r=te);r-s<=0&&(r=s+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!B(i)){this.updateId3CueEnds(s);const t=new n(s,r,"");t.value=i,e&&(t.type=e),this.id3Track.addCue(t)}}}}}updateId3CueEnds(t){var e;const s=null==(e=this.id3Track)?void 0:e.cues;if(s)for(let e=s.length;e--;){const r=s[e];r.startTime<t&&r.endTime===te&&(r.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===zt&&o:"video"===r?t=>t.type===Jt&&a:t=>t.type===zt&&o||t.type===Jt&&a,Xt(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,a=Object.keys(i);if(r){const t=Object.keys(s).filter(t=>!a.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 o=e.fragments[e.fragments.length-1];if(0===a.length||!n(null==o?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,h=Zt();for(let t=0;t<a.length;t++){const e=a[t],r=i[e],n=s[e],o=(null==n?void 0:n.cues)||{};let u=(null==n?void 0:n.durationKnown)||!1;const f=ee(r.startDate,l);let g=te;const m=r.endDate;if(m)g=ee(m,l),u=!0;else if(r.endOnNext&&!u){const t=a.reduce((t,e)=>{const s=i[e];return s.class===r.class&&s.id!==e&&s.startDate>r.startDate&&t.push(s),t},[]).sort((t,e)=>t.startDate.getTime()-e.startDate.getTime())[0];t&&(g=ee(t.startDate,l),u=!0)}const y=Object.keys(r.attr);for(let t=0;t<y.length;t++){const s=y[t];if("ID"===(c=s)||"CLASS"===c||"START-DATE"===c||"DURATION"===c||"END-DATE"===c||"END-ON-NEXT"===c)continue;let i=o[s];if(i)u&&!n.durationKnown&&(i.endTime=g);else{let t=r.attr[s];i=new h(f,g,""),p(s)&&(d=t,t=Uint8Array.from(d.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer),i.value={key:s,data:t},i.type=Qt,i.id=e,this.id3Track.addCue(i),o[s]=i}}s[e]={cues:o,dateRange:r,durationKnown:u}}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(a.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(a.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(a.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(a.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(a.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===l.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(s=this.levelDetails)&&s.live&&f.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)return;const n=this.targetLatency;if(null===n)return;const a=s-n,o=a<Math.min(this.maxLatency,n+e.targetduration);if(e.live&&o&&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 se=["NONE","TYPE-0","TYPE-1",null];var re="",ie="YES",ne="v2";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.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=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.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.unknownCodecs=t.unknownCodecs,this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>t).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(t){const e=t%this.url.length;this._urlId!==e&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=e)}get audioGroupId(){var t;return null==(t=this.audioGroupIds)?void 0:t[this.urlId]}get textGroupId(){var t;return null==(t=this.textGroupIds)?void 0:t[this.urlId]}addFallback(t){this.url.push(t.url),this._attrs.push(t.attrs)}}function ae(t,e){const s=e.startPTS;if(n(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,a){r-s<=0&&(f.warn("Fragment should have a positive duration",e),r=s+e.duration,a=i+e.duration);let o=s,l=r;const h=e.startPTS,d=e.endPTS;if(n(h)){const t=Math.abs(h-s);n(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,o=Math.max(s,h),s=Math.min(s,h),i=Math.min(i,e.startDTS),l=Math.min(r,d),r=Math.max(r,d),a=Math.max(a,e.endDTS)}const c=s-e.start;0!==e.start&&(e.start=s),e.duration=r-e.start,e.startPTS=s,e.maxStartPTS=o,e.startDTS=i,e.endPTS=r,e.minEndPTS=l,e.endDTS=a;const u=e.sn;if(!t||u<t.startSN||u>t.endSN)return 0;let g;const m=u-t.startSN,p=t.fragments;for(p[m]=e,g=m;g>0;g--)ae(p[g],p[g-1]);for(g=m;g<p.length-1;g++)ae(p[g],p[g+1]);return t.fragmentHint&&ae(p[p.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,c}function le(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 a,o=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&&(o=t.cc-r.cc),n(t.startPTS)&&n(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&&(a=r),e.PTSKnown=e.alignedSliding=!0),r.elementaryStreams=t.elementaryStreams,r.loader=t.loader,r.stats=t.stats,r.urlId=t.urlId,t.initSegment&&(r.initSegment=t.initSegment,s=t.initSegment)}),s){(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(t=>{var e;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){f.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=i({},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:f.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[t].attr)}"`)}),r}(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const l=e.fragments;if(o){f.warn("discontinuity sliding from playlist, take drift into account");for(let t=0;t<l.length;t++)l[t].cc+=o}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}),a?oe(e,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS):he(t,e),l.length&&(e.totalduration=e.edge-l[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 he(t,e){const s=e.startSN+e.skippedSegments-t.startSN,r=t.fragments;s<0||s>=r.length||de(e,r[s].start)}function de(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 ce(t,e,s){var r;return null!=t&&t.details?ue(null==(r=t.details)?void 0:r.partList,e,s):null}function ue(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 fe(t){switch(t.details){case l.FRAG_LOAD_TIMEOUT:case l.KEY_LOAD_TIMEOUT:case l.LEVEL_LOAD_TIMEOUT:case l.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ge(t,e){const s=fe(e);return t.default[(s?"timeout":"error")+"Retry"]}function me(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function pe(t){return s(s({},t),{errorRetry:null,timeoutRetry:null})}function ye(t,e,s,r){return!!t&&e<t.maxNumRetry&&(function(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}(r)||!!s)}const Te=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 Ee(t,e,s=0,r=0){let i=null;if(t?i=e[t.sn-e[0].sn+1]||null:0===s&&0===e[0].start&&(i=e[0]),i&&0===ve(s,r,i))return i;const n=Te(e,ve.bind(null,s,r));return!n||n===t&&i?i:n}function ve(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 Se(t,e,s){const r=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-r>t}var Le=0,Ae=2,Re=5,be=0,De=1,ke=2;function Ie(t,e,s){if(performance.now()-t.lastErrorPerfMs>3e5)return!0;const r=t.details;if(e.details===l.FRAG_GAP&&r&&e.frag){const t=e.frag.start,s=Ee(null,r.fragments,t);if(s&&!s.gap)return!0}if(s&&t.errors.length<s.errors.length){const s=t.errors[t.errors.length-1];if(r&&s.frag&&e.frag&&Math.abs(s.frag.start-e.frag.start)>3*r.targetduration)return!0}return!1}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=f.log.bind(f,e+":"),this.warn=f.warn.bind(f,e+":"),this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e){const s=null==e?void 0:e.renditionReports;if(s){let r=-1;for(let i=0;i<s.length;i++){const n=s[i];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){f.warn("Could not construct new URL for Rendition Report: "+t),a=n.URI||""}if(a===t){r=i;break}a===t.substring(0,a.length)&&(r=i)}if(-1!==r){const t=s[r],i=parseInt(t["LAST-MSN"])||(null==e?void 0:e.lastPartSn);let n=parseInt(t["LAST-PART"])||(null==e?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);n>=0&&t>e.partTarget&&(n+=1)}return new HlsUrlParameters(i,n>=0?n:void 0,re)}}}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:"MISSED"}`),s&&r.fragments.length>0&&le(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&&(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=function(t,e){const{canSkipUntil:s,canSkipDateRanges:r,endSN:i}=t;return s&&(void 0!==e?e-i:0)<s?r?ne:ie:re}(t,s);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,r=e.part,i=re),new HlsUrlParameters(s,r,i)}checkRetry(t){const e=t.details,s=fe(t),r=t.errorAction,{action:i,retryCount:n=0,retryConfig:a}=r||{},o=i===Re&&!!r&&!!a;if(o){var l;if(this.requestScheduled=-1,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=me(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}}let Ce;class LevelController extends BasePlaylistController{constructor(t,e){super(t,"[level-controller]"),this._levels=[],this._firstLevel=-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(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const s=[],r={};let i;e.levels.forEach(t=>{var e;const n=t.attrs;-1!==(null==(e=t.audioCodec)?void 0:e.indexOf("mp4a.40.34"))&&(Ce||(Ce=/chrome|firefox/i.test(navigator.userAgent)),Ce&&(t.audioCodec=void 0));const{AUDIO:a,CODECS:o,"FRAME-RATE":l,"PATHWAY-ID":h,RESOLUTION:d,SUBTITLES:c}=n,u=`${(h||".")+"-"}${t.bitrate}-${d}-${l}-${o}`;i=r[u],i?i.addFallback(t):(i=new Level(t),r[u]=i,s.push(i)),we(i,"audio",a),we(i,"text",c)}),this.filterAndSortMediaOptions(s,e)}filterAndSortMediaOptions(t,e){let s=[],r=[],i=!1,n=!1,h=!1,d=t.filter(({audioCodec:t,videoCodec:e,width:s,height:r,unknownCodecs:a})=>(i||(i=!(!s||!r)),n||(n=!!e),h||(h=!!t),!(null!=a&&a.length)&&(!t||Rt(t,"audio"))&&(!e||Rt(e,"video"))));if((i||n)&&h&&(d=d.filter(({videoCodec:t,width:e,height:s})=>!!t||!(!e||!s))),0===d.length)return void Promise.resolve().then(()=>{if(this.hls){const t=new Error("no level with compatible codecs found in manifest");this.hls.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:t,reason:t.message})}});e.audioTracks&&(s=e.audioTracks.filter(t=>!t.audioCodec||Rt(t.audioCodec,"audio")),_e(s)),e.subtitles&&(r=e.subtitles,_e(r));const c=d.slice(0);d.sort((t,e)=>t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"]?(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1:t.bitrate!==e.bitrate?t.bitrate-e.bitrate:t.attrs["FRAME-RATE"]!==e.attrs["FRAME-RATE"]?t.attrs.decimalFloatingPoint("FRAME-RATE")-e.attrs.decimalFloatingPoint("FRAME-RATE"):t.attrs.SCORE!==e.attrs.SCORE?t.attrs.decimalFloatingPoint("SCORE")-e.attrs.decimalFloatingPoint("SCORE"):i&&t.height!==e.height?t.height-e.height:0);let u=c[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==c.length))for(let t=0;t<c.length;t++)if(c[t].pathwayId===d[0].pathwayId){u=c[t];break}this._levels=d;for(let t=0;t<d.length;t++)if(d[t]===u){this._firstLevel=t,this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${u.bitrate}`);break}const f=h&&!n,g={levels:d,audioTracks:s,subtitleTracks:r,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:h,video:n,altAudio:!f&&s.some(t=>!!t.url)};this.hls.trigger(a.MANIFEST_PARSED,g),(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(a.ERROR,{type:o.OTHER_ERROR,details:l.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,n=r?r.attrs["PATHWAY-ID"]:void 0,h=e[t],d=h.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=h,s===t&&h.details&&r&&n===d)return;this.log(`Switching to level ${t}${d?" with Pathway "+d:""} from level ${s}${n?" with Pathway "+n:""}`);const c=i({},h,{level:t,maxBitrate:h.maxBitrate,attrs:h.attrs,uri:h.uri,urlId:h.urlId});delete c._attrs,delete c._urlId,this.hls.trigger(a.LEVEL_SWITCHING,c);const u=h.details;if(!u||u.live){const t=this.switchParams(h.uri,null==r?void 0:r.details);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){!e.fatal&&e.context&&e.context.type===Ut&&e.context.level===this.level&&this.checkRetry(e)}onFragLoaded(t,{frag:e}){if(void 0!==e&&e.type===Gt){const t=this._levels[e.level];void 0!==t&&(t.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)}onAudioTrackSwitched(t,e){const s=this.currentLevel;if(!s)return;const r=this.hls.audioTracks[e.id].groupId;if(s.audioGroupIds&&s.audioGroupId!==r){let t=-1;for(let e=0;e<s.audioGroupIds.length;e++)if(s.audioGroupIds[e]===r){t=e;break}-1!==t&&t!==s.urlId&&(s.urlId=t,this.canLoad&&this.startLoad())}}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){const r=s.urlId;let i=s.uri;if(t)try{i=t.addDirectives(i)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}const n=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${n?" Pathway "+n:""} URI ${r+1}/${s.url.length} ${i}`),this.clearTimer(),this.hls.trigger(a.LEVEL_LOADING,{url:i,level:e,id:r,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,e){const s=(t,s)=>s!==e,r=this._levels.filter((r,i)=>i!==t||(r.url.length>1&&void 0!==e?(r.url=r.url.filter(s),r.audioGroupIds&&(r.audioGroupIds=r.audioGroupIds.filter(s)),r.textGroupIds&&(r.textGroupIds=r.textGroupIds.filter(s)),r.urlId=0,!0):(this.steering&&this.steering.removeLevel(r),!1)));this.hls.trigger(a.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(t,{levels:e}){e.forEach((t,e)=>{const{details:s}=t;null!=s&&s.fragments&&s.fragments.forEach(t=>{t.level=e})}),this._levels=e}}function we(t,e,s){s&&("audio"===e?(t.audioGroupIds||(t.audioGroupIds=[]),t.audioGroupIds[t.url.length-1]=s):"text"===e&&(t.textGroupIds||(t.textGroupIds=[]),t.textGroupIds[t.url.length-1]=s))}function _e(t){const e={};t.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}var Pe="NOT_LOADED",Me="APPENDING",xe="PARTIAL",Fe="OK";class FragmentTracker{constructor(t){this.mainFragEntity=null,this.activeParts=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(a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.endListFragments=this.timeRanges=this.mainFragEntity=this.activeParts=null}getAppendedFrag(t,e){if(e===Gt){const{mainFragEntity:e,activeParts:s}=this;if(e)if(e&&s)for(let r=s.length;r--;){const i=s[r],n=i?i.end:e.appendedPTS;if(i.start<=t&&null!==n&&t<=n)return r>9&&(this.activeParts=s.slice(r-9)),i}else if(e.body.start<=t&&null!==e.appendedPTS&&t<=e.appendedPTS)return e.body}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){this.timeRanges&&(this.timeRanges[t]=e),Object.keys(this.fragments).forEach(r=>{const i=this.fragments[r];if(!i)return;if(!i.buffered&&!i.loaded)return void(i.body.type===s&&this.removeFragment(i.body));const n=i.range[t];n&&n.time.some(t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(i.body),s})})}detectPartialFragments(t){const e=this.timeRanges,{frag:s,part:r}=t;if(!e||"initSegment"===s.sn)return;const i=Ne(s),n=this.fragments[i];n&&(Object.keys(e).forEach(t=>{const i=s.elementaryStreams[t];if(!i)return;const a=e[t],o=null!==r||!0===i.partial;n.range[t]=this.getBufferedTimes(s,r,o,a)}),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,n.body.endList&&(this.endListFragments[n.body.type]=n)):this.removeFragment(n.body))}fragBuffered(t,e){const s=Ne(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=e?e.start:t.start,a=e?e.end: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)i.partial=!0,i.time.push({startPTS:Math.max(n,r.start(t)),endPTS:Math.min(a,r.end(t))});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&&Oe(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||Oe(e))}getState(t){const e=Ne(t),s=this.fragments[e];return s?s.buffered?Oe(s)?xe:Fe:Me:Pe}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||r)return;const i=Ne(s);this.fragments[i]={body:s,appendedPTS:null,loaded:e,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:r,timeRanges:i}=e;let n=this.mainFragEntity;if(s.type===Gt){const t=n?n.body:null;if(t!==s){n&&t&&t.sn!==s.sn&&(n.buffered=!0,this.fragments[Ne(t)]=n);const e=Ne(s);n=this.mainFragEntity=this.fragments[e]||{body:s,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)}}if(r){let t=this.activeParts;t||(this.activeParts=t=[]),t.push(r)}else this.activeParts=null}this.timeRanges=i,Object.keys(i).forEach(t=>{const e=i[t];if(this.detectEvictedFragments(t,e),!r&&n){const r=s.elementaryStreams[t];if(!r)return;for(let t=0;t<e.length;t++){const s=e.end(t);s<=r.endPTS&&s>r.startPTS?n.appendedPTS=Math.max(s,n.appendedPTS||0):n.appendedPTS=r.endPTS}}})}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Ne(t);return!!this.fragments[e]}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=Ne(t);t.stats.loaded=0,t.clearElementaryStreamInfo(),this.mainFragEntity===this.fragments[e]&&(this.mainFragEntity=null),delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.mainFragEntity=null,this.activeParts=null,this.hasGaps=!1}}function Oe(t){var e,s;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(s=t.range.audio)?void 0:s.partial))}function Ne(t){return`${t.type}_${t.level}_${t.urlId}_${t.sn}`}const Ue=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 r=t.url;if(!r)return Promise.reject(new LoadError({type:o.NETWORK_ERROR,details:l.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,n=i.fLoader,a=i.loader;return new Promise((h,d)=>{if(this.loader&&this.loader.destroy(),t.gap)return void d($e(t));const c=this.loader=t.loader=n?new n(i):new a(i),u=Be(t),f=pe(i.fragLoadPolicy.default),g={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Ue};t.stats=c.stats,c.load(u,g,{onSuccess:(e,s,r,i)=>{this.resetLoader(t,c);let n=e.data;r.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),h({frag:t,part:null,payload:n,networkDetails:i})},onError:(e,i,n,a)=>{this.resetLoader(t,c),d(new LoadError({type:o.NETWORK_ERROR,details:l.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:s({url:r,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:n,stats:a}))},onAbort:(e,s,r)=>{this.resetLoader(t,c),d(new LoadError({type:o.NETWORK_ERROR,details:l.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:r,stats:e}))},onTimeout:(e,s,r)=>{this.resetLoader(t,c),d(new LoadError({type:o.NETWORK_ERROR,details:l.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,r){this.abort();const i=this.config,n=i.fLoader,a=i.loader;return new Promise((h,d)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void d($e(t,e));const c=this.loader=t.loader=n?new n(i):new a(i),u=Be(t,e),f=pe(i.fragLoadPolicy.default),g={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ue};e.stats=c.stats,c.load(u,g,{onSuccess:(s,i,n,a)=>{this.resetLoader(t,c),this.updateStatsFromPart(t,e);const o={frag:t,part:e,payload:s.data,networkDetails:a};r(o),h(o)},onError:(r,i,n,a)=>{this.resetLoader(t,c),d(new LoadError({type:o.NETWORK_ERROR,details:l.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:s({url:u.url,data:void 0},r),error:new Error(`HTTP Error ${r.code} ${r.text}`),networkDetails:n,stats:a}))},onAbort:(s,r,i)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,c),d(new LoadError({type:o.NETWORK_ERROR,details:l.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:i,stats:s}))},onTimeout:(s,r,i)=>{this.resetLoader(t,c),d(new LoadError({type:o.NETWORK_ERROR,details:l.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 Be(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,a=s.byteRangeEndOffset;if(n(i)&&n(a)){var o;let e=i,s=a;if("initSegment"===t.sn&&"AES-128"===(null==(o=t.decryptdata)?void 0:o.method)){const t=a-i;t%16&&(s=a+(16-t%16)),0!==i&&(r.resetIV=!0,e=i-16)}r.rangeStart=e,r.rangeEnd=s}return r}function $e(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),r={type:o.MEDIA_ERROR,details:l.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 KeyLoader{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.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=l.KEY_LOAD_ERROR,s,r,i){return new LoadError({type:o.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,l.KEY_LOAD_ERROR,s))}const n=i.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,l.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,l.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 r=this.config,i=new(0,r.loader)(r);return e.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((n,a)=>{const o={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},h=r.keyLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,e,s,r)=>{const{frag:i,keyInfo:o,url:h}=s;if(!i.decryptdata||o!==this.keyUriToKeyInfo[h])return a(this.createKeyLoadError(i,l.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,r,i,n)=>{this.resetLoader(r),a(this.createKeyLoadError(e,l.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),i,s({url:o.url,data:void 0},t)))},onTimeout:(t,s,r)=>{this.resetLoader(s),a(this.createKeyLoadError(e,l.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(t,s,r)=>{this.resetLoader(s),a(this.createKeyLoadError(e,l.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};i.load(o,d,c)})}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()}}const Ge={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 f.log("failed to get media.buffered",t),Ge}}}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 Ke(t,e){let s=null;for(let r=0,i=t.length;r<i;r++){const i=t[r];if(i&&i.cc===e){s=i;break}}return s}function He(t,e){if(t){const s=t.start+e;t.start=t.startPTS=s,t.endPTS=s+t.duration}}function Ve(t,e){const s=e.fragments;for(let e=0,r=s.length;e<r;e++)He(s[e],t);e.fragmentHint&&He(e.fragmentHint,t),e.alignedSliding=!0}function Ye(t,e,s){e&&(!function(t,e,s){if(function(t,e,s){return!(!e.details||!(s.endCC>s.startCC||t&&t.cc<s.startCC))}(t,s,e)){const t=function(t,e,s=0){const r=t.fragments,i=e.fragments;if(!i.length||!r.length)return void f.log("No fragments to align");const n=Ke(r,i[0].cc);if(n&&(!n||n.startPTS))return n;f.log("No frag in previous level to align on")}(s.details,e);t&&n(t.start)&&(f.log("Adjusting PTS using last level due to CC increase within current level "+e.url),Ve(t.start,e))}}(t,s,e),!s.alignedSliding&&e.details&&function(t,e){if(!e.fragments.length||!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=e.fragments[0].programDateTime,r=t.fragments[0].programDateTime,i=(r-s)/1e3+e.fragments[0].start;i&&n(i)&&(f.log(`Adjusting PTS using programDateTime delta ${r-s}ms, sliding:${i.toFixed(3)} ${t.url} `),Ve(i,t))}(s,e.details),s.alignedSliding||!e.details||s.skippedSegments||he(e.details,s))}function We(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,r=e.fragments;if(!s.length||!r.length)return;const i=r[Math.round(r.length/2)-1],n=Ke(s,i.cc)||s[Math.round(s.length/2)-1],a=i.programDateTime,o=n.programDateTime;if(null===a||null===o)return;Ve((o-a)/1e3-(n.start-i.start),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,T;for(a=0;a<n;a++)a<i?y=l[a]=e[a]:(T=y,a%i==0?(T=T<<8|T>>>24,T=d[T>>>24]<<24|d[T>>>16&255]<<16|d[T>>>8&255]<<8|d[255&T],T^=c[a/i|0]<<24):i>6&&a%i==4&&(T=d[T>>>24]<<24|d[T>>>16&255]<<16|d[T>>>8&255]<<8|d[255&T]),l[a]=y=(l[a-i]^T)>>>0);for(o=0;o<n;o++)a=n-o,T=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?T:f[d[T>>>24]]^g[d[T>>>16&255]]^m[d[T>>>8&255]]^p[d[255&T]],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 T,E,v,S,L,A,R,b,D,k,I,C,w,_;const P=this.networkToHostOrderSwap;for(;e<p.length;){for(D=P(p[e]),k=P(p[e+1]),I=P(p[e+2]),C=P(p[e+3]),L=D^i[0],A=C^i[1],R=I^i[2],b=k^i[3],w=4,_=1;_<r;_++)T=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],v=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=T,A=E,R=v,b=S,w+=4;T=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],v=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]=P(T^u),y[e+1]=P(S^f),y[e+2]=P(v^g),y[e+3]=P(E^m),u=D,f=k,g=I,m=C,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?M(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=dt(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=M(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=>(f.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=M(t,0,s),this.remainderData=M(t,s)),e}logOnce(t){this.logEnabled&&(f.log("[decrypter]: "+t),this.logEnabled=!1)}}const qe=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},je="STOPPED",Xe="IDLE",ze="KEY_LOADING",Qe="FRAG_LOADING",Je="FRAG_LOADING_WAITING_RETRY",Ze="WAITING_TRACK",ts="PARSING",es="PARSED",ss="ENDED",rs="ERROR",is="WAITING_INIT_PTS",ns="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=je,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=f.log.bind(f,r+":"),this.warn=f.warn.bind(f,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(a.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort();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=je}_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.levels[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===je&&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,a=s?s.currentTime:0,o=BufferHelper.bufferInfo(r||s,a,t.maxBufferHole);if(this.log(`media seeking to ${n(a)?a.toFixed(3):a}, state: ${i}`),this.state===ss)this.resetLoadingState();else if(e){const s=t.maxFragLookUpTolerance,r=e.start-s,i=e.start+e.duration+s;if(!o.len||i<o.start||r>o.end){const t=a>i;(a<r||t)&&(t&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests()),this.resetLoadingState())}}s&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),this.loadedmetadata||o.len||(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=je,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===Qe||!this.fragCurrent&&s===ts)&&(this.fragmentTracker.removeFragment(t),this.state=Xe):("payload"in e&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(a.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(e=>{this.state!==je&&this.state!==rs&&(this.warn(e),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;if(this.fragmentTracker.getState(t)===Me){const e=t.type,s=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,s?s.len:this.config.maxBufferLength);this.reduceMaxBufferLength(r)&&this.fragmentTracker.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)&&this.fragmentTracker.removeAllFragments()}flushMainBuffer(t,e,s=null){if(!(t-e))return;const r={startOffset:t,endOffset:e,type:s};this.hls.trigger(a.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&&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(a.ERROR,{type:o.MEDIA_ERROR,details:l.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(r=>{const i=self.performance.now();return s.trigger(a.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:n,tdecrypt:i}}),e.payload=r,e})}return e}).then(s=>{const{fragCurrent:r,hls:i,levels:n}=this;if(!n)throw new Error("init load aborted, missing levels");const o=t.stats;this.state=Xe,e.fragmentError=0,t.data=new Uint8Array(s.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),s.frag===r&&i.trigger(a.FRAG_BUFFERED,{stats:o,frag:r,part:null,id:t.type}),this.tick()}).catch(e=>{this.state!==je&&this.state!==rs&&(this.warn(e),this.resetFragmentLoading(t))})}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId}fragBufferedComplete(t,e){var s,r,i,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level} (frag:[${(null!=(s=t.startPTS)?s:NaN).toFixed(3)}-${(null!=(r=t.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?qe(BufferHelper.getBuffered(a)):"(detached)"})`),this.state=Xe,a&&(!this.loadedmetadata&&t.type==Gt&&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 o=null==e?void 0:e.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let l=null;if(!t.encrypted||null!=(i=t.decryptdata)&&i.key?!t.encrypted&&o.encryptedFragments.length&&this.keyLoader.loadClear(t,o.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${o.startSN}-${o.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level}`),this.state=ze,this.fragCurrent=t,l=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(a.KEY_LOADED,t),this.state===ze&&(this.state=Xe),t}),this.hls.trigger(a.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(l=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),s=Math.max(t.start,s||0),this.config.lowLatencyMode){const i=o.partList;if(i&&r){s>t.end&&o.fragmentHint&&(t=o.fragmentHint);const n=this.getNextPart(i,t,s);if(n>-1){const h=i[n];let d;return this.log(`Loading part sn: ${t.sn} p: ${h.index} cc: ${t.cc} of playlist [${o.startSN}-${o.endSN}] parts [0-${n}-${i.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=h.start+h.duration,this.state=Qe,d=l?l.then(s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,h,e,r)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,h,e,r).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(a.FRAG_LOADING,{frag:t,part:h,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!t.url||this.loadedEndOfParts(i,s))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${o?"of ["+o.startSN+"-"+o.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),n(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Qe;const h=this.config.progressive;let d;return d=h&&l?l.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,h?r:void 0),l]).then(([t])=>(!h&&t&&r&&r(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(a.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(t,e,s,r){return new Promise((i,n)=>{var o;const l=[],h=null==(o=s.details)?void 0:o.partList,d=e=>{this.fragmentLoader.loadPart(t,e,r).then(r=>{l[e.index]=r;const n=r.part;this.hls.trigger(a.FRAG_LOADED,r);const o=ce(s,t.sn,e.index+1)||ue(h,t.sn,e.index+1);if(!o)return i({frag:t,part:n,partsLoaded:l});d(o)}).catch(n)};d(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===l.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(a.ERROR,e)}else this.hls.trigger(a.ERROR,{type:o.OTHER_ERROR,details:l.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==ts)return void(this.fragCurrent||this.state===je||this.state===rs||(this.state=Xe));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?ce(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){var i;if(!t||this.state!==ts)return;const{data1:n,data2:o}=t;let l=n;if(n&&o&&(l=dt(n,o)),null==(i=l)||!i.length)return;const h={type:t.type,frag:e,part:s,chunkMeta:r,parent:e.type,data:l};this.hls.trigger(a.BUFFER_APPENDING,h),t.dropped&&t.independent&&!s&&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 n(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)}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 n=i.initialLiveManifestSize;if(r<n)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${n})`),null;e.PTSKnown||this.startFragRequested||-1!==this.startPosition||(a=this.getInitialLiveFragment(e,s),this.startPosition=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===Fe||s===xe&&!!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||!n(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(Se(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 Te(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=!!(r.lowLatencyMode&&s.partList&&o);let d;if(h&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),t<e){d=Ee(i,n,t,t>e-l?0:l)}else d=n[n.length-1];if(d){const t=d.sn-s.startSN,e=this.fragmentTracker.getState(d);if((e===Fe||e===xe&&d.gap)&&(i=d),i&&d.sn===i.sn&&!h){if(i&&d.level===i.level){const e=n[t+1];d=d.sn<a&&this.fragmentTracker.getState(e)!==Fe?e:null}}}return d}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){const{levels:s,levelLastLoaded:r,fragPrevious:i}=this,a=null!==r?s[r]:null,o=t.fragments.length;if(!o)return this.warn("No fragments in live playlist"),0;const l=t.fragments[0].start,h=!e,d=t.alignedSliding&&n(l);if(h||!d&&!l){Ye(i,a,t);const s=t.fragments[0].start;return this.log(`Live playlist sliding: ${s.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} prev-sn: ${i?i.sn:"na"} fragments: ${o}`),s}return l}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&&n(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===Je)||(this.state=Xe)}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===l.FRAG_GAP;i&&this.fragmentTracker.fragBuffered(s,!0);const n=e.errorAction,{action:a,retryCount:o=0,retryConfig:h}=n||{};if(n&&a===Re&&h){this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition);const r=me(h,o);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${o+1}/${h.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=Je}else h&&n?(this.resetFragmentErrors(t),o<h.maxNumRetry?i||(n.resolved=!0):f.warn(`${e.details} reached or exceeded max retry (${o})`)):this.state=rs;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===ts||this.state===es){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===Kt&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==je&&(this.state=Xe)}afterBufferFlushed(t,e,s){if(!t)return;const r=BufferHelper.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,s),this.state===ss&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Xe}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=this.levels?this.levels[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(t.level),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 o=t.elementaryStreams[i];if(o){const l=o.endPTS-o.startPTS;if(l<=0)return this.warn(`Could not parse fragment ${t.sn} ${i} duration reliably (${l})`),e||!1;const h=r?0:oe(n,t,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return this.hls.trigger(a.LEVEL_PTS_UPDATED,{details:n,level:s,drift:h,type:i,frag:t,start:o.startPTS,end:o.endPTS}),!0}return e},!1))s.fragmentError=0;else if(null===(null==(i=this.transmuxer)?void 0:i.error)){const e=new Error(`Found no media in fragment ${t.sn} of level ${s.id} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.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=es,this.hls.trigger(a.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.resetTransmuxer(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function as(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}function os(){return self.SourceBuffer||self.WebKitSourceBuffer}function ls(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=dt(this.cachedData,t),this.cachedData=null);let s,r=O(t,0),i=r?r.length:0;const a=this._audioTrack,o=this._id3Track,l=r?(t=>{const e=G(t);for(let t=0;t<e.length;t++){const s=e[t];if(B(s))return W(s)}})(r):void 0,h=t.length;for((null===this.basePTS||0===this.frameIndex&&n(l))&&(this.basePTS=hs(l,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:zt,duration:Number.POSITIVE_INFINITY});i<h;){if(this.canParse(t,i)){const e=this.appendFrame(a,t,i);e?(this.frameIndex++,this.lastPTS=e.sample.pts,i+=e.length,s=i):i=h}else U(t,i)?(r=O(t,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:zt,duration:Number.POSITIVE_INFINITY}),i+=r.length,s=i):i++;if(i===h&&s!==h){const e=M(t,s);this.cachedData?this.cachedData=dt(this.cachedData,e):this.cachedData=e}}return{audioTrack:a,videoTrack:ls(),id3Track:o,textTrack:ls()}}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:ls(),id3Track:this._id3Track,textTrack:ls()}}destroy(){}}const hs=(t,e,s)=>{if(n(t))return 90*t;return 9e4*e+(s?9e4*s.baseTime/s.timescale:0)};function ds(t,e){return 255===t[e]&&240==(246&t[e+1])}function cs(t,e){return 1&t[e+1]?7:9}function us(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function fs(t,e){return e+1<t.length&&ds(t,e)}function gs(t,e){if(fs(t,e)){const s=cs(t,e);if(e+s>=t.length)return!1;const r=us(t,e);if(r<=s)return!1;const i=e+r;return i===t.length||fs(t,i)}return!1}function ms(t,e,s,r,i){if(!t.samplerate){const n=function(t,e,s,r){let i,n,h,d;const c=navigator.userAgent.toLowerCase(),u=r,g=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=1+((192&e[s+2])>>>6);const m=(60&e[s+2])>>>2;if(!(m>g.length-1))return h=(1&e[s+2])<<2,h|=(192&e[s+3])>>>6,f.log(`manifest codec:${r}, ADTS type:${i}, samplingIndex:${m}`),/firefox/i.test(c)?m>=6?(i=5,d=new Array(4),n=m-3):(i=2,d=new Array(2),n=m):-1!==c.indexOf("android")?(i=2,d=new Array(2),n=m):(i=5,d=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&m>=6?n=m-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(m>=6&&1===h||/vivaldi/i.test(c))||!r&&1===h)&&(i=2,d=new Array(2)),n=m)),d[0]=i<<3,d[0]|=(14&m)>>1,d[1]|=(1&m)<<7,d[1]|=h<<3,5===i&&(d[1]|=(14&n)>>1,d[2]=(1&n)<<7,d[2]|=8,d[3]=0),{config:d,samplerate:g[m],channelCount:h,codec:"mp4a.40."+i,manifestCodec:u};t.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+m})}(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,f.log(`parsed codec:${t.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function ps(t){return 9216e4/t}function ys(t,e,s,r,i){const n=r+i*ps(t.samplerate),a=function(t,e){const s=cs(t,e);if(e+s<=t.length){const r=us(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}}const Ts=/\/emsg[-/]ID3/i;let Es=null;const vs=[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],Ss=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ls=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],As=[0,1,1,4];function Rs(t,e,s,r,i){if(s+24>e.length)return;const n=bs(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 bs(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*vs[14*(3===s?3-r:3===r?3:4)+i-1],h=Ss[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=Ls[s][r],u=As[r],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===Es){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Es=t?parseInt(t[1]):0}return!!Es&&Es<=87&&2===r&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function Ds(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function ks(t,e){return e+1<t.length&&Ds(t,e)}function Is(t,e){if(e+1<t.length&&Ds(t,e)){const s=4,r=bs(t,e);let i=s;null!=r&&r.frameLength&&(i=r.frameLength);const n=e+i;return n===t.length||ks(t,n)}return!1}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&&f.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(),T=h(),E=l(1);0===E&&c(1),c(1),d()&&(r=h(),i=h(),n=h(),a=h());let v=[1,1];if(d()&&d()){switch(o()){case 1:v=[1,1];break;case 2:v=[12,11];break;case 3:v=[10,11];break;case 4:v=[16,11];break;case 5:v=[40,33];break;case 6:v=[24,11];break;case 7:v=[20,11];break;case 8:v=[32,11];break;case 9:v=[80,33];break;case 10:v=[18,11];break;case 11:v=[15,11];break;case 12:v=[64,33];break;case 13:v=[160,99];break;case 14:v=[4,3];break;case 15:v=[3,2];break;case 16:v=[2,1];break;case 255:v=[o()<<8|o(),o()<<8|o()]}}return{width:Math.ceil(16*(y+1)-2*r-2*i),height:(2-E)*(T+1)*16-(E?2:4)*(n+a),pixelRatio:v}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}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=gt(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._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=s}static probe(t){const e=TSDemuxer.syncOffset(t);return e>0&&f.warn("MPEG2-TS detected but first sync word found @ offset "+e),-1!==e}static syncOffset(t){const e=t.length,s=Math.min(940,t.length-188)+1;let r=0;for(;r<s;){let i=!1;for(let n=r;n<e&&71===t[n];n+=188)if(i||0!==ws(t,n)||(i=!0),i&&n+188>s)return r;r++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Z[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._avcTrack=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.avcSample=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_avcTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(t,e,s=!1,r=!1){let i;s||(this.sampleAes=null);const n=this._avcTrack,h=this._audioTrack,d=this._id3Track,c=this._txtTrack;let u=n.pid,g=n.pesData,m=h.pid,p=d.pid,y=h.pesData,T=d.pesData,E=null,v=this.pmtParsed,S=this._pmtId,L=t.length;if(this.remainderData&&(L=(t=dt(this.remainderData,t)).length,this.remainderData=null),L<188&&!r)return this.remainderData=t,{audioTrack:h,videoTrack:n,id3Track:d,textTrack:c};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]),a=ws(t,e);let o;if((48&t[e+3])>>4>1){if(o=e+5+t[e+4],o===e+188)continue}else o=e+4;switch(a){case u:r&&(g&&(i=Ms(g))&&this.parseAVCPES(n,c,i,!1),g={data:[],size:0}),g&&(g.data.push(t.subarray(o,e+188)),g.size+=e+188-o);break;case m:if(r){if(y&&(i=Ms(y)))switch(h.segmentCodec){case"aac":this.parseAACPES(h,i);break;case"mp3":this.parseMPEGPES(h,i)}y={data:[],size:0}}y&&(y.data.push(t.subarray(o,e+188)),y.size+=e+188-o);break;case p:r&&(T&&(i=Ms(T))&&this.parseID3PES(d,i),T={data:[],size:0}),T&&(T.data.push(t.subarray(o,e+188)),T.size+=e+188-o);break;case 0:r&&(o+=t[o]+1),S=this._pmtId=_s(t,o);break;case S:{r&&(o+=t[o]+1);const i=Ps(t,o,this.typeSupported,s);u=i.avc,u>0&&(n.pid=u),m=i.audio,m>0&&(h.pid=m,h.segmentCodec=i.segmentCodec),p=i.id3,p>0&&(d.pid=p),null===E||v||(f.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),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=a}}else R++;if(R>0){const t=new Error(`Found ${R} TS packet/s that do not start with 0x47`);this.observer.emit(a.ERROR,a.ERROR,{type:o.MEDIA_ERROR,details:l.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message})}n.pesData=g,h.pesData=y,d.pesData=T;const b={audioTrack:h,videoTrack:n,id3Track:d,textTrack:c};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._avcTrack,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=Ms(n))?(this.parseAVCPES(s,i,l,!0),s.pesData=null):s.pesData=n,a&&(l=Ms(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l)}e.pesData=null}else null!=a&&a.size&&f.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=Ms(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}parseAVCPES(t,e,s,r){const i=this.parseAVCNALu(t,s.data);let n,a=this.avcSample,o=!1;s.data=null,a&&i.length&&!t.audFound&&(xs(a,t),a=this.avcSample=Cs(!1,s.pts,s.dts,"")),i.forEach(r=>{switch(r.type){case 1:{n=!0,a||(a=this.avcSample=Cs(!0,s.pts,s.dts,"")),a.frame=!0;const t=r.data;if(o&&t.length>4){const e=new ExpGolomb(t).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(a.key=!0)}break}case 5:n=!0,a||(a=this.avcSample=Cs(!0,s.pts,s.dts,"")),a.key=!0,a.frame=!0;break;case 6:n=!0,ft(r.data,1,s.pts,e.samples);break;case 7:if(n=!0,o=!0,!t.sps){const e=r.data,s=new ExpGolomb(e).readSPS();t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e],t.duration=this._duration;const i=e.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}break;case 8:n=!0,t.pps||(t.pps=[r.data]);break;case 9:n=!1,t.audFound=!0,a&&xs(a,t),a=this.avcSample=Cs(!1,s.pts,s.dts,"");break;case 12:n=!0;break;default:n=!1,a&&(a.debug+="unknown NAL "+r.type+" ")}if(a&&n){a.units.push(r)}}),r&&a&&(xs(a,t),this.avcSample=null)}getLastNalUnit(t){var e;let s,r=this.avcSample;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}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(d>=0){const t={data:e.subarray(d,h-r-1),type:c};n.push(t)}else{const s=this.getLastNalUnit(t.samples);if(s&&(i&&h<=4-i&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-i)),o=h-r-1,o>0)){const t=new Uint8Array(s.data.byteLength+o);t.set(s.data,0),t.set(e.subarray(0,o),s.data.byteLength),s.data=t,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);if(s){const t=new Uint8Array(s.data.byteLength+e.byteLength);t.set(s.data,0),t.set(e,s.data.byteLength),s.data=t}}return t.naluState=r,n}parseAACPES(t,e){let s=0;const r=this.aacOverFlow;let i,n,h,d=e.data;if(r){this.aacOverFlow=null;const e=r.missing,i=r.sample.unit.byteLength;if(-1===e){const t=new Uint8Array(i+d.byteLength);t.set(r.sample.unit,0),t.set(d,i),d=t}else{const n=i-e;r.sample.unit.set(d.subarray(0,e),n),t.samples.push(r.sample),s=r.missing}}for(i=s,n=d.length;i<n-1&&!fs(d,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(f.warn("parsing error: "+t),this.observer.emit(a.ERROR,a.ERROR,{type:o.MEDIA_ERROR,details:l.FRAG_PARSING_ERROR,fatal:!1,levelRetry:e,error:s,reason:t}),!e)return}if(ms(t,this.observer,d,i,this.audioCodec),void 0!==e.pts)h=e.pts;else{if(!r)return void f.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=ps(t.samplerate);h=r.sample.pts+e}}let c,u=0;for(;i<n;){if(c=ys(t,d,i,h,u),i+=c.length,c.missing){this.aacOverFlow=c;break}for(u++;i<n-1&&!fs(d,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(ks(s,n)){const e=Rs(t,s,n,a,i);if(!e)break;n+=e.length,i++}else n++;else f.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseID3PES(t,e){if(void 0===e.pts)return void f.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=i({},e,{type:this._avcTrack?Jt:zt,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function Cs(t,e,s,r){return{key:t,frame:!1,pts:e,dts:s,units:[],debug:r,length:0}}function ws(t,e){return((31&t[e+1])<<8)+t[e+2]}function _s(t,e){return(31&t[e+10])<<8|t[e+11]}function Ps(t,e,s,r){const i={audio:-1,avc:-1,id3:-1,segmentCodec:"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=ws(t,e);switch(t[e]){case 207:if(!r){f.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===i.audio&&(i.audio=n);break;case 21:-1===i.id3&&(i.id3=n);break;case 219:if(!r){f.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===i.avc&&(i.avc=n);break;case 3:case 4:!0!==s.mpeg&&!0!==s.mp3?f.log("MPEG audio found, not supported in this browser"):-1===i.audio&&(i.audio=n,i.segmentCodec="mp3");break;case 36:f.warn("Unsupported HEVC stream type found")}e+=5+((15&t[e+3])<<8|t[e+4])}return i}function Ms(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;){const t=new Uint8Array(o[0].length+o[1].length);t.set(o[0]),t.set(o[1],o[0].length),o[0]=t,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&&(f.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}function xs(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&&f.log(t.pts+"/"+t.dts+":"+t.debug)}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 Fs=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":[],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/(Fs+1)),r=Math.floor(e%(Fs+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/(Fs+1)),r=Math.floor(e%(Fs+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 mp4a(t){const e=t.samplerate;return MP4.box(MP4.types.mp4a,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]),MP4.box(MP4.types.esds,MP4.esds(t)))}static mp3(t){const e=t.samplerate;return MP4.box(MP4.types[".mp3"],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 stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp3(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/(Fs+1)),a=Math.floor(s%(Fs+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/(Fs+1)),n=Math.floor(e%(Fs+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),s=new Uint8Array(MP4.FTYP.byteLength+e.byteLength);return s.set(MP4.FTYP),s.set(e,MP4.FTYP.byteLength),s}}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 Os(t,e,s=1,r=!1){const i=t*e*s;return r?Math.round(i):i}function Ns(t,e=!1){return Os(t,1e3,1/9e4,e)}let Us,Bs=null,$s=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.observer=t,this.config=e,this.typeSupported=s,this.ISGenerated=!1,null===Bs){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Bs=t?parseInt(t[1]):0}if(null===$s){const t=navigator.userAgent.match(/Safari\/(\d+)/i);$s=t?parseInt(t[1]):0}}destroy(){}resetTimeStamp(t){f.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){f.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){f.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(t){let e=!1;const s=t.reduce((t,s)=>{const r=s.pts-t;return r<-4294967296?(e=!0,Gs(t,s.pts)):r>0?t:s.pts},t[0].pts);return e&&f.debug("PTS rollover detected"),s}remux(t,e,s,r,i,n,a,o){let l,h,d,c,u,g,m=i,p=i;const y=t.pid>-1,T=e.pid>-1,E=e.samples.length,v=t.samples.length>0,S=a&&E>0||E>1;if((!y||v)&&(!T||S)||this.ISGenerated||a){this.ISGenerated||(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(g=!0,a>0){f.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,p+=(e.samples[0].pts-t)/e.inputTimeScale,r=p}else-1===a&&(f.warn(`[mp4-remuxer]: No keyframe found out of ${E} video samples`),g=!1);if(this.ISGenerated){if(v&&S){const s=this.getVideoStartPts(e.samples),r=(Gs(t.samples[0].pts,s)-s)/e.inputTimeScale;m+=Math.max(0,r),p+=Math.max(0,-r)}if(v){if(t.samplerate||(f.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,i,n)),h=this.remuxAudio(t,m,this.isAudioContiguous,n,T||S||o===Kt?p:void 0),S){const r=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(f.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,i,n)),l=this.remuxVideo(e,p,s,r)}}else S&&(l=this.remuxVideo(e,p,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=Ks(s,i,this._initPTS,this._initDTS)),r.samples.length&&(c=Hs(r,i,this._initPTS))),{audio:h,video:l,initSegment:d,independent:g,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")}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&&(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,Gs(n[0].dts,t)-e),h=Math.min(h,t-e)}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 n=t.inputTimeScale,h=t.samples,d=[],c=h.length,u=this._initPTS;let g,m,p=this.nextAvcDts,y=8,T=this.videoSampleDuration,E=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,S=!1;if(!s||null===p){p=e*n-(h[0].pts-Gs(h[0].dts,h[0].pts))}const L=u.baseTime*n/u.timescale;for(let t=0;t<c;t++){const e=h[t];e.pts=Gs(e.pts-L,p),e.dts=Gs(e.dts-L,p),e.dts<h[t>0?t-1:t].dts&&(S=!0)}S&&h.sort((function(t,e){const s=t.dts-e.dts,r=t.pts-e.pts;return s||r})),g=h[0].dts,m=h[h.length-1].dts;const A=m-g,R=A?Math.round(A/(c-1)):T||t.inputTimeScale/30;if(s){const t=g-p,e=t>R,s=t<-1;if((e||s)&&(e?f.warn(`AVC: ${Ns(t,!0)} ms (${t}dts) hole between fragments detected, filling it`):f.warn(`AVC: ${Ns(-t,!0)} ms (${t}dts) overlapping between fragments detected`),!s||p>h[0].pts)){g=p;const e=h[0].pts-t;h[0].dts=g,h[0].pts=e,f.log(`Video: First PTS/DTS adjusted: ${Ns(e,!0)}/${Ns(g,!0)}, delta: ${Ns(t,!0)} ms`)}}g=Math.max(0,g);let b=0,D=0;for(let t=0;t<c;t++){const e=h[t],s=e.units,r=s.length;let i=0;for(let t=0;t<r;t++)i+=s[t].data.length;D+=i,b+=r,e.length=i,e.dts=Math.max(e.dts,g),E=Math.min(e.pts,E),v=Math.max(e.pts,v)}m=h[c-1].dts;const k=D+4*b+8;let I;try{I=new Uint8Array(k)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:o.MUX_ERROR,details:l.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:k,reason:"fail allocating video mdat "+k})}const C=new DataView(I.buffer);C.setUint32(0,k),I.set(MP4.types.mdat,4);let w=!1,_=Number.POSITIVE_INFINITY,P=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,x=Number.NEGATIVE_INFINITY;for(let t=0;t<c;t++){const e=h[t],s=e.units;let i,a=0;for(let t=0,e=s.length;t<e;t++){const e=s[t],r=e.data,i=e.data.byteLength;C.setUint32(y,i),y+=4,I.set(r,y),y+=i,a+=4+i}if(t<c-1)T=h[t+1].dts-e.dts,i=h[t+1].pts-e.pts;else{const s=this.config,a=t>0?e.dts-h[t-1].dts:R;if(i=t>0?e.pts-h[t-1].pts:R,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(s.maxBufferHole*n),i=(r?E+r*n:this.nextAudioPts)-e.pts;i>t?(T=i-a,T<0?T=a:w=!0,f.log(`[mp4-remuxer]: It is approximately ${i/90} ms to the next segment; using duration ${T/90} ms for the last video frame.`)):T=a}else T=a}const o=Math.round(e.pts-e.dts);_=Math.min(_,T),M=Math.max(M,T),P=Math.min(P,i),x=Math.max(x,i),d.push(new Mp4Sample(e.key,T,a,o))}if(d.length)if(Bs){if(Bs<70){const t=d[0].flags;t.dependsOn=2,t.isNonSync=0}}else if($s&&x-P<M-_&&R/M<.025&&0===d[0].cts){f.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=g;for(let e=0,s=d.length;e<s;e++){const r=t+d[e].duration,i=t+d[e].cts;if(e<s-1){const t=r+d[e+1].cts;d[e].duration=t-i}else d[e].duration=e?d[e-1].duration:R;d[e].cts=0,t=r}}T=w||!T?R:T,this.nextAvcDts=p=m+T,this.videoSampleDuration=T,this.isVideoContiguous=!0;const F={data1:MP4.moof(t.sequenceNumber++,g,i({},t,{samples:d})),data2:I,startPTS:E/n,endPTS:(v+T)/n,startDTS:g/n,endDTS:p/n,type:"video",hasAudio:!1,hasVideo:!0,nb:d.length,dropped:t.dropped};return t.samples=[],t.dropped=0,F}remuxAudio(t,e,s,r,n){const h=t.inputTimeScale,d=h/(t.samplerate?t.samplerate:h),c="aac"===t.segmentCodec?1024:1152,u=c*d,g=this._initPTS,m="mp3"===t.segmentCodec&&this.typeSupported.mpeg,p=[],y=void 0!==n;let T=t.samples,E=m?0:8,v=this.nextAudioPts||-1;const S=e*h,L=g.baseTime*h/g.timescale;if(this.isAudioContiguous=s=s||T.length&&v>0&&(r&&Math.abs(S-v)<9e3||Math.abs(Gs(T[0].pts-L,S)-v)<20*u),T.forEach((function(t){t.pts=Gs(t.pts-L,S)})),!s||v<0){if(T=T.filter(t=>t.pts>=0),!T.length)return;v=0===n?0:r&&!y?Math.max(0,S):T[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,r=v;s<T.length;s++){const i=T[s],n=i.pts,a=n-r,o=Math.abs(1e3*a/h);if(a<=-e*u&&y)0===s&&(f.warn(`Audio frame @ ${(n/h).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*a/h)} ms.`),this.nextAudioPts=v=r=n);else if(a>=e*u&&o<1e4&&y){let e=Math.round(a/u);r=n-e*u,r<0&&(e--,r+=u),0===s&&(this.nextAudioPts=v=r),f.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(r/h).toFixed(3)}s due to ${Math.round(1e3*a/h)} 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||(f.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=i.unit.subarray()),T.splice(s,0,{unit:n,pts:e}),r+=u,s++}}i.pts=r,r+=u}}let A,R=null,b=null,D=0,k=T.length;for(;k--;)D+=T[k].unit.byteLength;for(let e=0,r=T.length;e<r;e++){const r=T[e],i=r.unit;let n=r.pts;if(null!==b){p[e-1].duration=Math.round((n-b)/d)}else{if(s&&"aac"===t.segmentCodec&&(n=v),R=n,!(D>0))return;D+=E;try{A=new Uint8Array(D)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:o.MUX_ERROR,details:l.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:D,reason:"fail allocating audio mdat "+D})}if(!m){new DataView(A.buffer).setUint32(0,D),A.set(MP4.types.mdat,4)}}A.set(i,E);const h=i.byteLength;E+=h,p.push(new Mp4Sample(!0,c,h,0)),b=n}const I=p.length;if(!I)return;const C=p[p.length-1];this.nextAudioPts=v=b+d*C.duration;const w=m?new Uint8Array(0):MP4.moof(t.sequenceNumber++,R/d,i({},t,{samples:p}));t.samples=[];const _=R/h,P=v/h,M={data1:w,data2:A,startPTS:_,endPTS:P,startDTS:_,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};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),g=AAC.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(f.warn("[mp4-remuxer]: remux empty Audio"),!g)return void f.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const m=[];for(let t=0;t<u;t++){const e=h+t*c;m.push({unit:g,pts:e,dts:e})}return t.samples=m,this.remuxAudio(t,e,s,!1)}}function Gs(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 Ks(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=Gs(i.pts-9e4*s.baseTime/s.timescale,e*n)/n,i.dts=Gs(i.dts-9e4*r.baseTime/r.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Hs(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=Gs(r.pts-9e4*s.baseTime/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=new Mp4SampleFlags(t)}}class Mp4SampleFlags{constructor(t){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1}}function Vs(t,e){const s=null==t?void 0:t.codec;return s&&s.length>4?s:"hvc1"===s||"hev1"===s?"hvc1.1.c.L120.90":"av01"===s?"av01.0.04M.08":"avc1"===s||e===T?"avc1.42e01e":"mp4a.40.5"}try{Us=self.performance.now.bind(self.performance)}catch(t){f.debug("Unable to use Performance API on this environment"),Us="undefined"!=typeof self&&self.Date.now}const Ys=[{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=ls("video",1),n=this.audioTrack=ls("audio",1),a=this.txtTrack=ls("text",1);if(this.id3Track=ls("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=ot(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=Z.text,i.sampleDuration=0,i.duration=n.duration=r}resetContiguity(){}static probe(t){return nt(t=t.length>16384?t.subarray(0,16384):t,["moof"]).length>0}demux(t,e){this.timeOffset=e;let s=t;const r=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=dt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=nt(t,["moof"]);if(!s)return e;if(s.length<2)return e.remainder=t,e;const r=s[s.length-1];return e.valid=M(t,0,r.byteOffset-8),e.remainder=M(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=ct(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=ct(t,e),{videoTrack:e,audioTrack:ls(),id3Track:r,textTrack:ls()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const r=nt(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,h=0;if(0===e){for(;"\0"!==tt(t.subarray(h,h+1));)s+=tt(t.subarray(h,h+1)),h+=1;for(s+=tt(t.subarray(h,h+1)),h+=1;"\0"!==tt(t.subarray(h,h+1));)r+=tt(t.subarray(h,h+1)),h+=1;r+=tt(t.subarray(h,h+1)),h+=1,i=st(t,12),n=st(t,16),o=st(t,20),l=st(t,24),h=28}else if(1===e){h+=4,i=st(t,h),h+=4;const e=st(t,h);h+=4;const n=st(t,h);for(h+=4,a=2**32*e+n,Number.isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,f.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=st(t,h),h+=4,l=st(t,h),h+=4;"\0"!==tt(t.subarray(h,h+1));)s+=tt(t.subarray(h,h+1)),h+=1;for(s+=tt(t.subarray(h,h+1)),h+=1;"\0"!==tt(t.subarray(h,h+1));)r+=tt(t.subarray(h,h+1)),h+=1;r+=tt(t.subarray(h,h+1)),h+=1}return{schemeIdUri:s,value:r,timeScale:i,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(h,t.byteLength)}}(t);if(Ts.test(r.schemeIdUri)){const t=n(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 a=r.payload;s.samples.push({data:a,len:a.byteLength,dts:t,pts:t,type:Jt,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){nt(t,["moov","trak"]).forEach(t=>{const e=nt(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=nt(e,["enca"]);const i=r.length>0;i||(r=nt(e,["encv"])),r.forEach(t=>{nt(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)||(f.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${z(t)} -> ${z(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=ot(t);e||(e=Vs(r.audio,y)),s||(s=Vs(r.video,T));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"}:f.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=i}remux(t,e,s,r,i,a){var o,l;let{initPTS:h,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};n(d)||(d=this.lastEndTime=i||0);const u=e.samples;if(null==u||!u.length)return c;const g={initPTS:void 0,timescale:1};let m=this.initData;if(null!=(o=m)&&o.length||(this.generateInitSegment(u),m=this.initData),null==(l=m)||!l.length)return f.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const p=function(t,e){return nt(e,["moof","traf"]).reduce((e,s)=>{const r=nt(s,["tfdt"])[0],i=r[0],n=nt(s,["tfhd"]).reduce((e,s)=>{const n=st(s,4),a=t[n];if(a){let t=st(r,4);if(1===i){if(t===Q)return f.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=Q+1,t+=st(r,8)}const s=t/(a.timescale||9e4);if(isFinite(s)&&(null===e||s<e))return s}return e},null);return null!==n&&isFinite(n)&&(null===e||n<e)?n:e},null)}(m,u),E=null===p?i:p;(function(t,e,s){if(null===t)return!0;const r=e-t.baseTime/t.timescale;return r<0&&Math.abs(r-s)>1}(h,E,i)||g.timescale!==h.timescale&&a)&&(g.initPTS=E-i,this.initPTS=h={baseTime:g.initPTS,timescale:1});const v=function(t,e){let s=0,r=0,i=0;const n=nt(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=nt(a,["tfhd"])[0],l=e[st(o,4)];if(!l)continue;const h=l.default,d=st(o,0)|(null==h?void 0:h.flags);let c=null==h?void 0:h.duration;8&d&&(c=st(o,2&d?12:8));const u=l.timescale||9e4,f=nt(a,["trun"]);for(let t=0;t<f.length;t++){if(s=ht(f[t]),!s&&c){s=c*st(f[t],4)}l.type===T?r+=s/u:l.type===y&&(i+=s/u)}}if(0===r&&0===i){let e=0;const s=nt(t,["sidx"]);for(let t=0;t<s.length;t++){const r=at(s[t]);null!=r&&r.references&&(e+=r.references.reduce((t,e)=>t+e.info.duration||0,0))}return e}return r||i}(u,m),S=t?E-h.baseTime/h.timescale:d,L=S+v;!function(t,e,s){nt(e,["moof","traf"]).forEach(e=>{nt(e,["tfhd"]).forEach(r=>{const i=st(r,4),n=t[i];if(!n)return;const a=n.timescale||9e4;nt(e,["tfdt"]).forEach(t=>{const e=t[0];let r=st(t,4);if(0===e)r-=s*a,r=Math.max(r,0),it(t,4,r);else{r*=Math.pow(2,32),r+=st(t,8),r-=s*a,r=Math.max(r,0);const e=Math.floor(r/(Q+1)),i=Math.floor(r%(Q+1));it(t,4,e),it(t,8,i)}})})})}(m,u,h.baseTime/h.timescale),v>0?this.lastEndTime=L:(f.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const A=!!m.audio,R=!!m.video;let b="";A&&(b+="audio"),R&&(b+="video");const D={data1:u,startPTS:S,startDTS:S,endPTS:L,endDTS:L,type:b,hasAudio:A,hasVideo:R,nb:1,dropped:0};return c.audio="audio"===D.type?D:void 0,c.video="audio"!==D.type?D:void 0,c.initSegment=g,c.id3=Ks(s,i,h,h),r.samples.length&&(c.text=Hs(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;let e=(O(t,0)||[]).length;for(let s=t.length;e<s;e++)if(gs(t,e))return f.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)&&ds(t,e)&&us(t,e)<=t.length-e}(t,e)}appendFrame(t,e,s){ms(t,this.observer,e,s,t.manifestCodec);const r=ys(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;let e=(O(t,0)||[]).length;for(let s=t.length;e<s;e++)if(Is(t,e))return f.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return Ds(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,s){if(null!==this.basePTS)return Rs(t,e,s,this.basePTS,this.frameIndex)}},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=Us();let n=new Uint8Array(t);const{currentTransmuxState:h,transmuxConfig:d}=this;r&&(this.currentTransmuxState=r);const{contiguous:c,discontinuity:u,trackSwitch:g,accurateTimeOffset:m,timeOffset:p,initSegmentChange:y}=r||h,{audioCodec:T,videoCodec:E,defaultInitPts:v,duration:S,initSegmentData:L}=d,A=function(t,e){let s=null;t.byteLength>0&&null!=e&&null!=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=Us(),Ws(s);n=new Uint8Array(e)}}const R=this.needsProbing(u,g);if(R){const t=this.configureTransmuxer(n);if(t)return f.warn("[transmuxer] "+t.message),this.observer.emit(a.ERROR,a.ERROR,{type:o.MEDIA_ERROR,details:l.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),i.executeEnd=Us(),Ws(s)}(u||g||y||R)&&this.resetInitSegment(L,T,E,S,e),(u||y||R)&&this.resetInitialTimestamp(v),c||this.resetContiguity();const b=this.transmux(n,A,p,m,s),D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,i.executeEnd=Us(),b}flush(t){const e=t.transmuxing;e.executeStart=Us();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=Us(),[Ws(t)];const h=o.flush(a);return qs(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;f.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=Us()}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=Ys.length;e<s;e++)if(Ys[e].demux.probe(t)){n=Ys[e];break}if(!n)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=n.remux,h=n.demux;o&&o instanceof l||(this.remuxer=new l(s,e,r,i)),a&&a instanceof h||(this.demuxer=new h(s,e,r),this.probe=h.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Decrypter(this.config)),t}}const Ws=t=>({remuxResult:{},chunkMeta:t});function qs(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 js={};!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}({get exports(){return js},set exports(t){js=t}});const Xs=as()||{isTypeSupported:()=>!1};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===a.ERROR&&(this.error=e.error),this.hls.trigger(t,e)};this.observer=new js,this.observer.on(a.FRAG_DECRYPTED,n),this.observer.on(a.ERROR,n);const h={mp4:Xs.isTypeSupported("video/mp4"),mpeg:Xs.isTypeSupported("audio/mpeg"),mp3:Xs.isTypeSupported('audio/mp4; codecs="mp3"')},d=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(i.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{i.workerPath?(f.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)):(f.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,f.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(a.ERROR,{type:o.OTHER_ERROR,details:l.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:s})},t.postMessage({cmd:"init",typeSupported:h,vendor:d,id:e,config:JSON.stringify(i)})}catch(t){f.warn(`Error setting up "${e}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,h,i,d,e)}return}}this.transmuxer=new Transmuxer(this.observer,h,i,d,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,g=n?n.start:i.start,m=i.decryptdata,p=this.frag,y=!(p&&i.cc===p.cc),T=!(p&&l.level===p.level),E=p?l.sn-p.sn:-1,v=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),L=!T&&(1===E||0===E&&(1===v||S&&v<=0)),A=self.performance.now();(T||E||0===i.stats.parsing.start)&&(i.stats.parsing.start=A),!n||!v&&L||(n.stats.parsing.start=A);const R=!(p&&(null==(d=i.initSegment)?void 0:d.url)===(null==(c=p.initSegment)?void 0:c.url)),b=new TransmuxState(y,L,o,T,g,R);if(!L||y||R){f.log(`[transmuxer-interface, ${i.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${y}\n trackSwitch: ${T}\n contiguous: ${L}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\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:m,chunkMeta:l,state:b},t instanceof ArrayBuffer?[t]:[]);else if(u){const e=u.push(t,m,l,b);qs(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);qs(s)||e.async?(qs(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(a.ERROR,{type:o.MEDIA_ERROR,details:l.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":f[e.data.logType]&&f[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)}}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,null!==i){if(this.stallReported){const t=self.performance.now()-i;f.warn(`playback not stuck anymore @${n}, after ${Math.round(t)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(l||o)return void(this.stalled=null);if(r.paused&&!a||r.ended||0===r.playbackRate||!BufferHelper.getBuffered(r).length)return;const h=BufferHelper.bufferInfo(r,n,0),d=h.len>0,c=h.nextStart||0;if(!d&&!c)return;if(a){const t=h.len>2,s=!c||e&&e.start<=n||c-n>2&&!this.fragmentTracker.getPartialFragment(n);if(t||s)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var u;const t=Math.max(c,h.start||0)-n,e=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,s=(null==e||null==(u=e.details)?void 0:u.live)?2*e.details.targetduration:2,r=this.fragmentTracker.getPartialFragment(n);if(t>0&&(t<=s||r))return void this._trySkipBufferHole(r)}const g=self.performance.now();if(null===i)return void(this.stalled=g);const m=g-i;if(!a&&m>=250&&(this._reportStall(h),!this.media))return;const p=BufferHelper.bufferInfo(r,n,s.maxBufferHole);this._tryFixBufferStall(p,m)}_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&&(f.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)})`);f.warn(r.message),e.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.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),h=i<n.start?n.start:n.nextStart;if(h){const d=n.len<=e.maxBufferHole,c=n.len>0&&n.len<1&&r.readyState<3,u=h-i;if(u>0&&(d||c)){if(u>e.maxBufferHole){const{fragmentTracker:e}=this;let s=!1;if(0===i){const t=e.getAppendedFrag(0,Gt);t&&h<t.end&&(s=!0)}if(!s){const s=t||e.getAppendedFrag(i,Gt);if(s){let t=!1,r=s.end;for(;r<h;){const s=e.getPartialFragment(r);if(!s){t=!0;break}r+=s.duration}if(t)return 0}}}const n=Math.max(h+.05,i+.1);if(f.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(a.ERROR,{type:o.MEDIA_ERROR,details:l.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,h=new Error(`Nudging 'currentTime' from ${i} to ${n}`);f.warn(h.message),s.currentTime=n,e.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.BUFFER_NUDGE_ON_STALL,error:h,fatal:!1})}else{const s=new Error(`Playhead still not moving while enough data buffered @${i} after ${t.nudgeMaxRetry} nudges`);f.error(s.message),e.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.BUFFER_STALLED_ERROR,error:s,fatal:!0})}}}class StreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"[stream-controller]",Gt),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(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(a.ERROR,this.onError,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(a.ERROR,this.onError,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}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.nextAutoLevel),this.level=s.nextLoadLevel=t,this.loadedmetadata=!1}e>0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=Xe,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=je}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case ns:{var t;const{levels:e,level:s}=this,r=null==e||null==(t=e[s])?void 0:t.details;if(r&&(!r.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(r))break;this.state=Xe;break}break}case Je:{var e;const t=self.performance.now(),s=this.retryDate;(!s||t>=s||null!=(e=this.media)&&e.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=Xe)}}this.state===Xe&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:r}=this,{config:i,nextLoadLevel:n}=t;if(null===e||!r&&(this.startFragRequested||!i.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;if(null==s||!s[n])return;const o=s[n],l=this.getMainFwdBufferInfo();if(null===l)return;const h=this.getLevelDetails();if(h&&this._streamEnded(l,h)){const t={};return this.altAudio&&(t.type="video"),this.hls.trigger(a.BUFFER_EOS,t),void(this.state=ss)}t.loadLevel!==n&&-1===t.manualLevel&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=t.nextLoadLevel=n;const d=o.details;if(!d||this.state===ns||d.live&&this.levelLastLoaded!==n)return this.level=n,void(this.state=ns);const c=l.len,u=this.getMaxBufferLength(o.maxBitrate);if(c>=u)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:l.end;let g=this.getNextFragment(f,d);if(this.couldBacktrack&&!this.fragPrevious&&g&&"initSegment"!==g.sn&&this.fragmentTracker.getState(g)!==Fe){var m;const t=(null!=(m=this.backtrackFragment)?m:g).sn-d.startSN,e=d.fragments[t-1];e&&g.cc===e.cc&&(g=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,f)){if(!g.gap){const t=this.audioOnly&&!this.altAudio?y:T,e=(t===T?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,Gt)}g=this.getNextFragmentLoopLoading(g,d,l,Gt,u)}g&&(!g.initSegment||g.initSegment.data||this.bitrateTest||(g=g.initSegment),this.loadFragment(g,o,f))}loadFragment(t,e,s){const r=this.fragmentTracker.getState(t);this.fragCurrent=t,r===Pe?"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)}getAppendedFrag(t){const e=this.fragmentTracker.getAppendedFrag(t,Gt);return e&&"fragment"in e?e.fragment:e}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Gt)}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);if(r&&r.start>1&&this.flushMainBuffer(0,r.start-1),!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 i=this.getBufferedFrag(e.currentTime+s);if(i){const t=this.followingBufferedFrag(i);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,r=Math.max(i.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,.5*s),.75*s));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 ze:case Qe:case Je:case ts:case es:this.state=Xe}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;n(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(a.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null,this.backtrackFragment=null}onManifestParsed(t,e){let s,r=!1,i=!1;e.levels.forEach(t=>{s=t.audioCodec,s&&(-1!==s.indexOf("mp4a.40.2")&&(r=!0),-1!==s.indexOf("mp4a.40.5")&&(i=!0))}),this.audioCodecSwitch=r&&i&&!function(){var t;const e=os();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!==Xe)return;const r=s[e.level];(!r.details||r.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(r.details))&&(this.state=ns)}onLevelLoaded(t,e){var s;const{levels:r}=this,i=e.level,n=e.details,o=n.totalduration;if(!r)return void this.warn("Levels were reset while loading level "+i);this.log(`Level ${i} loaded [${n.startSN},${n.endSN}], cc [${n.startCC}, ${n.endCC}] duration:${o}`);const l=r[i],h=this.fragCurrent;!h||this.state!==Qe&&this.state!==Je||h.level===e.level&&h.urlId===l.urlId||!h.loader||this.abortCurrentFrag();let d=0;if(n.live||null!=(s=l.details)&&s.live){if(n.fragments[0]||(n.deltaUpdateFailed=!0),n.deltaUpdateFailed)return;d=this.alignPlaylists(n,l.details)}if(l.details=n,this.levelLastLoaded=i,this.hls.trigger(a.LEVEL_UPDATED,{details:n,level:i}),this.state===ns){if(this.waitForCdnTuneIn(n))return;this.state=Xe}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,d),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,Gt,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(a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(a.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!==Gt)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===es&&(this.state=Xe));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=rs;else switch(e.details){case l.FRAG_GAP:case l.FRAG_PARSING_ERROR:case l.FRAG_DECRYPT_ERROR:case l.FRAG_LOAD_ERROR:case l.FRAG_LOAD_TIMEOUT:case l.KEY_LOAD_ERROR:case l.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Gt,e);break;case l.LEVEL_LOAD_ERROR:case l.LEVEL_LOAD_TIMEOUT:case l.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==ns||(null==(s=e.context)?void 0:s.type)!==Ut||(this.state=Xe);break;case l.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case l.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!==Xe?this.fragCurrent:null;e.poll(this.lastCurrentTime,t)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=Xe,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==y||this.audioOnly&&!this.altAudio){const t=(e===T?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(t,e,Gt)}}onLevelsUpdated(t,e){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=Xe,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(a.FRAG_LOADED,s),t.bitrateTest=!1})}_handleTransmuxComplete(t){var e;const s="main",{hls:r}=this,{remuxResult:i,chunkMeta:o}=t,l=this.getCurrentContext(o);if(!l)return void this.resetWhenMissingContext(o);const{frag:h,part:d,level:c}=l,{video:u,text:f,id3:g,initSegment:m}=i,{details:p}=c,T=this.altAudio?void 0:i.audio;if(this.fragContextChanged(h))this.fragmentTracker.removeFragment(h);else{if(this.state=ts,m){m.tracks&&(this._bufferInitSegment(c,m.tracks,h,o),r.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:h,id:s,tracks:m.tracks}));const t=m.initPTS,e=m.timescale;n(t)&&(this.initPTS[h.cc]={baseTime:t,timescale:e},r.trigger(a.INIT_PTS_FOUND,{frag:h,id:s,initPTS:t,timescale:e}))}if(u&&!1!==i.independent){if(p){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=u;if(d)d.elementaryStreams[u.type]={startPTS:t,endPTS:e,startDTS:s,endDTS:r};else if(u.firstKeyFrame&&u.independent&&1===o.id&&(this.couldBacktrack=!0),u.dropped&&u.independent){const s=this.getMainFwdBufferInfo();if((s?s.end:this.getLoadPosition())+this.config.maxBufferHole<(u.firstKeyFramePTS?u.firstKeyFramePTS:t)-this.config.maxBufferHole)return void this.backtrack(h);h.setElementaryStreamInfo(u.type,h.start,e,h.start,r,!0)}h.setElementaryStreamInfo(u.type,t,e,s,r),this.backtrackFragment&&(this.backtrackFragment=h),this.bufferFragmentData(u,h,d,o)}}else if(!1===i.independent)return void this.backtrack(h);if(T){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=T;d&&(d.elementaryStreams[y]={startPTS:t,endPTS:e,startDTS:s,endDTS:r}),h.setElementaryStreamInfo(y,t,e,s,r),this.bufferFragmentData(T,h,d,o)}if(p&&null!=g&&null!=(e=g.samples)&&e.length){const t={id:s,frag:h,details:p,samples:g.samples};r.trigger(a.FRAG_PARSING_METADATA,t)}if(p&&f){const t={id:s,frag:h,details:p,samples:f.samples};r.trigger(a.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,s,r){if(this.state!==ts)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:i,video:n,audiovideo:o}=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")),-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}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.attrs.CODECS||""}/${o.codec}]`),this.hls.trigger(a.BUFFER_CODECS,e),Object.keys(e).forEach(t=>{const i=e[t].initSegment;null!=i&&i.byteLength&&this.hls.trigger(a.BUFFER_APPENDING,{type:t,data:i,frag:s,part:null,chunkMeta:r,parent:s.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Gt)}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=Xe}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&&e.urlId===t.urlId||(this.fragPlaying=e,this.hls.trigger(a.FRAG_CHANGED,{frag:e}),t&&t.level===s||this.hls.trigger(a.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&&n(e)&&n(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 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(){}}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 zs(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!Qs(t[s].attrs,e[s].attrs))return!1;return!0}function Qs(t,e){const s=t["STABLE-RENDITION-ID"];return s?s===e["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some(s=>t[s]!==e[s])}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)}}}function Js(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}class BufferOperationQueue{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e){const s=this.queues[e];s.push(t),1===s.length&&this.buffers[e]&&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{buffers:e,queues:s}=this,r=e[t],i=s[t];if(i.length){const e=i[0];try{e.execute()}catch(s){f.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),e.onError(s),null!=r&&r.updating||(i.shift(),this.executeNext(t))}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Zs=as(),tr=/([ha]vc.)(?:\.[^.,]+)+/;const er={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},sr=function(t){let e=t;return er.hasOwnProperty(t)&&(e=er[t]),String.fromCharCode(e)},rr={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},ir={17:2,18:4,21:6,22:8,23:10,19:13,20:15},nr={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},ar={25:2,26:4,29:6,30:8,31:10,27:13,28:15},or=["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;f.log(`${this.time} [${t}] ${s}`)}}}const lr=function(t){const e=[];for(let s=0;s<t.length;s++)e.push(t[s].toString(16));return e};class PenState{constructor(t,e,s,r,i){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=t||"white",this.underline=e||!1,this.italics=s||!1,this.background=r||"black",this.flash=i||!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(t,e,s,r,i,n){this.uchar=void 0,this.penState=void 0,this.uchar=t||" ",this.penState=new PenState(e,s,r,i,n)}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=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let t=0;t<100;t++)this.chars.push(new StyledUnicodeChar);this.logger=t,this.pos=0,this.currPenState=new PenState}equals(t){let e=!0;for(let s=0;s<100;s++)if(!this.chars[s].equals(t.chars[s])){e=!1;break}return e}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=sr(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=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let e=0;e<15;e++)this.rows.push(new Row(t));this.logger=t,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}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(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=void 0,this.logger=void 0;const r=new CaptionsLogger;this.channels=[null,new Cea608Channel(t,e,r),new Cea608Channel(t+1,s,r)],this.cmdHistory={a:null,b:null},this.logger=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,"["+lr([e[t],e[t+1]])+"] -> ("+lr([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 "+lr([r,i])+" orig: "+lr([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(dr(t,e,s))return hr(null,null,s),this.logger.log(3,"Repeated command ("+lr([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 ("+lr([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(dr(t,e,r))return hr(null,null,r),!0;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?rr[t]:nr[t]:1===i?ir[t]:ar[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 '"+sr(t)+"' in channel "+s),r=[t]}else t>=32&&t<=127&&(r=0===e?[t]:[t,e]);if(r){const s=lr(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=or[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 dr(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 cr=function(){if("undefined"!=typeof self&&self.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",T="start",E=50,v="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 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,"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 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,"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 ur(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 fr(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 gr=new cr(0,0,""),mr="middle"===gr.align?"middle":"center";function pr(t,e,s){const r=t;function i(){const e=ur(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;fr(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",mr,"end"]);break;case"position":i=e.split(","),r.percent(t,i[0]),2===i.length&&r.alt("positionAlign",i[1],["start",mr,"end","line-left","line-right","auto"]);break;case"size":r.percent(t,e);break;case"align":r.alt(t,e,["start",mr,"end","left","right"])}}),/:/,/\s/),e.region=r.get("region",null),e.vertical=r.get("vertical","");let i=r.get("line","auto");"auto"===i&&-1===gr.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",mr);let n=r.get("position","auto");"auto"===n&&50===gr.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function yr(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=yr(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)?fr(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 cr(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{pr(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 Tr=/\r\n|\n\r|\n|\r/g,Er=function(t,e,s=0){return t.slice(s,s+e.length)===e},vr=function(t){let e=5381,s=t.length;for(;s;)e=33*e^t.charCodeAt(--s);return(e>>>0).toString()};function Sr(t,e,s){return vr(t.toString())+vr(e.toString())+vr(s)}function Lr(t,e,s,r,i,a,o){const l=new VTTParser,h=q(new Uint8Array(t)).trim().replace(Tr,"\n").split("\n"),d=[],c=function(t,e=1){return Os(t,9e4,1/e)}(e.baseTime,e.timescale);let u,f="00:00.000",g=0,m=0,p=!0;l.oncue=function(t){const e=s[r];let n=s.ccOffset;const a=(g-c)/9e4;null!=e&&e.new&&(void 0!==m?n=s.ccOffset=e.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,a)),a&&(n=a-s.presentationOffset);const o=t.endTime-t.startTime,l=Gs(9e4*(t.startTime+n-m),9e4*i)/9e4;t.startTime=Math.max(l,0),t.endTime=Math.max(l+o,0);const h=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(h)),t.id||(t.id=Sr(t.startTime,t.endTime,h)),t.endTime>0&&d.push(t)},l.onparsingerror=function(t){u=t},l.onflush=function(){u?o(u):a(d)},h.forEach(t=>{if(p){if(Er(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach(t=>{Er(t,"LOCAL:")?f=t.slice(6):Er(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(!(n(e)&&n(s)&&n(r)&&n(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)}l.parse(t+"\n")}),l.flush()}const Ar=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Rr=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,br={left:"start",center:"center",right:"end",start:"start",end:"end"};function Dr(t,e,s,r){const n=nt(new Uint8Array(t),["mdat"]);if(0===n.length)return void r(new Error("Could not parse IMSC1 mdat"));const a=n.map(t=>q(t)),o=function(t,e,s=1,r=!1){return Os(t,e,1/s,r)}(e.baseTime,1,e.timescale);try{a.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 n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((t,e)=>(t[e]=r.getAttribute("ttp:"+e)||n[e],t),{}),o="preserve"!==r.getAttribute("xml:space"),l=Ir(kr(r,"styling","style")),h=Ir(kr(r,"layout","region")),d=kr(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,o);if(!s||!t.hasAttribute("begin"))return null;const r=_r(t.getAttribute("begin"),a),n=_r(t.getAttribute("dur"),a);let d=_r(t.getAttribute("end"),a);if(null===r)throw wr(t);if(null===d){if(null===n)throw wr(t);d=r+n}const c=new cr(r-e,d-e,s);c.id=Sr(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=Cr(e,r,n)||Cr(t,r,n)||Cr(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=br[f];t&&(c.lineAlign=t),c.align=f}return i(c,u),c}).filter(t=>null!==t)}(t,o)))}catch(t){r(t)}}function kr(t,e,s){const r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(s)):[]}function Ir(t){return t.reduce((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t},{})}function Cr(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function wr(t){return new Error("Could not parse ttml timestamp "+t)}function _r(t,e){if(!t)return null;let s=ur(t);return null===s&&(Ar.test(t)?s=function(t,e){const s=Ar.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):Rr.test(t)&&(s=function(t,e){const s=Rr.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 Pr(t,e){return!!t&&t.label===e.name&&!(t.textTrack1||t.textTrack2)}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.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(a.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(a.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.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}onManifestParsed(t,e){const s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const t=this.hls.levels;if(t.length){const e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),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,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),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;for(let a=0;a<t.length;a+=1){const o=t[a];if((o.width>=e||o.height>=s)&&(i=o,!(n=t[a+1])||i.width!==n.width||i.height!==n.height)){r=a;break}}var i,n;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=f.debug.bind(f,"[eme]"),this.log=f.log.bind(f,"[eme]"),this.warn=f.warn.bind(f,"[eme]"),this.error=f.error.bind(f,"[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(a.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(a.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(a.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(a.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(a.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,r=e[t];if(r)return r.licenseUrl;if(t===A.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:o.KEY_SYSTEM_ERROR,details:l.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===P&&"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 A.FAIRPLAY:i=["cenc","sinf"];break;case A.WIDEVINE:case A.PLAYREADY:i=["cenc"];break;case A.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||"not-allowed",distinctiveIdentifier:r.distinctiveIdentifier||"not-allowed",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: ${z(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 z(t.keyId)}updateKeySession(t,e){var s;const r=t.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${z((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=_(this.config),i=t.map(I).filter(t=>!!t&&-1!==r.indexOf(t));return this.getKeySystemSelectionPromise(i).then(({keySystem:t})=>{const r=w(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(a.ERROR,t.data):this.hls.trigger(a.ERROR,{type:o.KEY_SYSTEM_ERROR,details:l.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[e];if(!s){const e=I(t.keyFormat),s=e?[e]:_(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=_(this.config)),0===t.length)throw new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.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[A.FAIRPLAY]){const t=tt(new Uint8Array(s));try{const e=v(JSON.parse(t).sinf),s=lt(new Uint8Array(e));if(!s)return;r=s.subarray(8,24),i=A.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=z(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===C&&t.data&&(r=t.data.subarray(8,24)),i=function(t){if(t===C)return A.WIDEVINE}(t.systemId)}if(!i||!r)return;const n=z(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=z(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=w(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 h;if(this.warn(t.message),null!=(h=this.hls)&&h.config.debug)throw t}if(null===s)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const d=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${r}": ${d} (init data type: ${e} length: ${s?s.byteLength:null})`);const c=new js;t.mediaKeysSession.onmessage=e=>{const s=t.mediaKeysSession;if(!s)return void c.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),c.emit("error",t)}):"license-release"===r?t.keySystem===A.FAIRPLAY&&(this.updateKeySession(t,L("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${r}"`)},t.mediaKeysSession.onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void c.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const s=t.keyStatus;c.emit("keyStatus",s),"expired"===s&&(this.warn(`${t.keySystem} expired for key ${d}`),this.renewKeySession(t))};const u=new Promise((t,e)=>{c.on("error",e),c.on("keyStatus",s=>{s.startsWith("usable")?t():"output-restricted"===s?e(new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?e(new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.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: ${d}`)}).catch(t=>{throw new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},"Error generating key-session request: "+t)}).then(()=>u).catch(e=>{throw c.removeAllListeners(),this.removeSession(t),e}).then(()=>(c.removeAllListeners(),t))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach((e,s)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${z("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${z(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e})}fetchServerCertificate(t){const e=this.config,r=new(0,e.loader)(e),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching serverCertificate for "${t}"`),new Promise((n,a)=>{const h={responseType:"arraybuffer",url:i},d=e.certLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(t,e,s,r)=>{n(t.data)},onError:(e,r,n,d)=>{a(new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:s({url:h.url,data:void 0},e)},`"${t}" certificate request failed (${i}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,r)=>{a(new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:h.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(t,e,s)=>{a(new Error("aborted"))}};r.load(h,c,u)})):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:o.KEY_SYSTEM_ERROR,details:l.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:o.KEY_SYSTEM_ERROR,details:l.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))}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 h=s.errorRetry,d=h?h.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||a.status>=400&&a.status<500)i(new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.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=d-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:t,licenseChallenge:e})=>{t.send(e)})})}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(e=>{this.log(`Could not clear media keys: ${e}. media.src: ${null==t?void 0:t.src}`)}))).then(()=>{s&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)}).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}. media.src: ${null==t?void 0:t.src}`)})}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),e.onmessage=null,e.onkeystatuseschange=null,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 Mr="m",xr="a",Fr="v",Or="av",Nr="i",Ur="tt";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.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:Mr,su:!this.initialized})}catch(t){f.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!==Fr&&r!==xr&&r!=Or||(i.br=s.bitrate/1e3,i.tb=this.getTopBandwidth(r)/1e3,i.bl=this.getBufferLength(r)),this.apply(t,i)}catch(t){f.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||CMCDController.uuid(),this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.registerListeners())}registerListeners(){const t=this.hls;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHED,this.onMediaDetached,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHED,this.onMediaDetached,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=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:"h",sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){i(e,this.createData());const s=e.ot===Nr||e.ot===Fr||e.ot===Or;if(this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering),this.useHeaders){const s=CMCDController.toHeaders(e);if(!Object.keys(s).length)return;t.headers||(t.headers={}),i(t.headers,s)}else{const s=CMCDController.toQuery(e);if(!s)return;t.url=CMCDController.appendQueryToUri(t.url,s)}}getObjectType(t){const{type:e}=t;return"subtitle"===e?Ur:"initSegment"===t.sn?Nr:"audio"===e?xr:"main"===e?this.hls.audioTracks.length?Fr:Or:void 0}getTopBandwidth(t){let e,s=0;const r=this.hls;if(t===xr)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===xr?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)}}}static uuid(){const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}static serialize(t){const e=[],s=t=>!Number.isNaN(t)&&null!=t&&""!==t&&!1!==t,r=t=>Math.round(t),i=t=>100*r(t/100),n={br:r,d:r,bl:i,dl:i,mtp:i,nor:t=>encodeURIComponent(t),rtp:i,tb:r},a=Object.keys(t||{}).sort();for(const r of a){let i=t[r];if(!s(i))continue;if("v"===r&&1===i)continue;if("pr"==r&&1===i)continue;const a=n[r];a&&(i=a(i));const o=typeof i;let l;l="ot"===r||"sf"===r||"st"===r?`${r}=${i}`:"boolean"===o?r:"number"===o?`${r}=${i}`:`${r}=${JSON.stringify(i)}`,e.push(l)}return e.join(",")}static toHeaders(t){const e=Object.keys(t),s={},r=["Object","Request","Session","Status"],i=[{},{},{},{}],n={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const s of e){i[null!=n[s]?n[s]:1][s]=t[s]}for(let t=0;t<i.length;t++){const e=CMCDController.serialize(i[t]);e&&(s["CMCD-"+r[t]]=e)}return s}static toQuery(t){return"CMCD="+encodeURIComponent(CMCDController.serialize(t))}static appendQueryToUri(t,e){if(!e)return t;const s=t.includes("?")?"&":"?";return`${t}${s}${e}`}}function Br(t,e,s,r){t&&Object.keys(e).forEach(n=>{const a=t.filter(t=>t.groupId===n).map(t=>{const a=i({},t);return a.details=void 0,a.attrs=new AttrList(a.attrs),a.url=a.attrs.URI=$r(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),a.groupId=a.attrs["GROUP-ID"]=e[n],a.attrs["PATHWAY-ID"]=r,a});t.push(...a)})}function $r(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 Gr=/^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=void 0,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}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)return;const s=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0;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=this.context.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:a}=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&&n(i)?i:a,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,r)?this.retry(n):(f.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{f.warn("timeout while loading "+this.context.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=me(t,s.retry),s.retry++,f.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${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&&Gr.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 Kr=/(\d+)-(\d+)\/(\d+)/;class FetchLoader{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Hr,this.controller=new self.AbortController,this.stats=new LoadStats}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const t=this.response;null!=t&&t.ok||(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 a=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(i({},t.headers))};t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return s}(t,this.controller.signal),o=s.onProgress,l="arraybuffer"===t.responseType,h=l?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:c}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=s,this.request=this.fetchSetup(t,a),self.clearTimeout(this.requestTimeout),e.timeout=d&&n(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 a=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-(a-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=a,r.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Kr.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(n(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(i.headers)||r.total,o&&n(e.highWaterMark)?this.loadProgressively(i,r,t,e.highWaterMark,o):l?i.arrayBuffer():"json"===t.responseType?i.json():i.text()}).then(i=>{const{response:a}=this;self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=i[h];l&&(r.loaded=r.total=l);const d={url:a.url,data:i,code:a.status};o&&!n(e.highWaterMark)&&o(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 Hr(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 Vr=/\s/,Yr={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++)Vr.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=yr(h.trim()),f=Sr(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=>qt(t,e))),i}},Wr=s(s({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength: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=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=t;const e=t.config;this.bwEstimator=new EwmaBandWidthEstimator(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:t}=this;t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(t,e){var s;const r=e.frag;this.ignoreFragment(r)||(this.fragCurrent=r,this.partCurrent=null!=(s=e.part)?s:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(t,e){this.clearTimer()}getTimeToLoadFrag(t,e,s,r){return t+s/e+(r?this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{total:r,bwEstimate:i}=e.stats;n(r)&&n(i)&&(this.lastLevelLoadSec=8*r/i),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:t,partCurrent:e,hls:s}=this,{autoLevelEnabled:r,media:i}=s;if(!t||!i)return;const o=performance.now(),l=e?e.stats:t.stats,h=e?e.duration:t.duration,d=o-l.loading.start;if(l.aborted||l.loaded&&l.loaded===l.total||0===t.level)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||i.paused||!i.playbackRate||!i.readyState)return;const c=s.mainForwardBufferInfo;if(null===c)return;const u=this.bwEstimator.getEstimateTTFB(),g=Math.abs(i.playbackRate);if(d<=Math.max(u,h/(2*g)*1e3))return;const m=c.len/g;if(m>=2*h/g)return;const p=l.loading.first?l.loading.first-l.loading.start:-1,y=l.loaded&&p>-1,T=this.bwEstimator.getEstimate(),{levels:E,minAutoLevel:v}=s,S=E[t.level],L=l.total||Math.max(l.loaded,Math.round(h*S.maxBitrate/8));let A=d-p;A<1&&y&&(A=Math.min(d,8*l.loaded/T));const R=y?1e3*l.loaded/A:0,b=R?(L-l.loaded)/R:8*L/T+u/1e3;if(b<=m)return;const D=R?8*R:T;let k,I=Number.POSITIVE_INFINITY;for(k=t.level-1;k>v;k--){const t=E[k].maxBitrate;if(I=this.getTimeToLoadFrag(u/1e3,D,h*t,!E[k].details),I<m)break}I>=b||I>10*h||(s.nextLoadLevel=k,y?this.bwEstimator.sample(d-Math.min(u,p),l.loaded):this.bwEstimator.sampleTTFB(d),this.clearTimer(),f.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: ${I.toFixed(3)} s\n TTFB estimate: ${p}\n Current BW estimate: ${n(T)?(T/1024).toFixed(3):"Unknown"} Kb/s\n New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s\n Aborting and switching to level ${k}`),t.loader&&(this.fragCurrent=this.partCurrent=null,t.abortRequests()),s.trigger(a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:l}))}onFragLoaded(t,{frag:e,part:s}){const r=s?s.stats:e.stats;if(e.type===Gt&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),this.lastLoadedFragLevel=e.level,this._nextAutoLevel=-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(a.FRAG_BUFFERED,t),e.bitrateTest=!1}}}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.bwEstimator.getEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==Gt||"initSegment"===t.sn}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const t=this._nextAutoLevel,e=this.bwEstimator;if(-1!==t&&!e.canEstimate())return t;let s=this.getNextABRAutoLevel();if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,s)&&e[t].loadError<=e[s].loadError)return t}return-1!==t&&(s=Math.min(t,s)),s}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this,{maxAutoLevel:r,config:i,minAutoLevel:n,media:a}=s,o=e?e.duration:t?t.duration:0,l=a&&0!==a.playbackRate?Math.abs(a.playbackRate):1,h=this.bwEstimator?this.bwEstimator.getEstimate():i.abrEwmaDefaultEstimate,d=s.mainForwardBufferInfo,c=(d?d.len:0)/l;let u=this.findBestLevel(h,n,r,c,i.abrBandWidthFactor,i.abrBandWidthUpFactor);if(u>=0)return u;f.trace(`[abr] ${c?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let g=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay,m=i.abrBandWidthFactor,p=i.abrBandWidthUpFactor;if(!c){const t=this.bitrateTestDelay;if(t){g=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-t,f.trace(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*g)} ms`),m=p=1}}return u=this.findBestLevel(h,n,r,c+g,m,p),Math.max(u,0)}findBestLevel(t,e,s,r,i,a){var o;const{fragCurrent:l,partCurrent:h,lastLoadedFragLevel:d}=this,{levels:c}=this.hls,u=c[d],g=!(null==u||null==(o=u.details)||!o.live),m=null==u?void 0:u.codecSet,p=h?h.duration:l?l.duration:0,y=this.bwEstimator.getEstimateTTFB()/1e3;let T=e,E=-1;for(let o=s;o>=e;o--){const e=c[o];if(!e||m&&e.codecSet!==m){e&&(T=Math.min(o,T),E=Math.max(o,E));continue}-1!==E&&f.trace(`[abr] Skipped level(s) ${T}-${E} with CODECS:"${c[E].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);const s=e.details,l=(h?null==s?void 0:s.partTarget:null==s?void 0:s.averagetargetduration)||p;let v;v=o<=d?i*t:a*t;const S=c[o].maxBitrate,L=this.getTimeToLoadFrag(y,v,S*l,void 0===s);if(f.trace(`[abr] level:${o} adjustedbw-bitrate:${Math.round(v-S)} avgDuration:${l.toFixed(1)} maxFetchDuration:${r.toFixed(1)} fetchDuration:${L.toFixed(1)}`),v>S&&(0===L||!n(L)||g&&!this.bitrateTestDelay||L<r))return o}return-1}set nextAutoLevel(t){this._nextAutoLevel=t}},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.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:t,mediaSource:e}=this;f.log("[buffer-controller]: Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(a.MEDIA_ATTACHED,{media:t})),e&&e.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{f.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{f.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:t,_objectUrl:e}=this;t&&t.src!==e&&f.error(`Media element src was set while attaching MediaSource (${e} > ${t.src})`)},this.hls=t,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}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.BUFFER_RESET,this.onBufferReset,this),t.on(a.BUFFER_APPENDING,this.onBufferAppending,this),t.on(a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.BUFFER_EOS,this.onBufferEos,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.FRAG_PARSED,this.onFragParsed,this),t.on(a.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.BUFFER_RESET,this.onBufferReset,this),t.off(a.BUFFER_APPENDING,this.onBufferAppending,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.BUFFER_EOS,this.onBufferEos,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.FRAG_PARSED,this.onFragParsed,this),t.off(a.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new BufferOperationQueue(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestParsed(t,e){let s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.details=null,f.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")}onMediaAttaching(t,e){const s=this.media=e.media;if(s&&Zs){const t=this.mediaSource=new Zs;t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),s.src=self.URL.createObjectURL(t),this._objectUrl=s.src,s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:s}=this;if(e){if(f.log("[buffer-controller]: media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){f.warn(`[buffer-controller]: onMediaDetaching: ${t.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(t.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),t.src===s?(t.removeAttribute("src"),t.load()):f.warn("[buffer-controller]: media.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(a.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(t=>{const e=this.sourceBuffer[t];try{e&&(this.removeBufferListeners(t),this.mediaSource&&this.mediaSource.removeSourceBuffer(e),this.sourceBuffer[t]=void 0)}catch(e){f.warn(`[buffer-controller]: Failed to reset the ${t} buffer`,e)}}),this._initSourceBuffer()}onBufferCodecs(t,e){const s=this.getSourceBufferTypes().length;Object.keys(e).forEach(t=>{if(s){const s=this.tracks[t];if(s&&"function"==typeof s.buffer.changeType){const{id:r,codec:i,levelCodec:n,container:a,metadata:o}=e[t],l=(s.levelCodec||s.codec).replace(tr,"$1"),h=(n||i).replace(tr,"$1");if(l!==h){const e=`${a};codecs=${n||i}`;this.appendChangeType(t,e),f.log(`[buffer-controller]: switching codec ${l} to ${h}`),this.tracks[t]={buffer:s.buffer,codec:i,container:a,levelCodec:n,metadata:o,id:r}}}}else this.pendingTracks[t]=e[t]}),s||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())}appendChangeType(t,e){const{operationQueue:s}=this,r={execute:()=>{const r=this.sourceBuffer[t];r&&(f.log(`[buffer-controller]: changing ${t} sourceBuffer type to ${e}`),r.changeType(e)),s.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{f.warn(`[buffer-controller]: Failed to change ${t} SourceBuffer type`,e)}};s.append(r,t)}onBufferAppending(t,e){const{hls:s,operationQueue:r,tracks:i}=this,{data:n,type:h,frag:d,part:c,chunkMeta:u}=e,g=u.buffering[h],m=self.performance.now();g.start=m;const p=d.stats.buffering,y=c?c.stats.buffering:null;0===p.start&&(p.start=m),y&&0===y.start&&(y.start=m);const T=i.audio;let E=!1;"audio"===h&&"audio/mpeg"===(null==T?void 0:T.container)&&(E=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);const v=d.start,S={execute:()=>{if(g.executeStart=self.performance.now(),E){const t=this.sourceBuffer[h];if(t){const e=v-t.timestampOffset;Math.abs(e)>=.1&&(f.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${v} (delta: ${e}) sn: ${d.sn})`),t.timestampOffset=v)}}this.appendExecutor(n,h)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();g.executeEnd=g.end=t,0===p.first&&(p.first=t),y&&0===y.first&&(y.first=t);const{sourceBuffer:e}=this,s={};for(const t in e)s[t]=BufferHelper.getBuffered(e[t]);this.appendError=0,this.hls.trigger(a.BUFFER_APPENDED,{type:h,frag:d,part:c,chunkMeta:u,parent:d.type,timeRanges:s})},onError:t=>{f.error(`[buffer-controller]: Error encountered while trying to append to the ${h} SourceBuffer`,t);const e={type:o.MEDIA_ERROR,parent:d.type,details:l.BUFFER_APPEND_ERROR,frag:d,part:c,chunkMeta:u,error:t,err:t,fatal:!1};t.code===DOMException.QUOTA_EXCEEDED_ERR?e.details=l.BUFFER_FULL_ERROR:(this.appendError++,e.details=l.BUFFER_APPEND_ERROR,this.appendError>s.config.appendErrorMaxRetry&&(f.error(`[buffer-controller]: Failed ${s.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),e.fatal=!0)),s.trigger(a.ERROR,e)}};r.append(S,h)}onBufferFlushing(t,e){const{operationQueue:s}=this,r=t=>({execute:this.removeExecutor.bind(this,t,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(a.BUFFER_FLUSHED,{type:t})},onError:e=>{f.warn(`[buffer-controller]: 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[E]?i.push("audiovideo"):(n[y]&&i.push("audio"),n[T]&&i.push("video"));0===i.length&&f.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(a.FRAG_BUFFERED,{frag:s,part:r,stats:e,id:s.type})},i)}onFragChanged(t,e){this.flushBackBuffer()}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,f.log(`[buffer-controller]: ${s} sourceBuffer now EOS`))),t&&!(r&&!r.ended)},!0)&&(f.log("[buffer-controller]: 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?(f.log("[buffer-controller]: Calling mediaSource.endOfStream()"),t.endOfStream()):t&&f.info("[buffer-controller]: 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())}flushBackBuffer(){const{hls:t,details:e,media:s,sourceBuffer:r}=this;if(!s||null===e)return;const i=this.getSourceBufferTypes();if(!i.length)return;const o=e.live&&null!==t.config.liveBackBufferLength?t.config.liveBackBufferLength:t.config.backBufferLength;if(!n(o)||o<0)return;const l=s.currentTime,h=e.levelTargetDuration,d=Math.max(o,h),c=Math.floor(l/h)*h-d;i.forEach(s=>{const i=r[s];if(i){const r=BufferHelper.getBuffered(i);if(r.length>0&&c>r.start(0)){if(t.trigger(a.BACK_BUFFER_REACHED,{bufferEnd:c}),e.live)t.trigger(a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:c});else if(i.ended&&r.end(r.length-1)-l<2*h)return void f.info(`[buffer-controller]: Cannot flush ${s} back buffer while SourceBuffer is in ended state`);t.trigger(a.BUFFER_FLUSHING,{startOffset:0,endOffset:c,type:s})}}})}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,a=s.duration,o=n(r.duration)?r.duration:0;t.live&&e.config.liveDurationInfinity?(f.log("[buffer-controller]: Media Source duration is set to Infinity"),r.duration=1/0,this.updateSeekableRange(t)):(i>o&&i>a||!n(a))&&(f.log("[buffer-controller]: 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);e.setLiveSeekableRange(r,i)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:s}=this,r=Object.keys(s).length;if(r&&!t||2===r){this.createSourceBuffers(s),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(a.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(a.ERROR,{type:o.MEDIA_ERROR,details:l.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 r in t)if(!e[r]){const i=t[r];if(!i)throw Error(`source buffer exists for track ${r}, however track does not`);const n=i.levelCodec||i.codec,h=`${i.container};codecs=${n}`;f.log(`[buffer-controller]: creating sourceBuffer(${h})`);try{const t=e[r]=s.addSourceBuffer(h),a=r;this.addBufferListener(a,"updatestart",this._onSBUpdateStart),this.addBufferListener(a,"updateend",this._onSBUpdateEnd),this.addBufferListener(a,"error",this._onSBUpdateError),this.tracks[r]={buffer:t,codec:n,container:i.container,levelCodec:i.levelCodec,metadata:i.metadata,id:i.id}}catch(t){f.error("[buffer-controller]: error while trying to add sourceBuffer: "+t.message),this.hls.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,mimeType:h})}}}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){const{operationQueue:e}=this;e.current(t).onComplete(),e.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){const s=new Error(t+" SourceBuffer error");f.error("[buffer-controller]: "+s,e),this.hls.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.BUFFER_APPENDING_ERROR,error:s,fatal:!1});const r=this.operationQueue.current(t);r&&r.onError(e)}removeExecutor(t,e,s){const{media:r,mediaSource:i,operationQueue:a,sourceBuffer:o}=this,l=o[t];if(!r||!i||!l)return f.warn(`[buffer-controller]: Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void a.shiftAndExecuteNext(t);const h=n(r.duration)?r.duration:1/0,d=n(i.duration)?i.duration:1/0,c=Math.max(0,e),u=Math.min(s,h,d);u>c&&!l.ending?(l.ended=!1,f.log(`[buffer-controller]: Removing [${c},${u}] from the ${t} SourceBuffer`),l.remove(c,u)):a.shiftAndExecuteNext(t)}appendExecutor(t,e){const{operationQueue:s,sourceBuffer:r}=this,i=r[e];if(!i)return f.warn(`[buffer-controller]: Attempting to append to the ${e} SourceBuffer, but it does not exist`),void s.shiftAndExecuteNext(e);i.ended=!1,i.appendBuffer(t)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length)return f.log("[buffer-controller]: 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=f.log.bind(f,"[info]:"),this.warn=f.warn.bind(f,"[warning]:"),this.error=f.error.bind(f,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(a.ERROR,this.onError,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this)}unregisterListeners(){const t=this.hls;t&&(t.off(a.ERROR,this.onError,this),t.off(a.ERROR,this.onErrorOut,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){this.playlistError=0}stopLoad(){}getVariantLevelIndex(t){return(null==t?void 0:t.type)===Gt?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onError(t,e){var s;if(e.fatal)return;const r=this.hls,i=e.context;switch(e.details){case l.FRAG_LOAD_ERROR:case l.FRAG_LOAD_TIMEOUT:case l.KEY_LOAD_ERROR:case l.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case l.FRAG_GAP:case l.FRAG_PARSING_ERROR:case l.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ae);case l.LEVEL_EMPTY_ERROR:case l.LEVEL_PARSING_ERROR:{var n,a;const t=e.parent===Gt?e.level:r.loadLevel;e.details===l.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(a=n.levelDetails)&&a.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case l.LEVEL_LOAD_ERROR:case l.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.level)));case l.AUDIO_TRACK_LOAD_ERROR:case l.AUDIO_TRACK_LOAD_TIMEOUT:case l.SUBTITLE_LOAD_ERROR:case l.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const t=r.levels[r.loadLevel];if(t&&(i.type===Bt&&i.groupId===t.audioGroupId||i.type===$t&&i.groupId===t.textGroupId))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.loadLevel),e.errorAction.action=Ae,void(e.errorAction.flags=De)}return;case l.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=r.levels[r.loadLevel],s=null==t?void 0:t.attrs["HDCP-LEVEL"];s&&(e.errorAction={action:Ae,flags:ke,hdcpLevel:s})}return;case l.BUFFER_ADD_CODEC_ERROR:case l.REMUX_ALLOC_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(s=e.level)?s:r.loadLevel));case l.INTERNAL_EXCEPTION:case l.BUFFER_APPENDING_ERROR:case l.BUFFER_APPEND_ERROR:case l.BUFFER_FULL_ERROR:case l.LEVEL_SWITCH_ERROR:case l.BUFFER_STALLED_ERROR:case l.BUFFER_SEEK_OVER_HOLE:case l.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:Le,flags:be})}if(e.type===o.KEY_SYSTEM_ERROR){const t=this.getVariantLevelIndex(e.frag);return e.levelRetry=!1,void(e.errorAction=this.getLevelSwitchAction(e,t))}}getPlaylistRetryOrSwitchAction(t,e){var s,r;const i=ge(this.hls.config.playlistLoadPolicy,t),n=this.playlistError++,a=null==(s=t.response)?void 0:s.code;return ye(i,n,fe(t),a)?{action:Re,flags:be,retryConfig:i,retryCount:n}:null!=(r=t.context)&&r.deliveryDirectives?{action:Le,flags:be,retryConfig:i||{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},retryCount:n}:this.getLevelSwitchAction(t,e)}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),r=e.levels[s],{fragLoadPolicy:i,keyLoadPolicy:n}=e.config,a=ge(t.details.startsWith("key")?n:i,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(r){var h;t.details!==l.FRAG_GAP&&r.fragmentError++;const e=null==(h=t.response)?void 0:h.code;if(ye(a,o,fe(t),e))return{action:Re,flags:be,retryConfig:a,retryCount:o}}const d=this.getLevelSwitchAction(t,s);return a&&(d.retryConfig=a,d.retryCount=o),d}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const r=this.hls.levels[e];if(r&&(r.loadError++,s.autoLevelEnabled)){var i,n;let e=-1;const a=s.levels,o=null==(i=t.frag)?void 0:i.type,{type:h,groupId:d}=null!=(n=t.context)?n:{};for(let i=a.length;i--;){const n=(i+s.loadLevel)%a.length;if(n!==s.loadLevel&&0===a[n].loadError){const s=a[n];if(t.details===l.FRAG_GAP&&t.frag){const e=a[n].details;if(e){const s=Ee(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(h===Bt&&d===s.audioGroupId||h===$t&&d===s.textGroupId)continue;if(o===Kt&&r.audioGroupId===s.audioGroupId||o===Ht&&r.textGroupId===s.textGroupId)continue}e=n;break}}if(e>-1&&s.loadLevel!==e)return t.levelRetry=!0,{action:Ae,flags:be,nextAutoLevel:e}}return{action:Ae,flags:De}}onErrorOut(t,e){var s;switch(null==(s=e.errorAction)?void 0:s.action){case Le:break;case Ae:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===l.FRAG_GAP||(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 be:this.switchLevel(t,n);break;case De:s.resolved||(s.resolved=this.redundantFailover(t));break;case ke:i&&(e.maxHdcpLevel=se[se.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)}redundantFailover(t){const{hls:e,penalizedRenditions:s}=this,r=t.parent===Gt?t.level:e.loadLevel,i=e.levels[r],n=i.url.length,a=t.frag?t.frag.urlId:i.urlId;i.urlId!==a||t.frag&&!i.details||this.penalizeRendition(i,t);for(let o=1;o<n;o++){const l=(a+o)%n,h=s[l];if(!h||Ie(h,t,s[a]))return this.warn(`Switching to Redundant Stream ${l+1}/${n}: "${i.url[l]}" after ${t.details}`),this.playlistError=0,e.levels.forEach(t=>{t.urlId=l}),e.nextLoadLevel=r,!0}return!1}penalizeRendition(t,e){const{penalizedRenditions:s}=this,r=s[t.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};r.lastErrorPerfMs=performance.now(),r.errors.push(e),r.details=t.details,s[t.urlId]=r}},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(a.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(a.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,o=1e3*i/t,l=this.hls;if(l.trigger(a.FPS_DROP,{currentDropped:i,currentDecoded:n,totalDroppedFrames:s}),o>0&&i>l.config.fpsDroppedMonitoringThreshold*n){let t=l.currentLevel;f.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=t)&&(t-=1,l.trigger(a.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:l.currentLevel}),l.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,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:P,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!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:Yr,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]",Ht),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.ERROR,this.onError,this),t.on(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(a.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.ERROR,this.onError,this),t.off(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(a.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=Xe,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=Xe,!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)}onBufferFlushing(t,e){const{startOffset:s,endOffset:r}=e;if(0===s&&r!==Number.POSITIVE_INFINITY){const{currentTrackId:t,levels:i}=this;if(!i.length||!i[t]||!i[t].details)return;const n=r-i[t].details.targetduration;if(n<=0)return;e.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(t=>{for(let e=0;e<t.length;)if(t[e].end<=n)t.shift();else{if(!(t[e].start<n))break;t[e].start=n,e++}}),this.fragmentTracker.removeFragmentsInRange(s,n,Ht)}}onFragBuffered(t,e){var s;this.loadedmetadata||e.frag.type!==Gt||null!=(s=this.media)&&s.buffered.length&&(this.loadedmetadata=!0)}onError(t,e){const s=e.frag;(null==s?void 0:s.type)===Ht&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==je&&(this.state=Xe))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){zs(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,Ht),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){if(this.currentTrackId=e.id,!this.levels.length||-1===this.currentTrackId)return void this.clearInterval();const s=this.levels[this.currentTrackId];null!=s&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var s;const{details:r,id:i}=e,{currentTrackId:n,levels:a}=this;if(!a.length)return;const o=a[n];if(i>=a.length||i!==n||!o)return;this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(r.live||null!=(s=o.details)&&s.live){const t=this.mainDetails;if(r.deltaUpdateFailed||!t)return;const e=t.fragments[0];o.details?(l=this.alignPlaylists(r,o.details),0===l&&e&&(l=e.start,de(r,l))):r.hasProgramDateTime&&t.hasProgramDateTime?(We(r,t),l=r.fragments[0].start):e&&(l=e.start,de(r,l))}if(o.details=r,this.levelLastLoaded=i,this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(o.details,l),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===Xe){Ee(null,r.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&&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(a.ERROR,{type:o.MEDIA_ERROR,details:l.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(s=>{const r=performance.now();i.trigger(a.FRAG_DECRYPTED,{frag:e,payload:s,stats:{tstart:t,tdecrypt:r}})}).catch(t=>{this.warn(`${t.name}: ${t.message}`),this.state=Xe})}}doTick(){if(this.media){if(this.state===Xe){const{currentTrackId:t,levels:e}=this,s=e[t];if(!e.length||!s||!s.details)return;const r=s.details,i=r.targetduration,{config:n}=this,a=this.getLoadPosition(),o=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a-i,n.maxBufferHole),{end:l,len:h}=o,d=this.getFwdBufferInfo(this.media,Gt);if(h>this.getMaxBufferLength(null==d?void 0:d.len)+i)return;const c=r.fragments,u=c.length,f=r.edge;let g=null;const m=this.fragPrevious;if(l<f){const{maxFragLookUpTolerance:t}=n;g=Ee(m,c,Math.max(c[0].start,l),t),!g&&m&&m.start<c[0].start&&(g=c[0])}else g=c[u-1];if(!g)return;g=this.mapToInitFragWhenRequired(g),this.fragmentTracker.getState(g)===Pe&&this.loadFragment(g,s,l)}}else this.state=Xe}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.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(a.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.trackChangeListener,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);Js(this.media.textTracks).forEach(t=>{jt(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,details:r}=e,{trackId:i}=this,n=this.tracksInGroup[i];if(!n)return void this.warn("Invalid subtitle track id "+s);const a=n.details;n.details=e.details,this.log(`subtitle track ${s} loaded [${r.startSN}-${r.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(null==e||!e.textGroupIds)return;const s=e.textGroupIds[e.urlId],r=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==s){const t=this.tracks.filter(t=>!s||t.groupId===s);this.tracksInGroup=t;const e=this.findTrackId(null==r?void 0:r.name)||this.findTrackId();this.groupId=s||null;const i={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${s}" group-id`),this.hls.trigger(a.SUBTITLE_TRACKS_UPDATED,i),-1!==e&&this.setSubtitleTrack(e,r)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId,r)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const r=e[s];if((!this.selectDefaultTrack||r.default)&&(!t||t===r.name))return r.id}return-1}onError(t,e){!e.fatal&&e.context&&e.context.type===$t&&e.context.id===this.trackId&&e.context.groupId===this.groupId&&this.checkRetry(e)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1;const e=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(t,e)}loadPlaylist(t){super.loadPlaylist();const e=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(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(a.SUBTITLE_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null})}}toggleTrackModes(t){const{media:e,trackId:s}=this;if(!e)return;const r=Js(e.textTracks),i=r.filter(t=>t.groupId===this.groupId);if(-1===t)[].slice.call(r).forEach(t=>{t.mode="disabled"});else{const t=i[s];t&&(t.mode="disabled")}const n=i[t];n&&(n.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(t,e){var s;const r=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(this.trackId!==t&&this.toggleTrackModes(t),this.trackId===t&&(-1===t||null!=(s=r[t])&&s.details)||t<-1||t>=r.length)return;this.clearTimer();const i=r[t];if(this.log("Switching to subtitle-track "+t+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:"")),this.trackId=t,i){const{id:t,groupId:s="",name:r,type:n,url:o}=i;this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:t,groupId:s,name:r,type:n,url:o});const l=this.switchParams(i.url,null==e?void 0:e.details);this.loadPlaylist(l)}else this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:t})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1;const e=Js(this.media.textTracks);for(let s=0;s<e.length;s++)if("hidden"===e[s].mode)t=s;else if("showing"===e[s].mode){t=s;break}this.subtitleTrack!==t&&(this.subtitleTrack=t)}},timelineController:class TimelineController{constructor(t){if(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.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}},this.config.enableCEA708Captions){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)}t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(a.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(a.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(t,e,s,r,i){let n=!1;for(let t=i.length;t--;){const r=i[t],a=(o=r[0],l=r[1],h=e,d=s,Math.min(l,d)-Math.max(o,h));if(a>=0&&(r[0]=Math.min(r[0],e),r[1]=Math.max(r[1],s),n=!0,a/(s-e)>.5))return}var o,l,h,d;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(a.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(a.FRAG_LOADED,t)}))}getExistingTrack(t){const{media:e}=this;if(e)for(let s=0;s<e.textTracks.length;s++){const r=e.textTracks[s];if(r[t])return r}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(t);if(a)s[t]=a,jt(s[t]),Wt(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(a.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=>{jt(t[e]),delete t[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){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.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++)jt(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(zs(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media?this.media.textTracks:null;this.tracks.forEach((e,s)=>{let r;if(t&&s<t.length){let s=null;for(let r=0;r<t.length;r++)if(Pr(t[r],e)){s=t[r];break}s&&(r=s)}if(r)jt(r);else{const t=this._captionsOrSubtitlesFromCharacteristics(e);r=this.createTextTrack(t,e.name,e.lang),r&&(r.mode="disabled")}r&&(r.groupId=e.groupId,this.textTracks.push(r))})}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(a.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}_captionsOrSubtitlesFromCharacteristics(t){if(t.attrs.CHARACTERISTICS){const e=/transcribes-spoken-dialog/gi.test(t.attrs.CHARACTERISTICS),s=/describes-music-and-sound/gi.test(t.attrs.CHARACTERISTICS);if(e&&s)return"captions"}return"subtitles"}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){const{cea608Parser1:s,cea608Parser2:r,lastSn:i,lastPartIndex:n}=this;if(this.enabled&&s&&r&&e.frag.type===Gt){var a,o;const t=e.frag.sn,l=null!=(a=null==e||null==(o=e.part)?void 0:o.index)?a:-1;t===i+1||t===i&&l===n+1||(s.reset(),r.reset()),this.lastSn=t,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:s,payload:r}=e,{initPTS:i,unparsedVttFrags:n}=this;if(s.type===Ht)if(r.byteLength){if(!i[s.cc])return n.push(e),void(i.length&&this.hls.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Missing initial subtitle PTS")}));const t=s.decryptdata,o="stats"in e;if(null==t||!t.encrypted||o){const t=this.tracks[s.level],e=this.vttCCs;e[s.cc]||(e[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(s,r,e)}}else this.hls.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const s=this.hls;Dr(e,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),s.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},e=>{f.log("Failed to parse IMSC1: "+e),s.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})})}_parseVTTs(t,e,s){var r;const i=this.hls;Lr(null!=(r=t.initSegment)&&r.data?dt(t.initSegment.data,new Uint8Array(e)):e,this.initPTS[t.cc],s,t.cc,t.start,e=>{this._appendCues(e,t.level),i.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},s=>{this._fallbackToIMSC1(t,e),f.log("Failed to parse VTT cue: "+s),i.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:s})})}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||Dr(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=>qt(s,t))}else{const r=this.tracks[e];if(!r)return;const i=r.default?"default":"subtitles"+e;s.trigger(a.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,e){const{frag:s}=e;if(s.type===Ht){if(!this.initPTS[s.cc])return void this.unparsedVttFrags.push(e);this.onFragLoaded(a.FRAG_LOADED,e)}}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){const{cea608Parser1:s,cea608Parser2:r}=this;if(!this.enabled||!s||!r)return;const{frag:i,samples:n}=e;if(i.type!==Gt||"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=>Xt(t[r],e,s))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==r){const{textTracks:t}=this;Object.keys(t).forEach(s=>Xt(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]",Kt),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.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(a.ERROR,this.onError,this),t.on(a.BUFFER_RESET,this.onBufferReset,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(a.ERROR,this.onError,this),t.off(a.BUFFER_RESET,this.onBufferReset,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.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===is&&this.tick()}}startLoad(t){if(!this.levels)return this.startPosition=t,void(this.state=je);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=Xe):(this.loadedmetadata=!1,this.state=Ze),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case Xe:this.doTickIdle();break;case Ze:{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=is}break}case Je:{var e;const t=performance.now(),s=this.retryDate;(!s||t>=s||null!=(e=this.media)&&e.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=Xe);break}case is:{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=Qe;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);ve(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=Xe}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Xe)}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(null==e||!e[r])return;if(!s&&(this.startFragRequested||!i.startFragPrefetch))return;const n=e[r],o=n.details;if(!o||o.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(o))return void(this.state=Ze);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,y,Kt));const h=this.getFwdBufferInfo(l,Kt);if(null===h)return;const{bufferedTrack:d,switchingTrack:c}=this;if(!c&&this._streamEnded(h,o))return t.trigger(a.BUFFER_EOS,{type:"audio"}),void(this.state=ss);const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Gt),f=h.len,g=this.getMaxBufferLength(null==u?void 0:u.len);if(f>=g&&!c)return;const m=o.fragments[0].start;let p=h.end;if(c&&s){const t=this.getLoadPosition();d&&c.attrs!==d.attrs&&(p=t),o.PTSKnown&&t<m&&(h.end>m||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=m+.05)}let T=this.getNextFragment(p,o),E=!1;if(T&&this.isLoopLoading(T,p)&&(E=!!T.gap,T=this.getNextFragmentLoopLoading(T,o,h,Gt,g)),!T)return void(this.bufferFlushed=!0);const v=u&&T.start>u.end+o.targetduration;if(v||(null==u||!u.len)&&h.len){const t=this.fragmentTracker.getBufferedFrag(T.start,Gt);if(null===t)return;if(E||(E=!!t.gap||!!v&&0===u.len),v&&!E||E&&h.nextStart&&h.nextStart<t.end)return}this.loadFragment(T,n,p)}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.min(Math.max(e,t),this.config.maxMaxBufferLength):e}onMediaDetaching(){this.videoBuffer=null,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=Xe):(this.switchingTrack=null,this.bufferedTrack=e,this.state=je),this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.bufferedTrack=null,this.switchingTrack=null}onLevelLoaded(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(a.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(`Track ${n} loaded [${i.startSN},${i.endSN}],duration:${i.totalduration}`);const a=r[n];let o=0;if(i.live||null!=(s=a.details)&&s.live){const t=this.mainDetails;if(i.fragments[0]||(i.deltaUpdateFailed=!0),i.deltaUpdateFailed||!t)return;!a.details&&i.hasProgramDateTime&&t.hasProgramDateTime?(We(i,t),o=i.fragments[0].start):o=this.alignPlaylists(i,a.details)}a.details=i,this.levelLastLoaded=n,this.startFragRequested||!this.mainDetails&&i.live||this.setStartPosition(a.details,o),this.state!==Ze||this.waitForCdnTuneIn(i)||(this.state=Xe),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,Kt,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=is}}_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:r,part:i}=e;var n;if(r.type===Kt)if(this.fragContextChanged(r))this.warn(`Fragment ${r.sn}${i?" p: "+i.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==r.sn){this.fragPrevious=r;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(a.AUDIO_TRACK_SWITCHED,s({},t)))}this.fragBufferedComplete(r,i)}else this.loadedmetadata||r.type!==Gt||null!=(n=this.videoBuffer||this.media)&&n.buffered.length&&(this.loadedmetadata=!0)}onError(t,e){var s;if(e.fatal)this.state=rs;else switch(e.details){case l.FRAG_GAP:case l.FRAG_PARSING_ERROR:case l.FRAG_DECRYPT_ERROR:case l.FRAG_LOAD_ERROR:case l.FRAG_LOAD_TIMEOUT:case l.KEY_LOAD_ERROR:case l.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Kt,e);break;case l.AUDIO_TRACK_LOAD_ERROR:case l.AUDIO_TRACK_LOAD_TIMEOUT:case l.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ze||(null==(s=e.context)?void 0:s.type)!==Bt||(this.state=Xe);break;case l.BUFFER_FULL_ERROR:if(!e.parent||"audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case l.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushed(t,{type:e}){e===y&&(this.bufferFlushed=!0,this.state===ss&&(this.state=Xe))}_handleTransmuxComplete(t){var e;const s="audio",{hls:r}=this,{remuxResult:n,chunkMeta:o}=t,l=this.getCurrentContext(o);if(!l)return void this.resetWhenMissingContext(o);const{frag:h,part:d,level:c}=l,{details:u}=c,{audio:f,text:g,id3:m,initSegment:p}=n;if(!this.fragContextChanged(h)&&u){if(this.state=ts,this.switchingTrack&&f&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks&&(this._bufferInitSegment(p.tracks,h,o),r.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:h,id:s,tracks:p.tracks})),f){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=f;d&&(d.elementaryStreams[y]={startPTS:t,endPTS:e,startDTS:s,endDTS:r}),h.setElementaryStreamInfo(y,t,e,s,r),this.bufferFragmentData(f,h,d,o)}if(null!=m&&null!=(e=m.samples)&&e.length){const t=i({id:s,frag:h,details:u},m);r.trigger(a.FRAG_PARSING_METADATA,t)}if(g){const t=i({id:s,frag:h,details:u},g);r.trigger(a.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(h)}_bufferInitSegment(t,e,s){if(this.state!==ts)return;t.video&&delete t.video;const r=t.audio;if(!r)return;r.levelCodec=r.codec,r.id="audio",this.log(`Init audio buffer, container:${r.container}, codecs[parsed]=[${r.codec}]`),this.hls.trigger(a.BUFFER_CODECS,t);const i=r.initSegment;if(null!=i&&i.byteLength){const t={type:"audio",frag:e,part:null,chunkMeta:s,parent:e.type,data:i};this.hls.trigger(a.BUFFER_APPENDING,t)}this.tick()}loadFragment(t,e,s){const r=this.fragmentTracker.getState(t);var i;(this.fragCurrent=t,this.switchingTrack||r===Pe||r===xe)?"initSegment"===t.sn?this._loadInitSegment(t,e):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=is):(this.startFragRequested=!0,super.loadFragment(t,e,s)):this.clearTrackerIfNeeded(t)}completeAudioSwitch(t){const{hls:e,media:r,bufferedTrack:i}=this,n=null==i?void 0:i.attrs,o=t.attrs;r&&n&&(n.CHANNELS!==o.CHANNELS||n.NAME!==o.NAME||n.LANGUAGE!==o.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(a.AUDIO_TRACK_SWITCHED,s({},t))}},audioTrackController:class AudioTrackController extends BasePlaylistController{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(a.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,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(`Track with id:${s} and group:${r} not found in active group ${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(null==e||!e.audioGroupIds)return;const s=e.audioGroupIds[e.urlId];if(this.groupId!==s){this.groupId=s||null;const t=this.tracks.filter(t=>!s||t.groupId===s);this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=t;const e={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group:${s}`),this.hls.trigger(a.AUDIO_TRACKS_UPDATED,e),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(t,e){!e.fatal&&e.context&&e.context.type===Bt&&e.context.id===this.trackId&&e.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(e))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn("Invalid id passed to audio-track controller");this.clearTimer();const r=this.currentTrack;e[this.trackId];const i=e[t],{groupId:n,name:o}=i;if(this.log(`Switching to audio-track ${t} "${o}" lang:${i.lang} group:${n}`),this.trackId=t,this.currentTrack=i,this.selectDefaultTrack=!1,this.hls.trigger(a.AUDIO_TRACK_SWITCHING,s({},i)),i.details&&!i.details.live)return;const l=this.switchParams(i.url,null==r?void 0:r.details);this.loadPlaylist(l)}selectInitialTrack(){const t=this.tracksInGroup,e=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(-1!==e)this.setAudioTrack(e);else{const e=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const r=e[s];if(!this.selectDefaultTrack||r.default){if(!t||t.attrs["STABLE-RENDITION-ID"]===r.attrs["STABLE-RENDITION-ID"])return r.id;if(t.name===r.name&&t.lang===r.lang)return r.id}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(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 audio-track playlist ${s} "${e.name}" lang:${e.lang} group:${r}`),this.clearTimer(),this.hls.trigger(a.AUDIO_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null})}}},emeController:EMEController,cmcdController:CMCDController,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=f.log.bind(f,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.ERROR,this.onError,this))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const t=Math.max(1e3*this.timeToLoad-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,t)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}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)===Ae&&s.flags===De){let t=this.pathwayPriority;const e=this.pathwayId;this.penalizedPathways[e]||(this.penalizedPathways[e]=performance.now()),!t&&this.levels&&(t=this.levels.reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])),t&&t.length>1&&(this.updatePathwayPriority(t),s.resolved=this.pathwayId!==e)}}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(s[i])continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,o=this.hls.levels[n];if(e=this.getLevelsForPathway(i),e.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,this.hls.trigger(a.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];o&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}clonePathways(t){const e=this.levels;if(!e)return;const s={},r={};t.forEach(t=>{const{ID:n,"BASE-ID":a,"URI-REPLACEMENT":o}=t;if(e.some(t=>t.pathwayId===n))return;const l=this.getLevelsForPathway(a).map(t=>{const e=i({},t);e.details=void 0,e.url=$r(t.uri,t.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o);const a=new AttrList(t.attrs);a["PATHWAY-ID"]=n;const l=a.AUDIO&&`${a.AUDIO}_clone_${n}`,h=a.SUBTITLES&&`${a.SUBTITLES}_clone_${n}`;l&&(s[a.AUDIO]=l,a.AUDIO=l),h&&(r[a.SUBTITLES]=h,a.SUBTITLES=h),e.attrs=a;const d=new Level(e);return we(d,"audio",l),we(d,"text",h),d});e.push(...l),Br(this.audioTracks,s,o,n),Br(this.subtitleTracks,r,o,n)})}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),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){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(t)},e)}}});function qr(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(qr):Object.keys(t).reduce((e,s)=>(e[s]=qr(t[s]),e),{}):t}function jr(t){const e=t.loader;if(e!==FetchLoader&&e!==XhrLoader)f.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,f.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Hls{static get version(){return"1.4.0"}static isSupported(){return function(){const t=as();if(!t)return!1;const e=os(),s=t&&"function"==typeof t.isTypeSupported&&t.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),r=!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove;return!!s&&!!r}()}static get Events(){return a}static get ErrorTypes(){return o}static get ErrorDetails(){return l}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:Wr}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._emitter=new js,this._autoLevelCapping=void 0,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,function(t,e){if(self.console&&!0===t||"object"==typeof t){u(t,"debug","log","info","warn","error");try{c.log(`Debug logs enabled for "${e}" in hls.js version 1.4.0`)}catch(t){c=d}}else c=d}(t.debug||!1,"Hls instance");const e=this.config=function(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=qr(t),i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const s=("level"===t?"playlist":t)+"LoadPolicy",n=void 0===e[s],a=[];i.forEach(i=>{const o=`${t}Loading${i}`,l=e[o];if(void 0!==l&&n){a.push(o);const t=r[s].default;switch(e[s]={default:t},i){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&&f.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(e[s])}`)}),s(s({},r),e)}(Hls.DefaultConfig,t);this.userConfig=t,this._autoLevelCapping=-1,e.progressive&&jr(e);const{abrController:r,bufferController:i,capLevelController:n,errorController:o,fpsController:l}=e,h=new o(this),g=this.abrController=new r(this),m=this.bufferController=new i(this),p=this.capLevelController=new n(this),y=new l(this),T=new PlaylistLoader(this),E=new ID3TrackController(this),v=e.contentSteeringController,S=v?new v(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);p.setStreamController(b),y.setStreamController(b);const D=[T,L,b];S&&D.splice(1,0,S),this.networkControllers=D;const k=[g,m,p,y,E,A];this.audioTrackController=this.createController(e.audioTrackController,D);const I=e.audioStreamController;I&&D.push(new I(this,A,R)),this.subtitleTrackController=this.createController(e.subtitleTrackController,D);const C=e.subtitleStreamController;C&&D.push(new C(this,A,R)),this.createController(e.timelineController,k),R.emeController=this.emeController=this.createController(e.emeController,k),this.cmcdController=this.createController(e.cmcdController,k),this.latencyController=this.createController(LatencyController,k),this.coreComponents=k,D.push(h);const w=h.onErrorOut;"function"==typeof w&&this.on(a.ERROR,w,h)}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){f.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),this.trigger(a.ERROR,{type:o.OTHER_ERROR,details:l.INTERNAL_EXCEPTION,fatal:!1,event:t,error:e})}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){f.log("destroy"),this.trigger(a.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){f.log("attachMedia"),this._media=t,this.trigger(a.MEDIA_ATTACHING,{media:t})}detachMedia(){f.log("detachMedia"),this.trigger(a.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const s=this.media,r=this.url,i=this.url=t.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});f.log("loadSource:"+i),s&&r&&r!==i&&this.bufferController.hasSourceTypes()&&(this.detachMedia(),this.attachMedia(s)),this.trigger(a.MANIFEST_LOADING,{url:e})}startLoad(t=-1){f.log(`startLoad(${t})`),this.networkControllers.forEach(e=>{e.startLoad(t)})}stopLoad(){f.log("stopLoad"),this.networkControllers.forEach(t=>{t.stopLoad()})}swapAudioCodec(){f.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){f.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t,e=0){this.levelController.removeLevel(t,e)}get levels(){const t=this.levelController.levels;return t||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){f.log("set currentLevel:"+t),this.loadLevel=t,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){f.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){f.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){f.log("set firstLevel:"+t),this.levelController.firstLevel=t}get startLevel(){return this.levelController.startLevel}set startLevel(t){f.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}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(f.log("set autoLevelCapping:"+t),this._autoLevelCapping=t)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){se.indexOf(t)>-1&&(this._maxHdcpLevel=t)}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&&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 nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}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 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 Xr=Object.freeze({__proto__:null,ATTACHED:"hls:attached"});const zr="com.widevine.alpha";const Qr="application/vnd.apple.mpegURL",Jr=[Qr,"application/x-mpegurl"],Zr=document.createElement("video").canPlayType(Qr);function ti(t){const{pathname:e}=function(t){const e=document.createElement("a");return e.href=t,e}(t);return e.endsWith(".m3u8")}function ei({src:t="",type:e="",drm:s},r){const i=(null==r?void 0:r.hls)||{},n="native"in i&&i.native;return(!Zr||!n)&&(!(s&&!Object.keys(s).find(t=>{return e=t,[zr].filter((function(t){return t===e})).length;var e}))&&(!(!e||!Jr.includes(e))||ti(t)))}const si=window&&window.Hls||Hls;var ri="audio:set",ii="audio:update",ni="audio:tracks";var ai=Object.assign(Object.assign({},{"http.404":"the video was not found","http.403":"access to this video was denied","http.410":"the video no longer exists","http.live.404":"stream is offline","http.0":"no internet connection detected"}),{keySystemNoKeys:"no keys",keySystemNoAccess:"no access to key system",keySystemNoSession:"no session for key system",keySystemLicenseRequestFailed:"license request failed",keyLoadError:"decrypt key load failed",keyLoadTimeOut:"decrypt key load timed outs"});var oi,li;function hi(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}!function(t){t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=4]="HIGH"}(oi||(oi={})),function(t){t[t.FRAGMENT_ERRORS=0]="FRAGMENT_ERRORS",t[t.STALE_MANIFEST=1]="STALE_MANIFEST"}(li||(li={}));const di=hi("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;this.reset();const s=this.hls;if(!s)return;const r=s.levels[s.currentLevel];if(!r)return;if(r.url.length<2)return;const i=s.levels[s.currentLevel].details,n=(r.urlId+1)%r.url.length;s.levels.forEach(t=>{t.urlId=n}),null===(e=s.media)||void 0===e||e.dispatchEvent(new CustomEvent("hls/failover",{detail:{reason:t,from:null==i?void 0:i.url}}))}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||(di(`${t} / no change in ${s.count} tries`,this.playlistCounts),this.failover(li.STALE_MANIFEST)))}trackFragmentError(t){const e=this.fragmentFailures[t]||0;this.fragmentFailures[t]=e+1,this.fragmentFailures[t]>2&&this.failover(li.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 ci=hi("hls");function ui(t,e,s,r){if(!t.reaper||!s.src)return;t.hls&&t.hls.destroy();const i="live"in e==0,n={is_audio_only:!1,fragDuration:-1,media_recovers:0,audio_swaps:0};if(s.drm&&"https:"!==location.protocol&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname)return t.emit("error",{message:"Secure page required for DRM"});const a=new FailoverLoaderController,o=function(t){return Object.assign(Object.assign({autoStartLoad:!1,levelLoadingMaxRetry:1},t.hls),{startPosition:t.start_time||-1})}(e);o.renderTextTracksNatively=!1,o.pLoader=a.createPlaylistLoader(r),o.fLoader=a.createFragmentLoader();const l=t.hls=new si(o);a.setHls(l),l.subtitleDisplay=!1,l.attachMedia(t),l.loadSource(s.src),t.emit("hls:attached",{hls:l}),function(t,e){t.on(Hls.Events.AUDIO_TRACKS_UPDATED,(function(t,s){e.emit(ni,s.audioTracks)})),t.on(Hls.Events.AUDIO_TRACK_SWITCHING,(function(t,s){e.emit(ii,s)})),t.on(Hls.Events.MANIFEST_PARSED,(function(t,s){s.audioTracks&&e.emit(ni,s.audioTracks)})),t.on(Hls.Events.LEVEL_SWITCHED,(function(s,r){const i=t.levels[r.level];i&&e.emit(ni,t.audioTracks.filter((function(t){return t.groupId&&~(i.audioGroupIds||[]).indexOf(t.groupId)})))}))}(l,t),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)})}(l,t);const h=function(t){var e;const s=null===(e=t.data)||void 0===e?void 0:e.level;"number"==typeof s&&(l.levels[s]||-1===s?l.nextLevel=s:console.error(new Error("skipping invalid quality: "+t.data)))},d=function(t){var e;const s=null===(e=t.data)||void 0===e?void 0:e.id;"number"==typeof s&&s!=l.audioTrack&&setTimeout((function(){l.audioTrack=s}),0)};t.on("quality:set",h),t.on(ri,d),t.on("src",(function(){t.off("quality:set",h),t.off(ri,d),t.hls&&(t.hls.destroy(),delete t.hls,r.manifest=void 0)}));let c=0;t.on("error",e=>{var s;++c,c>=5||!t.hls||(null===(s=null==t?void 0:t.error)||void 0===s?void 0:s.code)!==MediaError.MEDIA_ERR_DECODE||(e.preventDefault(),l.config.autoStartLoad=!0,l.recoverMediaError())}),t.on("canplay",()=>c=0),t.on("beforeplay",()=>{if(t.hls&&!t.hasState("is-casting")&&!t.hasState("is-loaded")&&"none"===e.preload&&!e.autoplay)return t.hls.levels.length?fi(t,e.start_time||-1):void t.hls.once(si.Events.MANIFEST_PARSED,()=>{setTimeout(()=>{fi(t,e.start_time||-1)},0)})}),t.on("tracks:video:select",(function(e){var s;const r=e.detail.track,i=null===(s=t.tracks)||void 0===s?void 0:s.find(t=>t.selected&&t!==r),n=t.hls;if(!i||!r||!n)return;i.selected=!1;const a=r.data.slice(0).map(t=>(t.details=void 0,t));n.stopLoad(),n.levelController._levels=n.streamController.levels=a,n.currentLevel=-1,n.levelController.currentLevelIndex=-1,t.emit("qualities",gi(a)),t.hasState("is-starting")&&!t.hasState("is-loading")||n.startLoad()})),t.on("audioonlysource",(function(){n.is_audio_only=!0})),t.on("reap",(function(){l&&l.destroy()})),t.on("remotesession:started",()=>{t.hls&&t.hls.stopLoad()}),t.on("remotesession:ended",()=>{t.hls&&fi(t)}),t.on("retry",r=>{if(t.hls){if(r.preventDefault(),s.src&&l.loadSource(t.original_src),e.autoplay)return t.togglePlay(!0);t.setState("is-waiting",!1),t.emit("retry/done")}}),i&&l.on(si.Events.LEVEL_LOADED,(function(e,s){t.setOpts({live:s.details.live})})),l.on(si.Events.MANIFEST_PARSED,(function(i,n){const a=gi(n.levels);t.emit("qualities",a),t.emit("parse:video:tracks",{url:s.src,manifest:r.manifest}),function(t,e,s){var r,i;if(!t.hls)return;ci("Initializer::maybe_start_load_with_quality (start_quality, preload): (%d, %s)",e.start_quality,e.preload),void 0!==e.start_quality&&(oi.HIGH&e.start_quality&&(t.hls.startLevel=s[0].level),oi.LOW&e.start_quality&&(t.hls.startLevel=s[s.length-1].level),oi.MEDIUM&e.start_quality&&(t.hls.startLevel=s[Math.ceil(s.length/2)-1].level));const n=(null===(r=e.hls)||void 0===r?void 0:r.maxBufferSize)||1024,a=(null===(i=e.hls)||void 0===i?void 0:i.maxBufferLength)||30;ci("Setting maxBufferSize to %d",n),t.hls.config.maxBufferSize=n,"metadata"===e.preload&&ci("preload === metadata, setting maxBufferLength to 1sec");t.hls.config.maxBufferLength="metadata"===e.preload?1:a,t.once("playing",()=>{ci("Playback started, set maxBufferLenght to %d",a),t.hls&&(t.hls.config.maxBufferLength=a)}),("none"!==e.preload||e.autoplay)&&fi(t,e.start_time||-1)}(t,e,a.slice(0,-1));const o=a.find(t=>!!t.videoCodec);o||t.emit("audioonlysource"),!t.opt("ratio")&&o&&0!=o.width&&0!=o.height&&t.setOpts({ratio:o.width+":"+o.height})})),l.on(si.Events.INIT_PTS_FOUND,(function(t,e){n.fragDuration=e.frag.duration})),l.on(si.Events.ERROR,(function(e,s){!function(t,e,s){var r,i,n,a;if(0==t.reaper)return;if(0==e.fatal)return;switch(e.type){case si.ErrorTypes.MEDIA_ERROR:return ci("recovering from "+e.type),s.media_recovers+5e3>Date.now()&&0==s.audio_swaps?(null===(r=t.hls)||void 0===r||r.swapAudioCodec(),ci(`calling swapAudioCodec() : {count=${s.audio_swaps}}`),s.audio_swaps++,s.media_recovers=Date.now(),null===(i=t.hls)||void 0===i?void 0:i.recoverMediaError()):(s.media_recovers=Date.now(),s.audio_swaps=0,null===(n=t.hls)||void 0===n?void 0:n.recoverMediaError());case si.ErrorTypes.NETWORK_ERROR:return function(t,e){var s;const r=(null===(s=e.networkDetails)||void 0===s?void 0:s.status)||e.details;let i=t.opts.live?"http.live.":"http.";i+=r.toString();const n=t.i18n("error."+i,ai[i]||"an error occurred while loading this video");t.emit("error",{code:i,message:n,fatal:!0})}(t,e);case si.ErrorTypes.KEY_SYSTEM_ERROR:return function(t,e){var s;t.emit("error",{fatal:!0,message:ai[e.details]||"an error occurred while accessing this video"}),null===(s=t.hls)||void 0===s||s.destroy()}(t,e);default:null===(a=t.hls)||void 0===a||a.destroy()}}(t,s,n)})),l.on(si.Events.LEVEL_PTS_UPDATED,(function(e,s){var r;if("video"!==s.type&&(!n.is_audio_only||"audio"!==s.type))return;const i=null===(r=null==s?void 0:s.details)||void 0===r?void 0:r.fragments;if(!i)return;const a=i[0].start||0,o=(l.liveSyncPosition||i[i.length-1].start)+i[i.length-1].duration;t.emit("dvr/window",o-a)})),l.on(si.Events.LEVEL_SWITCHING,(e,s)=>{const r=l.levels[l.currentLevel],i=l.levels[s.level];t.emit("qualitychange",{before:r,after:i,kind:"hls"})});const u=t.opt("start_time");u&&t.once("loadedmetadata",(function(){t.currentTime=u}))}function fi(t,e){var s;!t.hasState("is-loaded")&&t.setState("is-loading",!0),null===(s=t.hls)||void 0===s||s.startLoad(e)}function gi(t){const e=t.map((t,e)=>({level:e,text:t.name||t.width+"",width:t.width,height:t.height,videoCodec:t.videoCodec||""})).sort((t,e)=>e.width-t.width);return t.length>1&&t.every(t=>void 0!==t.bitrate)&&e.push({text:"AUTO",level:-1,width:0,height:0,videoCodec:""}),e}class HLS{init(){}onload(t,e,s,r){ui(s,t,r,this)}wants(t,e,s){return Hls.isSupported()&&ei(e,s)}}return HLS.events=Xr,HLS.version=Hls.version,HLS.failover={Reasons:li},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;"function"==typeof s?s(e):(Array.isArray(s.extensions)||(s.extensions=[]),~s.extensions.indexOf(e)||s.extensions.push(e))}(window,HLS),HLS}));
|
|
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";var t={};function e(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 s(t){for(var s=1;s<arguments.length;s++){var i=null!=arguments[s]?arguments[s]:{};s%2?e(Object(i),!0).forEach((function(e){r(t,e,i[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))}))}return t}function r(t,e,s){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===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)}(e))in t?Object.defineProperty(t,e,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[e]=s,t}function i(){return(i=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)}!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}({get exports(){return t},set exports(e){t=e}});const n=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)};let a=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.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}({}),o=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}({}),l=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 h=function(){},d={trace:h,debug:h,log:h,warn:h,info:h,error:h};let c=d;function u(t,...e){e.forEach((function(e){c[e]=t[e]?t[e].bind(t):function(t){const e=self.console[t];return e?e.bind(self.console,`[${t}] >`):h}(e)}))}const f=c,g=/^(\d+)x(\d+)$/,m=/(.+?)=(".*?"|.*?)(?:,|$)/g;class AttrList{constructor(t){"string"==typeof t&&(t=AttrList.parseAttrList(t));for(const e in t)t.hasOwnProperty(e)&&("X-"===e.substring(0,2)&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(e)),this[e]=t[e])}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=g.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(m.lastIndex=0;null!==(e=m.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 p(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]){f.warn(`DATERANGE tag attribute: "${e}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=e;break}t=i(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"]);n(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(n(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&&n(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 y="audio",T="video",v="audiovideo";class BaseSegment{constructor(t){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[y]:null,[T]:null,[v]:null},this.baseurl=t}setByteRange(t,e){const s=t.split("@",2),r=[];1===s.length?r[0]=e?e.byteRangeEndOffset:0:r[0]=parseInt(s[1]),r[1]=parseInt(s[0])+r[0],this._byteRange=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=t.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.urlId=0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 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(!n(this.programDateTime))return null;const t=n(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[y]=null,t[T]=null,t[v]=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.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&&n(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 E(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function S(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=E(i)):s=function(t){const e=L(t).subarray(0,16),s=new Uint8Array(16);return s.set(e,16-e.length),s}(i)}}return s}function L(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}var A={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},R="org.w3.clearkey",b="com.apple.streamingkeydelivery",k="com.microsoft.playready",D="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function I(t){switch(t){case b:return A.FAIRPLAY;case k:return A.PLAYREADY;case D:return A.WIDEVINE;case R:return A.CLEARKEY}}var C="edef8ba979d64acea3c827dcd51d21ed";function w(t){switch(t){case A.FAIRPLAY:return b;case A.PLAYREADY:return k;case A.WIDEVINE:return D;case A.CLEARKEY:return R}}function _(t){const{drmSystems:e,widevineLicenseUrl:s}=t,r=e?[A.FAIRPLAY,A.WIDEVINE,A.PLAYREADY,A.CLEARKEY].filter(t=>!!e[t]):[];return!r[A.WIDEVINE]&&s&&r.push(A.WIDEVINE),r}const P="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function M(t,e,s){return Uint8Array.prototype.slice?t.slice(e,s):new Uint8Array(Array.prototype.slice.call(t,e,s))}const x=(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,F=(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,O=(t,e)=>{const s=e;let r=0;for(;x(t,e);){r+=10;r+=N(t,e+6),F(t,e+10)&&(r+=10),e+=r}if(r>0)return t.subarray(s,s+r)},N=(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},U=(t,e)=>x(t,e)&&N(t,e+6)+10<=t.length-e,B=t=>t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info,$=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),s=N(t,4);return{type:e,size:s,data:t.subarray(10,10+s)}},G=t=>{let e=0;const s=[];for(;x(t,e);){const r=N(t,e+6);e+=10;const i=e+r;for(;e+8<i;){const r=$(t.subarray(e)),i=K(r);i&&s.push(i),e+=r.size+10}F(t,e)&&(e+=10)}return s},K=t=>"PRIV"===t.type?H(t):"W"===t.type[0]?Y(t):V(t),H=t=>{if(t.size<2)return;const e=q(t.data,!0),s=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:s.buffer}},V=t=>{if(t.size<2)return;if("TXXX"===t.type){let e=1;const s=q(t.data.subarray(e),!0);e+=s.length+1;const r=q(t.data.subarray(e));return{key:t.type,info:s,data:r}}const e=q(t.data.subarray(1));return{key:t.type,data:e}},Y=t=>{if("WXXX"===t.type){if(t.size<2)return;let e=1;const s=q(t.data.subarray(e),!0);e+=s.length+1;const r=q(t.data.subarray(e));return{key:t.type,info:s,data:r}}const e=q(t.data);return{key:t.type,data:e}},W=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)}},q=(t,e=!1)=>{const s=X();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 j;function X(){return j||void 0===self.TextDecoder||(j=new self.TextDecoder("utf-8")),j}const z=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},Q=Math.pow(2,32)-1,J=[].push,Z={video:1,audio:2,id3:3,text:4};function tt(t){return String.fromCharCode.apply(null,t)}function et(t,e){const s=t[e]<<8|t[e+1];return s<0?65536+s:s}function st(t,e){const s=rt(t,e);return s<0?4294967296+s:s}function rt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function it(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 nt(t,e){const s=[];if(!e.length)return s;const r=t.byteLength;for(let i=0;i<r;){const n=st(t,i),a=n>1?i+n:r;if(tt(t.subarray(i+4,i+8))===e[0])if(1===e.length)s.push(t.subarray(i+8,a));else{const r=nt(t.subarray(i+8,a),e.slice(1));r.length&&J.apply(s,r)}i=a}return s}function at(t){const e=[],s=t[0];let r=8;const i=st(t,r);r+=4;r+=0===s?8:16,r+=2;let n=t.length+0;const a=et(t,r);r+=2;for(let s=0;s<a;s++){let s=r;const a=st(t,s);s+=4;const o=2147483647&a;if(1===(2147483648&a)>>>31)return f.warn("SIDX has hierarchical references (not supported)"),null;const l=st(t,s);s+=4,e.push({referenceSize:o,subsegmentDuration:l,info:{duration:l/i,start:n,end:n+o-1}}),n+=o,s+=4,r=s}return{earliestPresentationTime:0,timescale:i,version:s,referencesCount:a,references:e}}function ot(t){const e=[],s=nt(t,["moov","trak"]);for(let t=0;t<s.length;t++){const r=s[t],i=nt(r,["tkhd"])[0];if(i){let t=i[0],s=0===t?12:20;const n=st(i,s),a=nt(r,["mdia","mdhd"])[0];if(a){t=a[0],s=0===t?12:20;const i=st(a,s),o=nt(r,["mdia","hdlr"])[0];if(o){const t=tt(o.subarray(8,12)),s={soun:y,vide:T}[t];if(s){const t=nt(r,["mdia","minf","stbl","stsd"])[0];let a;t&&(a=tt(t.subarray(12,16))),e[n]={timescale:i,type:s},e[s]={timescale:i,id:n,codec:a}}}}}}return nt(t,["moov","mvex","trex"]).forEach(t=>{const s=st(t,4),r=e[s];r&&(r.default={duration:st(t,12),flags:st(t,20)})}),e}function lt(t){const e=nt(t,["schm"])[0];if(e){const s=tt(e.subarray(4,8));if("cbcs"===s||"cenc"===s)return nt(t,["schi","tenc"])[0]}return f.error("[eme] missing 'schm' box"),null}function ht(t){const e=st(t,0);let s=8;1&e&&(s+=4),4&e&&(s+=4);let r=0;const i=st(t,4);for(let n=0;n<i;n++){if(256&e){r+=st(t,s),s+=4}512&e&&(s+=4),1024&e&&(s+=4),2048&e&&(s+=4)}return r}function dt(t,e){const s=new Uint8Array(t.length+e.length);return s.set(t),s.set(e,t.length),s}function ct(t,e){const s=[],r=e.samples,i=e.timescale,n=e.id;let a=!1;return nt(r,["moof"]).map(o=>{const l=o.byteOffset-8;nt(o,["traf"]).map(o=>{const h=nt(o,["tfdt"]).map(t=>{const e=t[0];let s=st(t,4);return 1===e&&(s*=Math.pow(2,32),s+=st(t,8)),s/i})[0];return void 0!==h&&(t=h),nt(o,["tfhd"]).map(h=>{const d=st(h,4),c=16777215&st(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=st(h,p),p+=4),f&&(g=st(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)),nt(o,["trun"]).map(n=>{const o=n[0],h=16777215&st(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),S=0!=(2048&h);let L=0;const A=st(n,4);let R=8;d&&(c=st(n,R),R+=4),f&&(R+=4);let b=c+l;for(let l=0;l<A;l++){if(m?(p=st(n,R),R+=4):p=u,y?(v=st(n,R),R+=4):v=g,E&&(R+=4),S&&(L=0===o?st(n,R):rt(n,R),R+=4),e.type===T){let e=0;for(;e<v;){const n=st(r,b);if(b+=4,ut(a,r[b])){ft(r.subarray(b,b+n),a?2:1,t+L/i,s)}b+=n,e+=n+4}}t+=p/i}}))})})}),s}function ut(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function ft(t,e,s,r){const i=gt(t);let n=0;n+=e;let a=0,o=0,l=!1,h=0;for(;n<i.length;){a=0;do{if(n>=i.length)break;h=i[n++],a+=h}while(255===h);o=0;do{if(n>=i.length)break;h=i[n++],o+=h}while(255===h);const t=i.length-n;if(!l&&4===a&&n<i.length){l=!0;if(181===i[n++]){const t=et(i,n);if(n+=2,49===t){const t=st(i,n);if(n+=4,1195456820===t){const t=i[n++];if(3===t){const e=i[n++],o=31&e,l=64&e,h=l?2+3*o:0,d=new Uint8Array(h);if(l){d[0]=e;for(let t=1;t<h;t++)d[t]=i[n++]}r.push({type:t,payloadType:a,pts:s,bytes:d})}}}}}else if(5===a&&o<t){if(l=!0,o>16){const t=[];for(let e=0;e<16;e++){const s=i[n++].toString(16);t.push(1==s.length?"0"+s:s),3!==e&&5!==e&&7!==e&&9!==e||t.push("-")}const e=o-16,l=new Uint8Array(e);for(let t=0;t<e;t++)l[t]=i[n++];r.push({payloadType:a,pts:s,uuid:t.join(""),userData:q(l),userDataBytes:l})}}else if(o<t)n+=o;else if(o>t)break}}function gt(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 mt(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 pt={};class LevelKey{static clearKeyUriToKeyIdMap(){pt={}}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 b:case D:case k:case R: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||f.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=S(this.uri);if(e)switch(this.keyFormat){case D:this.pssh=e,e.length>=22&&(this.keyId=e.subarray(e.length-22,e.length-6));break;case k:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mt(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=E(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=pt[this.uri];if(!t){const e=Object.keys(pt).length%Number.MAX_SAFE_INTEGER;t=new Uint8Array(16);new DataView(t.buffer,12,4).setUint32(0,e),pt[this.uri]=t}this.keyId=t}return this}}const yt=/\{\$([a-zA-Z0-9-_]+)\}/g;function Tt(t){return yt.test(t)}function vt(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]=Et(t,n))}}function Et(t,e){if(null!==t.variableList||t.hasVariableRefs){const s=t.variableList;return e.replace(yt,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 St(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 Lt(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}"`))}const At={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}};function Rt(t,e){return MediaSource.isTypeSupported(`${e||"video"}/mp4;codecs="${t}"`)}const bt=/#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,kt=/#EXT-X-MEDIA:(.*)/g,Dt=/^#EXT(?:INF|-X-TARGETDURATION):/m,It=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Ct=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)/.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 convertAVC1ToAVCOTI(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}static resolve(e,s){return t.buildAbsoluteURL(s,e,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Dt.test(t)}static parseMasterPlaylist(t,e){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Tt(t)},r=[];let i;for(bt.lastIndex=0;null!=(i=bt.exec(t));)if(i[1]){var n;const t=new AttrList(i[1]);vt(s,t,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const a=Et(s,i[2]),o={attrs:t,bitrate:t.decimalInteger("AVERAGE-BANDWIDTH")||t.decimalInteger("BANDWIDTH"),name:t.NAME,url:M3U8Parser.resolve(a,e)},l=t.decimalResolution("RESOLUTION");l&&(o.width=l.width,o.height=l.height),Pt((t.CODECS||"").split(/[ ,]+/).filter(t=>t),o),o.videoCodec&&-1!==o.videoCodec.indexOf("avc1")&&(o.videoCodec=M3U8Parser.convertAVC1ToAVCOTI(o.videoCodec)),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);vt(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=wt(r,e,s);t.encrypted&&t.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(t)):f.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":{const t=new AttrList(r);vt(s,t,["NAME","VALUE","QUERYPARAM"]),St(s,t,e)}break;case"CONTENT-STEERING":{const t=new AttrList(r);vt(s,t,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:M3U8Parser.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=_t(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(kt.lastIndex=0;null!==(r=kt.exec(t));){const t=new AttrList(r[1]),n=t.TYPE;if(n){const r=a[n],l=i[n]||[];i[n]=l,vt(s,t,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const h={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",instreamId:t["INSTREAM-ID"],name:t.NAME||t.LANGUAGE||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:t.LANGUAGE,url:t.URI?M3U8Parser.resolve(t.URI,e):""};if(null!=r&&r.length){const t=M3U8Parser.findGroup(r,h.groupId)||r[0];Mt(h,t,"audioCodec"),Mt(h,t,"textCodec")}l.push(h)}}return i}static parseLevelPlaylist(t,e,s,r,a,o){const l=new LevelDetails(e),h=l.fragments;let d,c,u,g=null,m=0,p=0,y=0,T=0,v=null,E=new Fragment(r,e),S=-1,L=!1;for(It.lastIndex=0,l.m3u8=t,l.hasVariableRefs=Tt(t);null!==(d=It.exec(t));){L&&(L=!1,E=new Fragment(r,e),E.start=y,E.sn=m,E.cc=T,E.level=s,g&&(E.initSegment=g,E.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null));const t=d[1];if(t){E.duration=parseFloat(t);const e=(" "+d[2]).slice(1);E.title=e||null,E.tagList.push(e?["INF",t,e]:["INF",t])}else if(d[3]){if(n(E.duration)){E.start=y,u&&Ot(E,u,l),E.sn=m,E.level=s,E.cc=T,E.urlId=a,h.push(E);const t=(" "+d[3]).slice(1);E.relurl=Et(l,t),xt(E,v),v=E,y+=E.duration,m++,p=0,L=!0}}else if(d[4]){const t=(" "+d[4]).slice(1);v?E.setByteRange(t,v):E.setByteRange(t)}else if(d[5])E.rawProgramDateTime=(" "+d[5]).slice(1),E.tagList.push(["PROGRAM-DATE-TIME",E.rawProgramDateTime]),-1===S&&(S=h.length);else{if(d=d[0].match(Ct),!d){f.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),a=(" "+d[c+1]).slice(1),y=d[c+2]?(" "+d[c+2]).slice(1):"";switch(t){case"PLAYLIST-TYPE":l.type=a.toUpperCase();break;case"MEDIA-SEQUENCE":m=l.startSN=parseInt(a);break;case"SKIP":{const t=new AttrList(a);vt(l,t,["RECENTLY-REMOVED-DATERANGES"]);const e=t.decimalInteger("SKIPPED-SEGMENTS");if(n(e)){l.skippedSegments=e;for(let t=e;t--;)h.unshift(null);m+=e}const s=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");s&&(l.recentlyRemovedDateranges=s.split("\t"));break}case"TARGETDURATION":l.targetduration=Math.max(parseInt(a),1);break;case"VERSION":l.version=parseInt(a);break;case"EXTM3U":break;case"ENDLIST":l.live=!1;break;case"#":(a||y)&&E.tagList.push(y?[a,y]:[a]);break;case"DISCONTINUITY":T++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([t]);break;case"BITRATE":E.tagList.push([t,a]);break;case"DATERANGE":{const t=new AttrList(a);vt(l,t,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),vt(l,t,t.clientAttrs);const e=new DateRange(t,l.dateRanges[t.ID]);e.isValid||l.skippedSegments?l.dateRanges[e.id]=e:f.warn(`Ignoring invalid DATERANGE tag: "${a}"`),E.tagList.push(["EXT-X-DATERANGE",a]);break}case"DEFINE":{const t=new AttrList(a);vt(l,t,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in t?Lt(l,t,o):St(l,t,e)}break;case"DISCONTINUITY-SEQUENCE":T=parseInt(a);break;case"KEY":{const t=wt(a,e,l);if(t.isSupported()){if("NONE"===t.method){u=void 0;break}u||(u={}),u[t.keyFormat]&&(u=i({},u)),u[t.keyFormat]=t}else f.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${a}"`);break}case"START":l.startTimeOffset=_t(a);break;case"MAP":{const t=new AttrList(a);if(vt(l,t,["BYTERANGE","URI"]),E.duration){const i=new Fragment(r,e);Ft(i,t,s,u),g=i,E.initSegment=g,g.rawProgramDateTime&&!E.rawProgramDateTime&&(E.rawProgramDateTime=g.rawProgramDateTime)}else Ft(E,t,s,u),g=E,L=!0;break}case"SERVER-CONTROL":{const t=new AttrList(a);l.canBlockReload=t.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=t.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&t.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=t.optionalFloat("PART-HOLD-BACK",0),l.holdBack=t.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const t=new AttrList(a);l.partTarget=t.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=l.partList;t||(t=l.partList=[]);const s=p>0?t[t.length-1]:void 0,r=p++,i=new AttrList(a);vt(l,i,["BYTERANGE","URI"]);const n=new Part(i,E,e,r,s);t.push(n),E.duration+=n.duration;break}case"PRELOAD-HINT":{const t=new AttrList(a);vt(l,t,["URI"]),l.preloadHint=t;break}case"RENDITION-REPORT":{const t=new AttrList(a);vt(l,t,["URI"]),l.renditionReports=l.renditionReports||[],l.renditionReports.push(t);break}default:f.warn("line parsed but not handled: "+d)}}}v&&!v.relurl?(h.pop(),y-=v.duration,l.partList&&(l.fragmentHint=v)):l.partList&&(xt(E,v),E.cc=T,l.fragmentHint=E,u&&Ot(E,u,l));const A=h.length,R=h[0],b=h[A-1];if(y+=l.skippedSegments*l.targetduration,y>0&&A&&b){l.averagetargetduration=y/A;const t=b.sn;l.endSN="initSegment"!==t?t:0,l.live||(b.endList=!0),R&&(l.startCC=R.cc)}else l.endSN=0,l.startCC=0;return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,l.endCC=T,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),l}}function wt(t,e,s){var r,i;const n=new AttrList(t);vt(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&&f.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 _t(t){const e=new AttrList(t).decimalFloatingPoint("TIME-OFFSET");return n(e)?e:null}function Pt(t,e){["video","audio","text"].forEach(s=>{const r=t.filter(t=>function(t,e){const s=At[e];return!!s&&!0===s[t.slice(0,4)]}(t,s));if(r.length){const i=r.filter(t=>0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0));e[s+"Codec"]=i.length>0?i[0]:r[0],t=t.filter(t=>-1===r.indexOf(t))}}),e.unknownCodecs=t}function Mt(t,e,s){const r=e[s];r&&(t[s]=r)}function xt(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),n(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Ft(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 Ot(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 Nt="manifest",Ut="level",Bt="audioTrack",$t="subtitleTrack",Gt="main",Kt="audio",Ht="subtitle";function Vt(t){const{type:e}=t;switch(e){case Bt:return Kt;case $t:return Ht;default:return Gt}}function Yt(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(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(a.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:Nt,url:s,deliveryDirectives:null})}onLevelLoading(t,e){const{id:s,level:r,url:i,deliveryDirectives:n}=e;this.load({id:s,level:r,responseType:"text",type:Ut,url:i,deliveryDirectives:n})}onAudioTrackLoading(t,e){const{id:s,groupId:r,url:i,deliveryDirectives:n}=e;this.load({id:s,groupId:r,level:null,responseType:"text",type:Bt,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:$t,url:i,deliveryDirectives:n})}load(t){var e;const s=this.hls.config;let r,n=this.getInternalLoader(t);if(n){const e=n.context;if(e&&e.url===t.url)return void f.trace("[playlist-loader]: playlist request ongoing");f.log("[playlist-loader]: aborting previous loader for type: "+t.type),n.abort()}if(r=t.type===Nt?s.manifestLoadPolicy.default:i({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),null!=(e=t.deliveryDirectives)&&e.part){let e;if(t.type===Ut&&null!==t.level?e=this.hls.levels[t.level].details:t.type===Bt&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===$t&&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=i({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={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)}};n.load(t,o,l)}handleMasterPlaylist(t,e,s,r){const i=this.hls,n=t.data,o=Yt(t,s),l=M3U8Parser.parseMasterPlaylist(n,o);if(l.playlistParsingError)return void this.handleManifestParsingError(t,s,l.playlistParsingError,r,e);const{contentSteering:h,levels:d,sessionData:c,sessionKeys:u,startTimeOffset:g,variableList:m}=l;this.variableList=m;const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":T}=M3U8Parser.parseMasterPlaylistMedia(n,o,l);if(p.length){p.some(t=>!t.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(f.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new AttrList({}),bitrate:0,url:""}))}i.trigger(a.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:y,captions:T,contentSteering:h,url:o,stats:e,networkDetails:r,sessionData:c,sessionKeys:u,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(t,e,s,r,i){const o=this.hls,{id:l,level:h,type:d}=s,c=Yt(t,s),u=n(l)?l:0,f=n(h)?h:u,g=Vt(s),m=M3U8Parser.parseLevelPlaylist(t.data,c,f,g,u,this.variableList);if(d===Nt){const t={attrs:new AttrList({}),bitrate:0,details:m,name:"",url:c};o.trigger(a.MANIFEST_LOADED,{levels:[t],audioTracks:[],url:c,stats:e,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),s.levelDetails=m,this.handlePlaylistLoaded(m,t,e,s,r,i)}handleManifestParsingError(t,e,s,r,i){this.hls.trigger(a.ERROR,{type:o.NETWORK_ERROR,details:l.MANIFEST_PARSING_ERROR,fatal:e.type===Nt,url:t.url,err:s,error:s,reason:s.message,response:t,context:e,networkDetails:r,stats:i})}handleNetworkError(t,e,r=!1,i,n){let h=`A network ${r?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${t.type}`;t.type===Ut?h+=`: ${t.level} id: ${t.id}`:t.type!==Bt&&t.type!==$t||(h+=` id: ${t.id} group-id: "${t.groupId}"`);const d=new Error(h);f.warn("[playlist-loader]: "+h);let c=l.UNKNOWN,u=!1;const g=this.getInternalLoader(t);switch(t.type){case Nt:c=r?l.MANIFEST_LOAD_TIMEOUT:l.MANIFEST_LOAD_ERROR,u=!0;break;case Ut:c=r?l.LEVEL_LOAD_TIMEOUT:l.LEVEL_LOAD_ERROR,u=!1;break;case Bt:c=r?l.AUDIO_TRACK_LOAD_TIMEOUT:l.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case $t:c=r?l.SUBTITLE_TRACK_LOAD_TIMEOUT:l.SUBTITLE_LOAD_ERROR,u=!1}g&&this.resetInternalLoader(t.type);const m={type:o.NETWORK_ERROR,details:c,fatal:u,url:t.url,loader:g,context:t,error:d,networkDetails:e,stats:n};if(i){const r=(null==e?void 0:e.url)||t.url;m.response=s({url:r,data:void 0},i)}this.hls.trigger(a.ERROR,m)}handlePlaylistLoaded(t,e,s,r,i,n){const h=this.hls,{type:d,level:c,id:u,groupId:f,deliveryDirectives:g}=r,m=Yt(e,r),p=Vt(r),y="number"==typeof r.level&&p===Gt?c:void 0;if(!t.fragments.length){const t=new Error("No Segments found in Playlist");return void h.trigger(a.ERROR,{type:o.NETWORK_ERROR,details:l.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 T=t.playlistParsingError;if(T)h.trigger(a.ERROR,{type:o.NETWORK_ERROR,details:l.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:T,reason:T.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)),d){case Nt:case Ut:h.trigger(a.LEVEL_LOADED,{details:t,level:y||0,id:u||0,stats:s,networkDetails:i,deliveryDirectives:g});break;case Bt:h.trigger(a.AUDIO_TRACK_LOADED,{details:t,id:u||0,groupId:f||"",stats:s,networkDetails:i,deliveryDirectives:g});break;case $t:h.trigger(a.SUBTITLE_TRACK_LOADED,{details:t,id:u||0,groupId:f||"",stats:s,networkDetails:i,deliveryDirectives:g})}}}function Wt(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 qt(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){f.debug("[texttrack-utils]: "+s);const r=new self.TextTrackCue(e.startTime,e.endTime,e.text);r.id=e.id,t.addCue(r)}"disabled"===s&&(t.mode=s)}function jt(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 Xt(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)}var zt="org.id3",Qt="com.apple.quicktime.HLS",Jt="https://aomedia.org/emsg/ID3";function Zt(){if("undefined"!=typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}const te=(()=>{const t=Zt();try{new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function ee(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(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(t,e){this.media=e.media}onMediaDetaching(){this.id3Track&&(jt(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 Wt(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=Zt();for(let t=0;t<i.length;t++){const e=i[t].type;if(e===Jt&&!s||!r)continue;const a=G(i[t].data);if(a){const s=i[t].pts;let r=s+i[t].duration;r>te&&(r=te);r-s<=0&&(r=s+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!B(i)){this.updateId3CueEnds(s);const t=new n(s,r,"");t.value=i,e&&(t.type=e),this.id3Track.addCue(t)}}}}}updateId3CueEnds(t){var e;const s=null==(e=this.id3Track)?void 0:e.cues;if(s)for(let e=s.length;e--;){const r=s[e];r.startTime<t&&r.endTime===te&&(r.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===zt&&o:"video"===r?t=>t.type===Jt&&a:t=>t.type===zt&&o||t.type===Jt&&a,Xt(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,a=Object.keys(i);if(r){const t=Object.keys(s).filter(t=>!a.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 o=e.fragments[e.fragments.length-1];if(0===a.length||!n(null==o?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,h=Zt();for(let t=0;t<a.length;t++){const e=a[t],r=i[e],n=s[e],o=(null==n?void 0:n.cues)||{};let u=(null==n?void 0:n.durationKnown)||!1;const f=ee(r.startDate,l);let g=te;const m=r.endDate;if(m)g=ee(m,l),u=!0;else if(r.endOnNext&&!u){const t=a.reduce((t,e)=>{const s=i[e];return s.class===r.class&&s.id!==e&&s.startDate>r.startDate&&t.push(s),t},[]).sort((t,e)=>t.startDate.getTime()-e.startDate.getTime())[0];t&&(g=ee(t.startDate,l),u=!0)}const y=Object.keys(r.attr);for(let t=0;t<y.length;t++){const s=y[t];if("ID"===(c=s)||"CLASS"===c||"START-DATE"===c||"DURATION"===c||"END-DATE"===c||"END-ON-NEXT"===c)continue;let i=o[s];if(i)u&&!n.durationKnown&&(i.endTime=g);else{let t=r.attr[s];i=new h(f,g,""),p(s)&&(d=t,t=Uint8Array.from(d.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer),i.value={key:s,data:t},i.type=Qt,i.id=e,this.id3Track.addCue(i),o[s]=i}}s[e]={cues:o,dateRange:r,durationKnown:u}}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(a.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(a.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(a.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(a.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(a.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===l.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(s=this.levelDetails)&&s.live&&f.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)return;const n=this.targetLatency;if(null===n)return;const a=s-n,o=a<Math.min(this.maxLatency,n+e.targetduration);if(e.live&&o&&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 se=["NONE","TYPE-0","TYPE-1",null];var re="",ie="YES",ne="v2";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.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=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.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.unknownCodecs=t.unknownCodecs,this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>t).join(",").replace(/\.[^.,]+/g,"")}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get attrs(){return this._attrs[this._urlId]}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get uri(){return this.url[this._urlId]||""}get urlId(){return this._urlId}set urlId(t){const e=t%this.url.length;this._urlId!==e&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=e)}get audioGroupId(){var t;return null==(t=this.audioGroupIds)?void 0:t[this.urlId]}get textGroupId(){var t;return null==(t=this.textGroupIds)?void 0:t[this.urlId]}addFallback(t){this.url.push(t.url),this._attrs.push(t.attrs)}}function ae(t,e){const s=e.startPTS;if(n(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,a){r-s<=0&&(f.warn("Fragment should have a positive duration",e),r=s+e.duration,a=i+e.duration);let o=s,l=r;const h=e.startPTS,d=e.endPTS;if(n(h)){const t=Math.abs(h-s);n(e.deltaPTS)?e.deltaPTS=Math.max(t,e.deltaPTS):e.deltaPTS=t,o=Math.max(s,h),s=Math.min(s,h),i=Math.min(i,e.startDTS),l=Math.min(r,d),r=Math.max(r,d),a=Math.max(a,e.endDTS)}const c=s-e.start;0!==e.start&&(e.start=s),e.duration=r-e.start,e.startPTS=s,e.maxStartPTS=o,e.startDTS=i,e.endPTS=r,e.minEndPTS=l,e.endDTS=a;const u=e.sn;if(!t||u<t.startSN||u>t.endSN)return 0;let g;const m=u-t.startSN,p=t.fragments;for(p[m]=e,g=m;g>0;g--)ae(p[g],p[g-1]);for(g=m;g<p.length-1;g++)ae(p[g],p[g+1]);return t.fragmentHint&&ae(p[p.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,c}function le(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 a,o=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&&(o=t.cc-r.cc),n(t.startPTS)&&n(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&&(a=r),e.PTSKnown=e.alignedSliding=!0),r.elementaryStreams=t.elementaryStreams,r.loader=t.loader,r.stats=t.stats,r.urlId=t.urlId,t.initSegment&&(r.initSegment=t.initSegment,s=t.initSegment)}),s){(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(t=>{var e;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){f.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=i({},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:f.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[t].attr)}"`)}),r}(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const l=e.fragments;if(o){f.warn("discontinuity sliding from playlist, take drift into account");for(let t=0;t<l.length;t++)l[t].cc+=o}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}),a?oe(e,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS):he(t,e),l.length&&(e.totalduration=e.edge-l[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 he(t,e){const s=e.startSN+e.skippedSegments-t.startSN,r=t.fragments;s<0||s>=r.length||de(e,r[s].start)}function de(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 ce(t,e,s){var r;return null!=t&&t.details?ue(null==(r=t.details)?void 0:r.partList,e,s):null}function ue(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 fe(t){switch(t.details){case l.FRAG_LOAD_TIMEOUT:case l.KEY_LOAD_TIMEOUT:case l.LEVEL_LOAD_TIMEOUT:case l.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ge(t,e){const s=fe(e);return t.default[(s?"timeout":"error")+"Retry"]}function me(t,e){const s="linear"===t.backoff?1:Math.pow(2,e);return Math.min(s*t.retryDelayMs,t.maxRetryDelayMs)}function pe(t){return s(s({},t),{errorRetry:null,timeoutRetry:null})}function ye(t,e,s,r){return!!t&&e<t.maxNumRetry&&(function(t){return 0===t&&!1===navigator.onLine||!!t&&(t<400||t>499)}(r)||!!s)}const Te=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 ve(t,e,s=0,r=0){let i=null;if(t?i=e[t.sn-e[0].sn+1]||null:0===s&&0===e[0].start&&(i=e[0]),i&&0===Ee(s,r,i))return i;const n=Te(e,Ee.bind(null,s,r));return!n||n===t&&i?i:n}function Ee(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 Se(t,e,s){const r=1e3*Math.min(e,s.duration+(s.deltaPTS?s.deltaPTS:0));return(s.endProgramDateTime||0)-r>t}var Le=0,Ae=2,Re=5,be=0,ke=1,De=2;function Ie(t,e,s){if(performance.now()-t.lastErrorPerfMs>3e5)return!0;const r=t.details;if(e.details===l.FRAG_GAP&&r&&e.frag){const t=e.frag.start,s=ve(null,r.fragments,t);if(s&&!s.gap)return!0}if(s&&t.errors.length<s.errors.length){const s=t.errors[t.errors.length-1];if(r&&s.frag&&e.frag&&Math.abs(s.frag.start-e.frag.start)>3*r.targetduration)return!0}return!1}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=f.log.bind(f,e+":"),this.warn=f.warn.bind(f,e+":"),this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){clearTimeout(this.timer),this.timer=-1}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,e){const s=null==e?void 0:e.renditionReports;if(s){let r=-1;for(let i=0;i<s.length;i++){const n=s[i];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){f.warn("Could not construct new URL for Rendition Report: "+t),a=n.URI||""}if(a===t){r=i;break}a===t.substring(0,a.length)&&(r=i)}if(-1!==r){const t=s[r],i=parseInt(t["LAST-MSN"])||(null==e?void 0:e.lastPartSn);let n=parseInt(t["LAST-PART"])||(null==e?void 0:e.lastPartIndex);if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);n>=0&&t>e.partTarget&&(n+=1)}return new HlsUrlParameters(i,n>=0?n:void 0,re)}}}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:"MISSED"}`),s&&r.fragments.length>0&&le(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&&(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=function(t,e){const{canSkipUntil:s,canSkipDateRanges:r,endSN:i}=t;return s&&(void 0!==e?e-i:0)<s?r?ne:ie:re}(t,s);return null!=e&&e.skip&&t.deltaUpdateFailed&&(s=e.msn,r=e.part,i=re),new HlsUrlParameters(s,r,i)}checkRetry(t){const e=t.details,s=fe(t),r=t.errorAction,{action:i,retryCount:n=0,retryConfig:a}=r||{},o=i===Re&&!!r&&!!a;if(o){var l;if(this.requestScheduled=-1,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=me(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}}let Ce;class LevelController extends BasePlaylistController{constructor(t,e){super(t,"[level-controller]"),this._levels=[],this._firstLevel=-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(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}startLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const s=[],r={};let i;e.levels.forEach(t=>{var e;const n=t.attrs;-1!==(null==(e=t.audioCodec)?void 0:e.indexOf("mp4a.40.34"))&&(Ce||(Ce=/chrome|firefox/i.test(navigator.userAgent)),Ce&&(t.audioCodec=void 0));const{AUDIO:a,CODECS:o,"FRAME-RATE":l,"PATHWAY-ID":h,RESOLUTION:d,SUBTITLES:c}=n,u=`${(h||".")+"-"}${t.bitrate}-${d}-${l}-${o}`;i=r[u],i?i.addFallback(t):(i=new Level(t),r[u]=i,s.push(i)),we(i,"audio",a),we(i,"text",c)}),this.filterAndSortMediaOptions(s,e)}filterAndSortMediaOptions(t,e){let s=[],r=[],i=!1,n=!1,h=!1,d=t.filter(({audioCodec:t,videoCodec:e,width:s,height:r,unknownCodecs:a})=>(i||(i=!(!s||!r)),n||(n=!!e),h||(h=!!t),!(null!=a&&a.length)&&(!t||Rt(t,"audio"))&&(!e||Rt(e,"video"))));if((i||n)&&h&&(d=d.filter(({videoCodec:t,width:e,height:s})=>!!t||!(!e||!s))),0===d.length)return void Promise.resolve().then(()=>{if(this.hls){const t=new Error("no level with compatible codecs found in manifest");this.hls.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:t,reason:t.message})}});e.audioTracks&&(s=e.audioTracks.filter(t=>!t.audioCodec||Rt(t.audioCodec,"audio")),_e(s)),e.subtitles&&(r=e.subtitles,_e(r));const c=d.slice(0);d.sort((t,e)=>t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"]?(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1:t.bitrate!==e.bitrate?t.bitrate-e.bitrate:t.attrs["FRAME-RATE"]!==e.attrs["FRAME-RATE"]?t.attrs.decimalFloatingPoint("FRAME-RATE")-e.attrs.decimalFloatingPoint("FRAME-RATE"):t.attrs.SCORE!==e.attrs.SCORE?t.attrs.decimalFloatingPoint("SCORE")-e.attrs.decimalFloatingPoint("SCORE"):i&&t.height!==e.height?t.height-e.height:0);let u=c[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==c.length))for(let t=0;t<c.length;t++)if(c[t].pathwayId===d[0].pathwayId){u=c[t];break}this._levels=d;for(let t=0;t<d.length;t++)if(d[t]===u){this._firstLevel=t,this.log(`manifest loaded, ${d.length} level(s) found, first bitrate: ${u.bitrate}`);break}const f=h&&!n,g={levels:d,audioTracks:s,subtitleTracks:r,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:h,video:n,altAudio:!f&&s.some(t=>!!t.url)};this.hls.trigger(a.MANIFEST_PARSED,g),(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(a.ERROR,{type:o.OTHER_ERROR,details:l.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,n=r?r.attrs["PATHWAY-ID"]:void 0,h=e[t],d=h.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=h,s===t&&h.details&&r&&n===d)return;this.log(`Switching to level ${t}${d?" with Pathway "+d:""} from level ${s}${n?" with Pathway "+n:""}`);const c=i({},h,{level:t,maxBitrate:h.maxBitrate,attrs:h.attrs,uri:h.uri,urlId:h.urlId});delete c._attrs,delete c._urlId,this.hls.trigger(a.LEVEL_SWITCHING,c);const u=h.details;if(!u||u.live){const t=this.switchParams(h.uri,null==r?void 0:r.details);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel}set startLevel(t){this._startLevel=t}onError(t,e){!e.fatal&&e.context&&e.context.type===Ut&&e.context.level===this.level&&this.checkRetry(e)}onFragLoaded(t,{frag:e}){if(void 0!==e&&e.type===Gt){const t=this._levels[e.level];void 0!==t&&(t.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)}onAudioTrackSwitched(t,e){const s=this.currentLevel;if(!s)return;const r=this.hls.audioTracks[e.id].groupId;if(s.audioGroupIds&&s.audioGroupId!==r){let t=-1;for(let e=0;e<s.audioGroupIds.length;e++)if(s.audioGroupIds[e]===r){t=e;break}-1!==t&&t!==s.urlId&&(s.urlId=t,this.canLoad&&this.startLoad())}}loadPlaylist(t){super.loadPlaylist();const e=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){const r=s.urlId;let i=s.uri;if(t)try{i=t.addDirectives(i)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}const n=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${n?" Pathway "+n:""} URI ${r+1}/${s.url.length} ${i}`),this.clearTimer(),this.hls.trigger(a.LEVEL_LOADING,{url:i,level:e,id:r,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,e){const s=(t,s)=>s!==e,r=this._levels.filter((r,i)=>i!==t||(r.url.length>1&&void 0!==e?(r.url=r.url.filter(s),r.audioGroupIds&&(r.audioGroupIds=r.audioGroupIds.filter(s)),r.textGroupIds&&(r.textGroupIds=r.textGroupIds.filter(s)),r.urlId=0,!0):(this.steering&&this.steering.removeLevel(r),!1)));this.hls.trigger(a.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(t,{levels:e}){e.forEach((t,e)=>{const{details:s}=t;null!=s&&s.fragments&&s.fragments.forEach(t=>{t.level=e})}),this._levels=e}}function we(t,e,s){s&&("audio"===e?(t.audioGroupIds||(t.audioGroupIds=[]),t.audioGroupIds[t.url.length-1]=s):"text"===e&&(t.textGroupIds||(t.textGroupIds=[]),t.textGroupIds[t.url.length-1]=s))}function _e(t){const e={};t.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}var Pe="NOT_LOADED",Me="APPENDING",xe="PARTIAL",Fe="OK";class FragmentTracker{constructor(t){this.mainFragEntity=null,this.activeParts=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(a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.endListFragments=this.timeRanges=this.mainFragEntity=this.activeParts=null}getAppendedFrag(t,e){if(e===Gt){const{mainFragEntity:e,activeParts:s}=this;if(e)if(e&&s)for(let r=s.length;r--;){const i=s[r],n=i?i.end:e.appendedPTS;if(i.start<=t&&null!==n&&t<=n)return r>9&&(this.activeParts=s.slice(r-9)),i}else if(e.body.start<=t&&null!==e.appendedPTS&&t<=e.appendedPTS)return e.body}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){this.timeRanges&&(this.timeRanges[t]=e),Object.keys(this.fragments).forEach(r=>{const i=this.fragments[r];if(!i)return;if(!i.buffered&&!i.loaded)return void(i.body.type===s&&this.removeFragment(i.body));const n=i.range[t];n&&n.time.some(t=>{const s=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return s&&this.removeFragment(i.body),s})})}detectPartialFragments(t){const e=this.timeRanges,{frag:s,part:r}=t;if(!e||"initSegment"===s.sn)return;const i=Ne(s),n=this.fragments[i];n&&(Object.keys(e).forEach(t=>{const i=s.elementaryStreams[t];if(!i)return;const a=e[t],o=null!==r||!0===i.partial;n.range[t]=this.getBufferedTimes(s,r,o,a)}),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,n.body.endList&&(this.endListFragments[n.body.type]=n)):this.removeFragment(n.body))}fragBuffered(t,e){const s=Ne(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=e?e.start:t.start,a=e?e.end: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)i.partial=!0,i.time.push({startPTS:Math.max(n,r.start(t)),endPTS:Math.min(a,r.end(t))});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&&Oe(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||Oe(e))}getState(t){const e=Ne(t),s=this.fragments[e];return s?s.buffered?Oe(s)?xe:Fe:Me:Pe}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||r)return;const i=Ne(s);this.fragments[i]={body:s,appendedPTS:null,loaded:e,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:s,part:r,timeRanges:i}=e;let n=this.mainFragEntity;if(s.type===Gt){const t=n?n.body:null;if(t!==s){n&&t&&t.sn!==s.sn&&(n.buffered=!0,this.fragments[Ne(t)]=n);const e=Ne(s);n=this.mainFragEntity=this.fragments[e]||{body:s,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)}}if(r){let t=this.activeParts;t||(this.activeParts=t=[]),t.push(r)}else this.activeParts=null}this.timeRanges=i,Object.keys(i).forEach(t=>{const e=i[t];if(this.detectEvictedFragments(t,e),!r&&n){const r=s.elementaryStreams[t];if(!r)return;for(let t=0;t<e.length;t++){const s=e.end(t);s<=r.endPTS&&s>r.startPTS?n.appendedPTS=Math.max(s,n.appendedPTS||0):n.appendedPTS=r.endPTS}}})}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Ne(t);return!!this.fragments[e]}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=Ne(t);t.stats.loaded=0,t.clearElementaryStreamInfo(),this.mainFragEntity===this.fragments[e]&&(this.mainFragEntity=null),delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.mainFragEntity=null,this.activeParts=null,this.hasGaps=!1}}function Oe(t){var e,s;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(s=t.range.audio)?void 0:s.partial))}function Ne(t){return`${t.type}_${t.level}_${t.urlId}_${t.sn}`}const Ue=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 r=t.url;if(!r)return Promise.reject(new LoadError({type:o.NETWORK_ERROR,details:l.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(r?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,n=i.fLoader,a=i.loader;return new Promise((h,d)=>{if(this.loader&&this.loader.destroy(),t.gap)return void d($e(t));const c=this.loader=t.loader=n?new n(i):new a(i),u=Be(t),f=pe(i.fragLoadPolicy.default),g={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Ue};t.stats=c.stats,c.load(u,g,{onSuccess:(e,s,r,i)=>{this.resetLoader(t,c);let n=e.data;r.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),h({frag:t,part:null,payload:n,networkDetails:i})},onError:(e,i,n,a)=>{this.resetLoader(t,c),d(new LoadError({type:o.NETWORK_ERROR,details:l.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:s({url:r,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:n,stats:a}))},onAbort:(e,s,r)=>{this.resetLoader(t,c),d(new LoadError({type:o.NETWORK_ERROR,details:l.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:r,stats:e}))},onTimeout:(e,s,r)=>{this.resetLoader(t,c),d(new LoadError({type:o.NETWORK_ERROR,details:l.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,r){this.abort();const i=this.config,n=i.fLoader,a=i.loader;return new Promise((h,d)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void d($e(t,e));const c=this.loader=t.loader=n?new n(i):new a(i),u=Be(t,e),f=pe(i.fragLoadPolicy.default),g={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Ue};e.stats=c.stats,c.load(u,g,{onSuccess:(s,i,n,a)=>{this.resetLoader(t,c),this.updateStatsFromPart(t,e);const o={frag:t,part:e,payload:s.data,networkDetails:a};r(o),h(o)},onError:(r,i,n,a)=>{this.resetLoader(t,c),d(new LoadError({type:o.NETWORK_ERROR,details:l.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:s({url:u.url,data:void 0},r),error:new Error(`HTTP Error ${r.code} ${r.text}`),networkDetails:n,stats:a}))},onAbort:(s,r,i)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,c),d(new LoadError({type:o.NETWORK_ERROR,details:l.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:i,stats:s}))},onTimeout:(s,r,i)=>{this.resetLoader(t,c),d(new LoadError({type:o.NETWORK_ERROR,details:l.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 Be(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,a=s.byteRangeEndOffset;if(n(i)&&n(a)){var o;let e=i,s=a;if("initSegment"===t.sn&&"AES-128"===(null==(o=t.decryptdata)?void 0:o.method)){const t=a-i;t%16&&(s=a+(16-t%16)),0!==i&&(r.resetIV=!0,e=i-16)}r.rangeStart=e,r.rangeEnd=s}return r}function $e(t,e){const s=new Error(`GAP ${t.gap?"tag":"attribute"} found`),r={type:o.MEDIA_ERROR,details:l.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 KeyLoader{constructor(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}abort(){for(const t in this.keyUriToKeyInfo){const e=this.keyUriToKeyInfo[t].loader;e&&e.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=l.KEY_LOAD_ERROR,s,r,i){return new LoadError({type:o.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,l.KEY_LOAD_ERROR,s))}const n=i.uri;if(!n)return Promise.reject(this.createKeyLoadError(t,l.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,l.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 r=this.config,i=new(0,r.loader)(r);return e.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((n,a)=>{const o={keyInfo:t,frag:e,responseType:"arraybuffer",url:t.decryptdata.uri},h=r.keyLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,e,s,r)=>{const{frag:i,keyInfo:o,url:h}=s;if(!i.decryptdata||o!==this.keyUriToKeyInfo[h])return a(this.createKeyLoadError(i,l.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,r,i,n)=>{this.resetLoader(r),a(this.createKeyLoadError(e,l.KEY_LOAD_ERROR,new Error(`HTTP Error ${t.code} loading key ${t.text}`),i,s({url:o.url,data:void 0},t)))},onTimeout:(t,s,r)=>{this.resetLoader(s),a(this.createKeyLoadError(e,l.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(t,s,r)=>{this.resetLoader(s),a(this.createKeyLoadError(e,l.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};i.load(o,d,c)})}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()}}const Ge={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 f.log("failed to get media.buffered",t),Ge}}}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 Ke(t,e){let s=null;for(let r=0,i=t.length;r<i;r++){const i=t[r];if(i&&i.cc===e){s=i;break}}return s}function He(t,e){if(t){const s=t.start+e;t.start=t.startPTS=s,t.endPTS=s+t.duration}}function Ve(t,e){const s=e.fragments;for(let e=0,r=s.length;e<r;e++)He(s[e],t);e.fragmentHint&&He(e.fragmentHint,t),e.alignedSliding=!0}function Ye(t,e,s){e&&(!function(t,e,s){if(function(t,e,s){return!(!e.details||!(s.endCC>s.startCC||t&&t.cc<s.startCC))}(t,s,e)){const t=function(t,e,s=0){const r=t.fragments,i=e.fragments;if(!i.length||!r.length)return void f.log("No fragments to align");const n=Ke(r,i[0].cc);if(n&&(!n||n.startPTS))return n;f.log("No frag in previous level to align on")}(s.details,e);t&&n(t.start)&&(f.log("Adjusting PTS using last level due to CC increase within current level "+e.url),Ve(t.start,e))}}(t,s,e),!s.alignedSliding&&e.details&&function(t,e){if(!e.fragments.length||!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=e.fragments[0].programDateTime,r=t.fragments[0].programDateTime,i=(r-s)/1e3+e.fragments[0].start;i&&n(i)&&(f.log(`Adjusting PTS using programDateTime delta ${r-s}ms, sliding:${i.toFixed(3)} ${t.url} `),Ve(i,t))}(s,e.details),s.alignedSliding||!e.details||s.skippedSegments||he(e.details,s))}function We(t,e){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,r=e.fragments;if(!s.length||!r.length)return;const i=r[Math.round(r.length/2)-1],n=Ke(s,i.cc)||s[Math.round(s.length/2)-1],a=i.programDateTime,o=n.programDateTime;if(null===a||null===o)return;Ve((o-a)/1e3-(n.start-i.start),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,T;for(a=0;a<n;a++)a<i?y=l[a]=e[a]:(T=y,a%i==0?(T=T<<8|T>>>24,T=d[T>>>24]<<24|d[T>>>16&255]<<16|d[T>>>8&255]<<8|d[255&T],T^=c[a/i|0]<<24):i>6&&a%i==4&&(T=d[T>>>24]<<24|d[T>>>16&255]<<16|d[T>>>8&255]<<8|d[255&T]),l[a]=y=(l[a-i]^T)>>>0);for(o=0;o<n;o++)a=n-o,T=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?T:f[d[T>>>24]]^g[d[T>>>16&255]]^m[d[T>>>8&255]]^p[d[255&T]],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 T,v,E,S,L,A,R,b,k,D,I,C,w,_;const P=this.networkToHostOrderSwap;for(;e<p.length;){for(k=P(p[e]),D=P(p[e+1]),I=P(p[e+2]),C=P(p[e+3]),L=k^i[0],A=C^i[1],R=I^i[2],b=D^i[3],w=4,_=1;_<r;_++)T=o[L>>>24]^l[A>>16&255]^h[R>>8&255]^d[255&b]^i[w],v=o[A>>>24]^l[R>>16&255]^h[b>>8&255]^d[255&L]^i[w+1],E=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=T,A=v,R=E,b=S,w+=4;T=n[L>>>24]<<24^n[A>>16&255]<<16^n[R>>8&255]<<8^n[255&b]^i[w],v=n[A>>>24]<<24^n[R>>16&255]<<16^n[b>>8&255]<<8^n[255&L]^i[w+1],E=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]=P(T^u),y[e+1]=P(S^f),y[e+2]=P(E^g),y[e+3]=P(v^m),u=k,f=D,g=I,m=C,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?M(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=dt(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=M(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=>(f.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=M(t,0,s),this.remainderData=M(t,s)),e}logOnce(t){this.logEnabled&&(f.log("[decrypter]: "+t),this.logEnabled=!1)}}const qe=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},je="STOPPED",Xe="IDLE",ze="KEY_LOADING",Qe="FRAG_LOADING",Je="FRAG_LOADING_WAITING_RETRY",Ze="WAITING_TRACK",ts="PARSING",es="PARSED",ss="ENDED",rs="ERROR",is="WAITING_INIT_PTS",ns="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=je,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=f.log.bind(f,r+":"),this.warn=f.warn.bind(f,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(a.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort();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=je}_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.levels[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===je&&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,a=s?s.currentTime:0,o=BufferHelper.bufferInfo(r||s,a,t.maxBufferHole);if(this.log(`media seeking to ${n(a)?a.toFixed(3):a}, state: ${i}`),this.state===ss)this.resetLoadingState();else if(e){const s=t.maxFragLookUpTolerance,r=e.start-s,i=e.start+e.duration+s;if(!o.len||i<o.start||r>o.end){const t=a>i;(a<r||t)&&(t&&e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.abortRequests()),this.resetLoadingState())}}s&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),this.loadedmetadata||o.len||(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=je,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===Qe||!this.fragCurrent&&s===ts)&&(this.fragmentTracker.removeFragment(t),this.state=Xe):("payload"in e&&(this.log(`Loaded fragment ${t.sn} of level ${t.level}`),this.hls.trigger(a.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e))}).catch(e=>{this.state!==je&&this.state!==rs&&(this.warn(e),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;if(this.fragmentTracker.getState(t)===Me){const e=t.type,s=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,s?s.len:this.config.maxBufferLength);this.reduceMaxBufferLength(r)&&this.fragmentTracker.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)&&this.fragmentTracker.removeAllFragments()}flushMainBuffer(t,e,s=null){if(!(t-e))return;const r={startOffset:t,endOffset:e,type:s};this.hls.trigger(a.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&&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(a.ERROR,{type:o.MEDIA_ERROR,details:l.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(r=>{const i=self.performance.now();return s.trigger(a.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:n,tdecrypt:i}}),e.payload=r,e})}return e}).then(s=>{const{fragCurrent:r,hls:i,levels:n}=this;if(!n)throw new Error("init load aborted, missing levels");const o=t.stats;this.state=Xe,e.fragmentError=0,t.data=new Uint8Array(s.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),s.frag===r&&i.trigger(a.FRAG_BUFFERED,{stats:o,frag:r,part:null,id:t.type}),this.tick()}).catch(e=>{this.state!==je&&this.state!==rs&&(this.warn(e),this.resetFragmentLoading(t))})}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId}fragBufferedComplete(t,e){var s,r,i,n;const a=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level} (frag:[${(null!=(s=t.startPTS)?s:NaN).toFixed(3)}-${(null!=(r=t.endPTS)?r:NaN).toFixed(3)}] > buffer:${a?qe(BufferHelper.getBuffered(a)):"(detached)"})`),this.state=Xe,a&&(!this.loadedmetadata&&t.type==Gt&&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 o=null==e?void 0:e.details;if(!this.levels||!o)throw new Error(`frag load aborted, missing level${o?"":" detail"}s`);let l=null;if(!t.encrypted||null!=(i=t.decryptdata)&&i.key?!t.encrypted&&o.encryptedFragments.length&&this.keyLoader.loadClear(t,o.encryptedFragments):(this.log(`Loading key for ${t.sn} of [${o.startSN}-${o.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${t.level}`),this.state=ze,this.fragCurrent=t,l=this.keyLoader.load(t).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(a.KEY_LOADED,t),this.state===ze&&(this.state=Xe),t}),this.hls.trigger(a.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(l=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),s=Math.max(t.start,s||0),this.config.lowLatencyMode){const i=o.partList;if(i&&r){s>t.end&&o.fragmentHint&&(t=o.fragmentHint);const n=this.getNextPart(i,t,s);if(n>-1){const h=i[n];let d;return this.log(`Loading part sn: ${t.sn} p: ${h.index} cc: ${t.cc} of playlist [${o.startSN}-${o.endSN}] parts [0-${n}-${i.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=h.start+h.duration,this.state=Qe,d=l?l.then(s=>!s||this.fragContextChanged(s.frag)?null:this.doFragPartsLoad(t,h,e,r)).catch(t=>this.handleFragLoadError(t)):this.doFragPartsLoad(t,h,e,r).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(a.FRAG_LOADING,{frag:t,part:h,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):d}if(!t.url||this.loadedEndOfParts(i,s))return Promise.resolve(null)}}this.log(`Loading fragment ${t.sn} cc: ${t.cc} ${o?"of ["+o.startSN+"-"+o.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${t.level}, target: ${parseFloat(s.toFixed(3))}`),n(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Qe;const h=this.config.progressive;let d;return d=h&&l?l.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,h?r:void 0),l]).then(([t])=>(!h&&t&&r&&r(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(a.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(t,e,s,r){return new Promise((i,n)=>{var o;const l=[],h=null==(o=s.details)?void 0:o.partList,d=e=>{this.fragmentLoader.loadPart(t,e,r).then(r=>{l[e.index]=r;const n=r.part;this.hls.trigger(a.FRAG_LOADED,r);const o=ce(s,t.sn,e.index+1)||ue(h,t.sn,e.index+1);if(!o)return i({frag:t,part:n,partsLoaded:l});d(o)}).catch(n)};d(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;t.data&&e.details===l.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(a.ERROR,e)}else this.hls.trigger(a.ERROR,{type:o.OTHER_ERROR,details:l.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==ts)return void(this.fragCurrent||this.state===je||this.state===rs||(this.state=Xe));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?ce(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){var i;if(!t||this.state!==ts)return;const{data1:n,data2:o}=t;let l=n;if(n&&o&&(l=dt(n,o)),null==(i=l)||!i.length)return;const h={type:t.type,frag:e,part:s,chunkMeta:r,parent:e.type,data:l};this.hls.trigger(a.BUFFER_APPENDING,h),t.dropped&&t.independent&&!s&&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 n(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)}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 n=i.initialLiveManifestSize;if(r<n)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${n})`),null;e.PTSKnown||this.startFragRequested||-1!==this.startPosition||(a=this.getInitialLiveFragment(e,s),this.startPosition=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===Fe||s===xe&&!!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||!n(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(Se(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 Te(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=!!(r.lowLatencyMode&&s.partList&&o);let d;if(h&&o&&!this.bitrateTest&&(n=n.concat(o),a=o.sn),t<e){d=ve(i,n,t,t>e-l?0:l)}else d=n[n.length-1];if(d){const t=d.sn-s.startSN,e=this.fragmentTracker.getState(d);if((e===Fe||e===xe&&d.gap)&&(i=d),i&&d.sn===i.sn&&!h){if(i&&d.level===i.level){const e=n[t+1];d=d.sn<a&&this.fragmentTracker.getState(e)!==Fe?e:null}}}return d}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){const{levels:s,levelLastLoaded:r,fragPrevious:i}=this,a=null!==r?s[r]:null,o=t.fragments.length;if(!o)return this.warn("No fragments in live playlist"),0;const l=t.fragments[0].start,h=!e,d=t.alignedSliding&&n(l);if(h||!d&&!l){Ye(i,a,t);const s=t.fragments[0].start;return this.log(`Live playlist sliding: ${s.toFixed(2)} start-sn: ${e?e.startSN:"na"}->${t.startSN} prev-sn: ${i?i.sn:"na"} fragments: ${o}`),s}return l}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&&n(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===Je)||(this.state=Xe)}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===l.FRAG_GAP;i&&this.fragmentTracker.fragBuffered(s,!0);const n=e.errorAction,{action:a,retryCount:o=0,retryConfig:h}=n||{};if(n&&a===Re&&h){this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition);const r=me(h,o);this.warn(`Fragment ${s.sn} of ${t} ${s.level} errored with ${e.details}, retrying loading ${o+1}/${h.maxNumRetry} in ${r}ms`),n.resolved=!0,this.retryDate=self.performance.now()+r,this.state=Je}else h&&n?(this.resetFragmentErrors(t),o<h.maxNumRetry?i||(n.resolved=!0):f.warn(`${e.details} reached or exceeded max retry (${o})`)):this.state=rs;this.tickImmediate()}reduceLengthAndFlushBuffer(t){if(this.state===ts||this.state===es){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===Kt&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==je&&(this.state=Xe)}afterBufferFlushed(t,e,s){if(!t)return;const r=BufferHelper.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r,s),this.state===ss&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Xe}resetStartWhenNotLoaded(t){if(!this.loadedmetadata){this.startFragRequested=!1;const e=this.levels?this.levels[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(t.level),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 o=t.elementaryStreams[i];if(o){const l=o.endPTS-o.startPTS;if(l<=0)return this.warn(`Could not parse fragment ${t.sn} ${i} duration reliably (${l})`),e||!1;const h=r?0:oe(n,t,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return this.hls.trigger(a.LEVEL_PTS_UPDATED,{details:n,level:s,drift:h,type:i,frag:t,start:o.startPTS,end:o.endPTS}),!0}return e},!1))s.fragmentError=0;else if(null===(null==(i=this.transmuxer)?void 0:i.error)){const e=new Error(`Found no media in fragment ${t.sn} of level ${s.id} resetting transmuxer to fallback to playlist timing`);if(this.warn(e.message),this.hls.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.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=es,this.hls.trigger(a.FRAG_PARSED,{frag:t,part:e})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.resetTransmuxer(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}}function as(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}function os(){return self.SourceBuffer||self.WebKitSourceBuffer}function ls(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=dt(this.cachedData,t),this.cachedData=null);let s,r=O(t,0),i=r?r.length:0;const a=this._audioTrack,o=this._id3Track,l=r?(t=>{const e=G(t);for(let t=0;t<e.length;t++){const s=e[t];if(B(s))return W(s)}})(r):void 0,h=t.length;for((null===this.basePTS||0===this.frameIndex&&n(l))&&(this.basePTS=hs(l,e,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:zt,duration:Number.POSITIVE_INFINITY});i<h;){if(this.canParse(t,i)){const e=this.appendFrame(a,t,i);e?(this.frameIndex++,this.lastPTS=e.sample.pts,i+=e.length,s=i):i=h}else U(t,i)?(r=O(t,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:zt,duration:Number.POSITIVE_INFINITY}),i+=r.length,s=i):i++;if(i===h&&s!==h){const e=M(t,s);this.cachedData?this.cachedData=dt(this.cachedData,e):this.cachedData=e}}return{audioTrack:a,videoTrack:ls(),id3Track:o,textTrack:ls()}}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:ls(),id3Track:this._id3Track,textTrack:ls()}}destroy(){}}const hs=(t,e,s)=>{if(n(t))return 90*t;return 9e4*e+(s?9e4*s.baseTime/s.timescale:0)};function ds(t,e){return 255===t[e]&&240==(246&t[e+1])}function cs(t,e){return 1&t[e+1]?7:9}function us(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function fs(t,e){return e+1<t.length&&ds(t,e)}function gs(t,e){if(fs(t,e)){const s=cs(t,e);if(e+s>=t.length)return!1;const r=us(t,e);if(r<=s)return!1;const i=e+r;return i===t.length||fs(t,i)}return!1}function ms(t,e,s,r,i){if(!t.samplerate){const n=function(t,e,s,r){let i,n,h,d;const c=navigator.userAgent.toLowerCase(),u=r,g=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=1+((192&e[s+2])>>>6);const m=(60&e[s+2])>>>2;if(!(m>g.length-1))return h=(1&e[s+2])<<2,h|=(192&e[s+3])>>>6,f.log(`manifest codec:${r}, ADTS type:${i}, samplingIndex:${m}`),/firefox/i.test(c)?m>=6?(i=5,d=new Array(4),n=m-3):(i=2,d=new Array(2),n=m):-1!==c.indexOf("android")?(i=2,d=new Array(2),n=m):(i=5,d=new Array(4),r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&m>=6?n=m-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(m>=6&&1===h||/vivaldi/i.test(c))||!r&&1===h)&&(i=2,d=new Array(2)),n=m)),d[0]=i<<3,d[0]|=(14&m)>>1,d[1]|=(1&m)<<7,d[1]|=h<<3,5===i&&(d[1]|=(14&n)>>1,d[2]=(1&n)<<7,d[2]|=8,d[3]=0),{config:d,samplerate:g[m],channelCount:h,codec:"mp4a.40."+i,manifestCodec:u};t.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+m})}(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,f.log(`parsed codec:${t.codec}, rate:${n.samplerate}, channels:${n.channelCount}`)}}function ps(t){return 9216e4/t}function ys(t,e,s,r,i){const n=r+i*ps(t.samplerate),a=function(t,e){const s=cs(t,e);if(e+s<=t.length){const r=us(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}}const Ts=/\/emsg[-/]ID3/i;let vs=null;const Es=[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],Ss=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ls=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],As=[0,1,1,4];function Rs(t,e,s,r,i){if(s+24>e.length)return;const n=bs(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 bs(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*Es[14*(3===s?3-r:3===r?3:4)+i-1],h=Ss[3*(3===s?0:2===s?1:2)+n],d=3===o?1:2,c=Ls[s][r],u=As[r],f=8*c*u,g=Math.floor(c*l/h+a)*u;if(null===vs){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);vs=t?parseInt(t[1]):0}return!!vs&&vs<=87&&2===r&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function ks(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function Ds(t,e){return e+1<t.length&&ks(t,e)}function Is(t,e){if(e+1<t.length&&ks(t,e)){const s=4,r=bs(t,e);let i=s;null!=r&&r.frameLength&&(i=r.frameLength);const n=e+i;return n===t.length||Ds(t,n)}return!1}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&&f.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(),T=h(),v=l(1);0===v&&c(1),c(1),d()&&(r=h(),i=h(),n=h(),a=h());let E=[1,1];if(d()&&d()){switch(o()){case 1:E=[1,1];break;case 2:E=[12,11];break;case 3:E=[10,11];break;case 4:E=[16,11];break;case 5:E=[40,33];break;case 6:E=[24,11];break;case 7:E=[20,11];break;case 8:E=[32,11];break;case 9:E=[80,33];break;case 10:E=[18,11];break;case 11:E=[15,11];break;case 12:E=[64,33];break;case 13:E=[160,99];break;case 14:E=[4,3];break;case 15:E=[3,2];break;case 16:E=[2,1];break;case 255:E=[o()<<8|o(),o()<<8|o()]}}return{width:Math.ceil(16*(y+1)-2*r-2*i),height:(2-v)*(T+1)*16-(v?2:4)*(n+a),pixelRatio:E}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}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=gt(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._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=s}static probe(t){const e=TSDemuxer.syncOffset(t);return e>0&&f.warn("MPEG2-TS detected but first sync word found @ offset "+e),-1!==e}static syncOffset(t){const e=t.length,s=Math.min(940,t.length-188)+1;let r=0;for(;r<s;){let i=!1;for(let n=r;n<e&&71===t[n];n+=188)if(i||0!==ws(t,n)||(i=!0),i&&n+188>s)return r;r++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:Z[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._avcTrack=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.avcSample=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=s,this._duration=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_avcTrack:e,_id3Track:s}=this;t&&(t.pesData=null),e&&(e.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(t,e,s=!1,r=!1){let i;s||(this.sampleAes=null);const n=this._avcTrack,h=this._audioTrack,d=this._id3Track,c=this._txtTrack;let u=n.pid,g=n.pesData,m=h.pid,p=d.pid,y=h.pesData,T=d.pesData,v=null,E=this.pmtParsed,S=this._pmtId,L=t.length;if(this.remainderData&&(L=(t=dt(this.remainderData,t)).length,this.remainderData=null),L<188&&!r)return this.remainderData=t,{audioTrack:h,videoTrack:n,id3Track:d,textTrack:c};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]),a=ws(t,e);let o;if((48&t[e+3])>>4>1){if(o=e+5+t[e+4],o===e+188)continue}else o=e+4;switch(a){case u:r&&(g&&(i=Ms(g))&&this.parseAVCPES(n,c,i,!1),g={data:[],size:0}),g&&(g.data.push(t.subarray(o,e+188)),g.size+=e+188-o);break;case m:if(r){if(y&&(i=Ms(y)))switch(h.segmentCodec){case"aac":this.parseAACPES(h,i);break;case"mp3":this.parseMPEGPES(h,i)}y={data:[],size:0}}y&&(y.data.push(t.subarray(o,e+188)),y.size+=e+188-o);break;case p:r&&(T&&(i=Ms(T))&&this.parseID3PES(d,i),T={data:[],size:0}),T&&(T.data.push(t.subarray(o,e+188)),T.size+=e+188-o);break;case 0:r&&(o+=t[o]+1),S=this._pmtId=_s(t,o);break;case S:{r&&(o+=t[o]+1);const i=Ps(t,o,this.typeSupported,s);u=i.avc,u>0&&(n.pid=u),m=i.audio,m>0&&(h.pid=m,h.segmentCodec=i.segmentCodec),p=i.id3,p>0&&(d.pid=p),null===v||E||(f.warn(`MPEG-TS PMT found at ${e} after unknown PID '${v}'. Backtracking to sync byte @${A} to parse all TS packets.`),v=null,e=A-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:v=a}}else R++;if(R>0){const t=new Error(`Found ${R} TS packet/s that do not start with 0x47`);this.observer.emit(a.ERROR,a.ERROR,{type:o.MEDIA_ERROR,details:l.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message})}n.pesData=g,h.pesData=y,d.pesData=T;const b={audioTrack:h,videoTrack:n,id3Track:d,textTrack:c};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._avcTrack,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=Ms(n))?(this.parseAVCPES(s,i,l,!0),s.pesData=null):s.pesData=n,a&&(l=Ms(a))){switch(e.segmentCodec){case"aac":this.parseAACPES(e,l);break;case"mp3":this.parseMPEGPES(e,l)}e.pesData=null}else null!=a&&a.size&&f.log("last AAC PES packet truncated,might overlap between fragments"),e.pesData=a;o&&(l=Ms(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}parseAVCPES(t,e,s,r){const i=this.parseAVCNALu(t,s.data);let n,a=this.avcSample,o=!1;s.data=null,a&&i.length&&!t.audFound&&(xs(a,t),a=this.avcSample=Cs(!1,s.pts,s.dts,"")),i.forEach(r=>{switch(r.type){case 1:{n=!0,a||(a=this.avcSample=Cs(!0,s.pts,s.dts,"")),a.frame=!0;const t=r.data;if(o&&t.length>4){const e=new ExpGolomb(t).readSliceType();2!==e&&4!==e&&7!==e&&9!==e||(a.key=!0)}break}case 5:n=!0,a||(a=this.avcSample=Cs(!0,s.pts,s.dts,"")),a.key=!0,a.frame=!0;break;case 6:n=!0,ft(r.data,1,s.pts,e.samples);break;case 7:if(n=!0,o=!0,!t.sps){const e=r.data,s=new ExpGolomb(e).readSPS();t.width=s.width,t.height=s.height,t.pixelRatio=s.pixelRatio,t.sps=[e],t.duration=this._duration;const i=e.subarray(1,4);let n="avc1.";for(let t=0;t<3;t++){let e=i[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}break;case 8:n=!0,t.pps||(t.pps=[r.data]);break;case 9:n=!1,t.audFound=!0,a&&xs(a,t),a=this.avcSample=Cs(!1,s.pts,s.dts,"");break;case 12:n=!0;break;default:n=!1,a&&(a.debug+="unknown NAL "+r.type+" ")}if(a&&n){a.units.push(r)}}),r&&a&&(xs(a,t),this.avcSample=null)}getLastNalUnit(t){var e;let s,r=this.avcSample;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}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(d>=0){const t={data:e.subarray(d,h-r-1),type:c};n.push(t)}else{const s=this.getLastNalUnit(t.samples);if(s&&(i&&h<=4-i&&s.state&&(s.data=s.data.subarray(0,s.data.byteLength-i)),o=h-r-1,o>0)){const t=new Uint8Array(s.data.byteLength+o);t.set(s.data,0),t.set(e.subarray(0,o),s.data.byteLength),s.data=t,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);if(s){const t=new Uint8Array(s.data.byteLength+e.byteLength);t.set(s.data,0),t.set(e,s.data.byteLength),s.data=t}}return t.naluState=r,n}parseAACPES(t,e){let s=0;const r=this.aacOverFlow;let i,n,h,d=e.data;if(r){this.aacOverFlow=null;const e=r.missing,i=r.sample.unit.byteLength;if(-1===e){const t=new Uint8Array(i+d.byteLength);t.set(r.sample.unit,0),t.set(d,i),d=t}else{const n=i-e;r.sample.unit.set(d.subarray(0,e),n),t.samples.push(r.sample),s=r.missing}}for(i=s,n=d.length;i<n-1&&!fs(d,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(f.warn("parsing error: "+t),this.observer.emit(a.ERROR,a.ERROR,{type:o.MEDIA_ERROR,details:l.FRAG_PARSING_ERROR,fatal:!1,levelRetry:e,error:s,reason:t}),!e)return}if(ms(t,this.observer,d,i,this.audioCodec),void 0!==e.pts)h=e.pts;else{if(!r)return void f.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=ps(t.samplerate);h=r.sample.pts+e}}let c,u=0;for(;i<n;){if(c=ys(t,d,i,h,u),i+=c.length,c.missing){this.aacOverFlow=c;break}for(u++;i<n-1&&!fs(d,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(Ds(s,n)){const e=Rs(t,s,n,a,i);if(!e)break;n+=e.length,i++}else n++;else f.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseID3PES(t,e){if(void 0===e.pts)return void f.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=i({},e,{type:this._avcTrack?Jt:zt,duration:Number.POSITIVE_INFINITY});t.samples.push(s)}}function Cs(t,e,s,r){return{key:t,frame:!1,pts:e,dts:s,units:[],debug:r,length:0}}function ws(t,e){return((31&t[e+1])<<8)+t[e+2]}function _s(t,e){return(31&t[e+10])<<8|t[e+11]}function Ps(t,e,s,r){const i={audio:-1,avc:-1,id3:-1,segmentCodec:"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=ws(t,e);switch(t[e]){case 207:if(!r){f.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===i.audio&&(i.audio=n);break;case 21:-1===i.id3&&(i.id3=n);break;case 219:if(!r){f.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===i.avc&&(i.avc=n);break;case 3:case 4:!0!==s.mpeg&&!0!==s.mp3?f.log("MPEG audio found, not supported in this browser"):-1===i.audio&&(i.audio=n,i.segmentCodec="mp3");break;case 36:f.warn("Unsupported HEVC stream type found")}e+=5+((15&t[e+3])<<8|t[e+4])}return i}function Ms(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;){const t=new Uint8Array(o[0].length+o[1].length);t.set(o[0]),t.set(o[1],o[0].length),o[0]=t,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&&(f.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}function xs(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&&f.log(t.pts+"/"+t.dts+":"+t.debug)}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 Fs=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":[],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/(Fs+1)),r=Math.floor(e%(Fs+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/(Fs+1)),r=Math.floor(e%(Fs+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 mp4a(t){const e=t.samplerate;return MP4.box(MP4.types.mp4a,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]),MP4.box(MP4.types.esds,MP4.esds(t)))}static mp3(t){const e=t.samplerate;return MP4.box(MP4.types[".mp3"],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 stsd(t){return"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?MP4.box(MP4.types.stsd,MP4.STSD,MP4.mp3(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/(Fs+1)),a=Math.floor(s%(Fs+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/(Fs+1)),n=Math.floor(e%(Fs+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),s=new Uint8Array(MP4.FTYP.byteLength+e.byteLength);return s.set(MP4.FTYP),s.set(e,MP4.FTYP.byteLength),s}}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 Os(t,e,s=1,r=!1){const i=t*e*s;return r?Math.round(i):i}function Ns(t,e=!1){return Os(t,1e3,1/9e4,e)}let Us,Bs=null,$s=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.observer=t,this.config=e,this.typeSupported=s,this.ISGenerated=!1,null===Bs){const t=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Bs=t?parseInt(t[1]):0}if(null===$s){const t=navigator.userAgent.match(/Safari\/(\d+)/i);$s=t?parseInt(t[1]):0}}destroy(){}resetTimeStamp(t){f.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t}resetNextTimestamp(){f.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){f.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(t){let e=!1;const s=t.reduce((t,s)=>{const r=s.pts-t;return r<-4294967296?(e=!0,Gs(t,s.pts)):r>0?t:s.pts},t[0].pts);return e&&f.debug("PTS rollover detected"),s}remux(t,e,s,r,i,n,a,o){let l,h,d,c,u,g,m=i,p=i;const y=t.pid>-1,T=e.pid>-1,v=e.samples.length,E=t.samples.length>0,S=a&&v>0||v>1;if((!y||E)&&(!T||S)||this.ISGenerated||a){this.ISGenerated||(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(g=!0,a>0){f.warn(`[mp4-remuxer]: Dropped ${a} out of ${v} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,p+=(e.samples[0].pts-t)/e.inputTimeScale,r=p}else-1===a&&(f.warn(`[mp4-remuxer]: No keyframe found out of ${v} video samples`),g=!1);if(this.ISGenerated){if(E&&S){const s=this.getVideoStartPts(e.samples),r=(Gs(t.samples[0].pts,s)-s)/e.inputTimeScale;m+=Math.max(0,r),p+=Math.max(0,-r)}if(E){if(t.samplerate||(f.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(t,e,i,n)),h=this.remuxAudio(t,m,this.isAudioContiguous,n,T||S||o===Kt?p:void 0),S){const r=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(f.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(t,e,i,n)),l=this.remuxVideo(e,p,s,r)}}else S&&(l=this.remuxVideo(e,p,s,0));l&&(l.firstKeyFrame=a,l.independent=-1!==a,l.firstKeyFramePTS=r)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(u=Ks(s,i,this._initPTS,this._initDTS)),r.samples.length&&(c=Hs(r,i,this._initPTS))),{audio:h,video:l,initSegment:d,independent:g,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")}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&&(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,Gs(n[0].dts,t)-e),h=Math.min(h,t-e)}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 n=t.inputTimeScale,h=t.samples,d=[],c=h.length,u=this._initPTS;let g,m,p=this.nextAvcDts,y=8,T=this.videoSampleDuration,v=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,S=!1;if(!s||null===p){p=e*n-(h[0].pts-Gs(h[0].dts,h[0].pts))}const L=u.baseTime*n/u.timescale;for(let t=0;t<c;t++){const e=h[t];e.pts=Gs(e.pts-L,p),e.dts=Gs(e.dts-L,p),e.dts<h[t>0?t-1:t].dts&&(S=!0)}S&&h.sort((function(t,e){const s=t.dts-e.dts,r=t.pts-e.pts;return s||r})),g=h[0].dts,m=h[h.length-1].dts;const A=m-g,R=A?Math.round(A/(c-1)):T||t.inputTimeScale/30;if(s){const t=g-p,e=t>R,s=t<-1;if((e||s)&&(e?f.warn(`AVC: ${Ns(t,!0)} ms (${t}dts) hole between fragments detected, filling it`):f.warn(`AVC: ${Ns(-t,!0)} ms (${t}dts) overlapping between fragments detected`),!s||p>h[0].pts)){g=p;const e=h[0].pts-t;h[0].dts=g,h[0].pts=e,f.log(`Video: First PTS/DTS adjusted: ${Ns(e,!0)}/${Ns(g,!0)}, delta: ${Ns(t,!0)} ms`)}}g=Math.max(0,g);let b=0,k=0;for(let t=0;t<c;t++){const e=h[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=Math.max(e.dts,g),v=Math.min(e.pts,v),E=Math.max(e.pts,E)}m=h[c-1].dts;const D=k+4*b+8;let I;try{I=new Uint8Array(D)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:o.MUX_ERROR,details:l.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:D,reason:"fail allocating video mdat "+D})}const C=new DataView(I.buffer);C.setUint32(0,D),I.set(MP4.types.mdat,4);let w=!1,_=Number.POSITIVE_INFINITY,P=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,x=Number.NEGATIVE_INFINITY;for(let t=0;t<c;t++){const e=h[t],s=e.units;let i,a=0;for(let t=0,e=s.length;t<e;t++){const e=s[t],r=e.data,i=e.data.byteLength;C.setUint32(y,i),y+=4,I.set(r,y),y+=i,a+=4+i}if(t<c-1)T=h[t+1].dts-e.dts,i=h[t+1].pts-e.pts;else{const s=this.config,a=t>0?e.dts-h[t-1].dts:R;if(i=t>0?e.pts-h[t-1].pts:R,s.stretchShortVideoTrack&&null!==this.nextAudioPts){const t=Math.floor(s.maxBufferHole*n),i=(r?v+r*n:this.nextAudioPts)-e.pts;i>t?(T=i-a,T<0?T=a:w=!0,f.log(`[mp4-remuxer]: It is approximately ${i/90} ms to the next segment; using duration ${T/90} ms for the last video frame.`)):T=a}else T=a}const o=Math.round(e.pts-e.dts);_=Math.min(_,T),M=Math.max(M,T),P=Math.min(P,i),x=Math.max(x,i),d.push(new Mp4Sample(e.key,T,a,o))}if(d.length)if(Bs){if(Bs<70){const t=d[0].flags;t.dependsOn=2,t.isNonSync=0}}else if($s&&x-P<M-_&&R/M<.025&&0===d[0].cts){f.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=g;for(let e=0,s=d.length;e<s;e++){const r=t+d[e].duration,i=t+d[e].cts;if(e<s-1){const t=r+d[e+1].cts;d[e].duration=t-i}else d[e].duration=e?d[e-1].duration:R;d[e].cts=0,t=r}}T=w||!T?R:T,this.nextAvcDts=p=m+T,this.videoSampleDuration=T,this.isVideoContiguous=!0;const F={data1:MP4.moof(t.sequenceNumber++,g,i({},t,{samples:d})),data2:I,startPTS:v/n,endPTS:(E+T)/n,startDTS:g/n,endDTS:p/n,type:"video",hasAudio:!1,hasVideo:!0,nb:d.length,dropped:t.dropped};return t.samples=[],t.dropped=0,F}remuxAudio(t,e,s,r,n){const h=t.inputTimeScale,d=h/(t.samplerate?t.samplerate:h),c="aac"===t.segmentCodec?1024:1152,u=c*d,g=this._initPTS,m="mp3"===t.segmentCodec&&this.typeSupported.mpeg,p=[],y=void 0!==n;let T=t.samples,v=m?0:8,E=this.nextAudioPts||-1;const S=e*h,L=g.baseTime*h/g.timescale;if(this.isAudioContiguous=s=s||T.length&&E>0&&(r&&Math.abs(S-E)<9e3||Math.abs(Gs(T[0].pts-L,S)-E)<20*u),T.forEach((function(t){t.pts=Gs(t.pts-L,S)})),!s||E<0){if(T=T.filter(t=>t.pts>=0),!T.length)return;E=0===n?0:r&&!y?Math.max(0,S):T[0].pts}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let s=0,r=E;s<T.length;s++){const i=T[s],n=i.pts,a=n-r,o=Math.abs(1e3*a/h);if(a<=-e*u&&y)0===s&&(f.warn(`Audio frame @ ${(n/h).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*a/h)} ms.`),this.nextAudioPts=E=r=n);else if(a>=e*u&&o<1e4&&y){let e=Math.round(a/u);r=n-e*u,r<0&&(e--,r+=u),0===s&&(this.nextAudioPts=E=r),f.warn(`[mp4-remuxer]: Injecting ${e} audio frame @ ${(r/h).toFixed(3)}s due to ${Math.round(1e3*a/h)} 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||(f.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),n=i.unit.subarray()),T.splice(s,0,{unit:n,pts:e}),r+=u,s++}}i.pts=r,r+=u}}let A,R=null,b=null,k=0,D=T.length;for(;D--;)k+=T[D].unit.byteLength;for(let e=0,r=T.length;e<r;e++){const r=T[e],i=r.unit;let n=r.pts;if(null!==b){p[e-1].duration=Math.round((n-b)/d)}else{if(s&&"aac"===t.segmentCodec&&(n=E),R=n,!(k>0))return;k+=v;try{A=new Uint8Array(k)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:o.MUX_ERROR,details:l.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:k,reason:"fail allocating audio mdat "+k})}if(!m){new DataView(A.buffer).setUint32(0,k),A.set(MP4.types.mdat,4)}}A.set(i,v);const h=i.byteLength;v+=h,p.push(new Mp4Sample(!0,c,h,0)),b=n}const I=p.length;if(!I)return;const C=p[p.length-1];this.nextAudioPts=E=b+d*C.duration;const w=m?new Uint8Array(0):MP4.moof(t.sequenceNumber++,R/d,i({},t,{samples:p}));t.samples=[];const _=R/h,P=E/h,M={data1:w,data2:A,startPTS:_,endPTS:P,startDTS:_,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};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),g=AAC.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(f.warn("[mp4-remuxer]: remux empty Audio"),!g)return void f.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const m=[];for(let t=0;t<u;t++){const e=h+t*c;m.push({unit:g,pts:e,dts:e})}return t.samples=m,this.remuxAudio(t,e,s,!1)}}function Gs(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 Ks(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=Gs(i.pts-9e4*s.baseTime/s.timescale,e*n)/n,i.dts=Gs(i.dts-9e4*r.baseTime/r.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Hs(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=Gs(r.pts-9e4*s.baseTime/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=new Mp4SampleFlags(t)}}class Mp4SampleFlags{constructor(t){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1}}function Vs(t,e){const s=null==t?void 0:t.codec;return s&&s.length>4?s:"hvc1"===s||"hev1"===s?"hvc1.1.c.L120.90":"av01"===s?"av01.0.04M.08":"avc1"===s||e===T?"avc1.42e01e":"mp4a.40.5"}try{Us=self.performance.now.bind(self.performance)}catch(t){f.debug("Unable to use Performance API on this environment"),Us="undefined"!=typeof self&&self.Date.now}const Ys=[{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=ls("video",1),n=this.audioTrack=ls("audio",1),a=this.txtTrack=ls("text",1);if(this.id3Track=ls("id3",1),this.timeOffset=0,null==t||!t.byteLength)return;const o=ot(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=Z.text,i.sampleDuration=0,i.duration=n.duration=r}resetContiguity(){}static probe(t){return nt(t=t.length>16384?t.subarray(0,16384):t,["moof"]).length>0}demux(t,e){this.timeOffset=e;let s=t;const r=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=dt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},s=nt(t,["moof"]);if(!s)return e;if(s.length<2)return e.remainder=t,e;const r=s[s.length-1];return e.valid=M(t,0,r.byteOffset-8),e.remainder=M(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=ct(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=ct(t,e),{videoTrack:e,audioTrack:ls(),id3Track:r,textTrack:ls()}}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const r=nt(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,h=0;if(0===e){for(;"\0"!==tt(t.subarray(h,h+1));)s+=tt(t.subarray(h,h+1)),h+=1;for(s+=tt(t.subarray(h,h+1)),h+=1;"\0"!==tt(t.subarray(h,h+1));)r+=tt(t.subarray(h,h+1)),h+=1;r+=tt(t.subarray(h,h+1)),h+=1,i=st(t,12),n=st(t,16),o=st(t,20),l=st(t,24),h=28}else if(1===e){h+=4,i=st(t,h),h+=4;const e=st(t,h);h+=4;const n=st(t,h);for(h+=4,a=2**32*e+n,Number.isSafeInteger(a)||(a=Number.MAX_SAFE_INTEGER,f.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=st(t,h),h+=4,l=st(t,h),h+=4;"\0"!==tt(t.subarray(h,h+1));)s+=tt(t.subarray(h,h+1)),h+=1;for(s+=tt(t.subarray(h,h+1)),h+=1;"\0"!==tt(t.subarray(h,h+1));)r+=tt(t.subarray(h,h+1)),h+=1;r+=tt(t.subarray(h,h+1)),h+=1}return{schemeIdUri:s,value:r,timeScale:i,presentationTime:a,presentationTimeDelta:n,eventDuration:o,id:l,payload:t.subarray(h,t.byteLength)}}(t);if(Ts.test(r.schemeIdUri)){const t=n(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 a=r.payload;s.samples.push({data:a,len:a.byteLength,dts:t,pts:t,type:Jt,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){nt(t,["moov","trak"]).forEach(t=>{const e=nt(t,["mdia","minf","stbl","stsd"])[0].subarray(8);let r=nt(e,["enca"]);const i=r.length>0;i||(r=nt(e,["encv"])),r.forEach(t=>{nt(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)||(f.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${z(t)} -> ${z(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=ot(t);e||(e=Vs(r.audio,y)),s||(s=Vs(r.video,T));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"}:f.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=i}remux(t,e,s,r,i,a){var o,l;let{initPTS:h,lastEndTime:d}=this;const c={audio:void 0,video:void 0,text:r,id3:s,initSegment:void 0};n(d)||(d=this.lastEndTime=i||0);const u=e.samples;if(null==u||!u.length)return c;const g={initPTS:void 0,timescale:1};let m=this.initData;if(null!=(o=m)&&o.length||(this.generateInitSegment(u),m=this.initData),null==(l=m)||!l.length)return f.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const p=function(t,e){return nt(e,["moof","traf"]).reduce((e,s)=>{const r=nt(s,["tfdt"])[0],i=r[0],n=nt(s,["tfhd"]).reduce((e,s)=>{const n=st(s,4),a=t[n];if(a){let t=st(r,4);if(1===i){if(t===Q)return f.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=Q+1,t+=st(r,8)}const s=t/(a.timescale||9e4);if(isFinite(s)&&(null===e||s<e))return s}return e},null);return null!==n&&isFinite(n)&&(null===e||n<e)?n:e},null)}(m,u),v=null===p?i:p;(function(t,e,s){if(null===t)return!0;const r=e-t.baseTime/t.timescale;return r<0&&Math.abs(r-s)>1}(h,v,i)||g.timescale!==h.timescale&&a)&&(g.initPTS=v-i,this.initPTS=h={baseTime:g.initPTS,timescale:1});const E=function(t,e){let s=0,r=0,i=0;const n=nt(t,["moof","traf"]);for(let t=0;t<n.length;t++){const a=n[t],o=nt(a,["tfhd"])[0],l=e[st(o,4)];if(!l)continue;const h=l.default,d=st(o,0)|(null==h?void 0:h.flags);let c=null==h?void 0:h.duration;8&d&&(c=st(o,2&d?12:8));const u=l.timescale||9e4,f=nt(a,["trun"]);for(let t=0;t<f.length;t++){if(s=ht(f[t]),!s&&c){s=c*st(f[t],4)}l.type===T?r+=s/u:l.type===y&&(i+=s/u)}}if(0===r&&0===i){let e=0;const s=nt(t,["sidx"]);for(let t=0;t<s.length;t++){const r=at(s[t]);null!=r&&r.references&&(e+=r.references.reduce((t,e)=>t+e.info.duration||0,0))}return e}return r||i}(u,m),S=t?v-h.baseTime/h.timescale:d,L=S+E;!function(t,e,s){nt(e,["moof","traf"]).forEach(e=>{nt(e,["tfhd"]).forEach(r=>{const i=st(r,4),n=t[i];if(!n)return;const a=n.timescale||9e4;nt(e,["tfdt"]).forEach(t=>{const e=t[0];let r=st(t,4);if(0===e)r-=s*a,r=Math.max(r,0),it(t,4,r);else{r*=Math.pow(2,32),r+=st(t,8),r-=s*a,r=Math.max(r,0);const e=Math.floor(r/(Q+1)),i=Math.floor(r%(Q+1));it(t,4,e),it(t,8,i)}})})})}(m,u,h.baseTime/h.timescale),E>0?this.lastEndTime=L:(f.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const A=!!m.audio,R=!!m.video;let b="";A&&(b+="audio"),R&&(b+="video");const k={data1:u,startPTS:S,startDTS:S,endPTS:L,endDTS:L,type:b,hasAudio:A,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=g,c.id3=Ks(s,i,h,h),r.samples.length&&(c.text=Hs(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;let e=(O(t,0)||[]).length;for(let s=t.length;e<s;e++)if(gs(t,e))return f.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)&&ds(t,e)&&us(t,e)<=t.length-e}(t,e)}appendFrame(t,e,s){ms(t,this.observer,e,s,t.manifestCodec);const r=ys(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;let e=(O(t,0)||[]).length;for(let s=t.length;e<s;e++)if(Is(t,e))return f.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return ks(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,s){if(null!==this.basePTS)return Rs(t,e,s,this.basePTS,this.frameIndex)}},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=Us();let n=new Uint8Array(t);const{currentTransmuxState:h,transmuxConfig:d}=this;r&&(this.currentTransmuxState=r);const{contiguous:c,discontinuity:u,trackSwitch:g,accurateTimeOffset:m,timeOffset:p,initSegmentChange:y}=r||h,{audioCodec:T,videoCodec:v,defaultInitPts:E,duration:S,initSegmentData:L}=d,A=function(t,e){let s=null;t.byteLength>0&&null!=e&&null!=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=Us(),Ws(s);n=new Uint8Array(e)}}const R=this.needsProbing(u,g);if(R){const t=this.configureTransmuxer(n);if(t)return f.warn("[transmuxer] "+t.message),this.observer.emit(a.ERROR,a.ERROR,{type:o.MEDIA_ERROR,details:l.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),i.executeEnd=Us(),Ws(s)}(u||g||y||R)&&this.resetInitSegment(L,T,v,S,e),(u||y||R)&&this.resetInitialTimestamp(E),c||this.resetContiguity();const b=this.transmux(n,A,p,m,s),k=this.currentTransmuxState;return k.contiguous=!0,k.discontinuity=!1,k.trackSwitch=!1,i.executeEnd=Us(),b}flush(t){const e=t.transmuxing;e.executeStart=Us();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=Us(),[Ws(t)];const h=o.flush(a);return qs(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;f.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=Us()}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=Ys.length;e<s;e++)if(Ys[e].demux.probe(t)){n=Ys[e];break}if(!n)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=n.remux,h=n.demux;o&&o instanceof l||(this.remuxer=new l(s,e,r,i)),a&&a instanceof h||(this.demuxer=new h(s,e,r),this.probe=h.probe)}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Decrypter(this.config)),t}}const Ws=t=>({remuxResult:{},chunkMeta:t});function qs(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 js={};!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}({get exports(){return js},set exports(t){js=t}});const Xs=as()||{isTypeSupported:()=>!1};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===a.ERROR&&(this.error=e.error),this.hls.trigger(t,e)};this.observer=new js,this.observer.on(a.FRAG_DECRYPTED,n),this.observer.on(a.ERROR,n);const h={mp4:Xs.isTypeSupported("video/mp4"),mpeg:Xs.isTypeSupported("audio/mpeg"),mp3:Xs.isTypeSupported('audio/mp4; codecs="mp3"')},d=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){if(i.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{i.workerPath?(f.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)):(f.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,f.warn(`Error in "${e}" Web Worker, fallback to inline`),this.hls.trigger(a.ERROR,{type:o.OTHER_ERROR,details:l.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:s})},t.postMessage({cmd:"init",typeSupported:h,vendor:d,id:e,config:JSON.stringify(i)})}catch(t){f.warn(`Error setting up "${e}" Web Worker, fallback to inline`,t),this.resetWorker(),this.error=null,this.transmuxer=new Transmuxer(this.observer,h,i,d,e)}return}}this.transmuxer=new Transmuxer(this.observer,h,i,d,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,g=n?n.start:i.start,m=i.decryptdata,p=this.frag,y=!(p&&i.cc===p.cc),T=!(p&&l.level===p.level),v=p?l.sn-p.sn:-1,E=this.part?l.part-this.part.index:-1,S=0===v&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),L=!T&&(1===v||0===v&&(1===E||S&&E<=0)),A=self.performance.now();(T||v||0===i.stats.parsing.start)&&(i.stats.parsing.start=A),!n||!E&&L||(n.stats.parsing.start=A);const R=!(p&&(null==(d=i.initSegment)?void 0:d.url)===(null==(c=p.initSegment)?void 0:c.url)),b=new TransmuxState(y,L,o,T,g,R);if(!L||y||R){f.log(`[transmuxer-interface, ${i.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}\n discontinuity: ${y}\n trackSwitch: ${T}\n contiguous: ${L}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\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:m,chunkMeta:l,state:b},t instanceof ArrayBuffer?[t]:[]);else if(u){const e=u.push(t,m,l,b);qs(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);qs(s)||e.async?(qs(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(a.ERROR,{type:o.MEDIA_ERROR,details:l.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":f[e.data.logType]&&f[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)}}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,null!==i){if(this.stallReported){const t=self.performance.now()-i;f.warn(`playback not stuck anymore @${n}, after ${Math.round(t)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(l||o)return void(this.stalled=null);if(r.paused&&!a||r.ended||0===r.playbackRate||!BufferHelper.getBuffered(r).length)return;const h=BufferHelper.bufferInfo(r,n,0),d=h.len>0,c=h.nextStart||0;if(!d&&!c)return;if(a){const t=h.len>2,s=!c||e&&e.start<=n||c-n>2&&!this.fragmentTracker.getPartialFragment(n);if(t||s)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var u;const t=Math.max(c,h.start||0)-n,e=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,s=(null==e||null==(u=e.details)?void 0:u.live)?2*e.details.targetduration:2,r=this.fragmentTracker.getPartialFragment(n);if(t>0&&(t<=s||r))return void this._trySkipBufferHole(r)}const g=self.performance.now();if(null===i)return void(this.stalled=g);const m=g-i;if(!a&&m>=250&&(this._reportStall(h),!this.media))return;const p=BufferHelper.bufferInfo(r,n,s.maxBufferHole);this._tryFixBufferStall(p,m)}_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&&(f.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)})`);f.warn(r.message),e.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.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),h=i<n.start?n.start:n.nextStart;if(h){const d=n.len<=e.maxBufferHole,c=n.len>0&&n.len<1&&r.readyState<3,u=h-i;if(u>0&&(d||c)){if(u>e.maxBufferHole){const{fragmentTracker:e}=this;let s=!1;if(0===i){const t=e.getAppendedFrag(0,Gt);t&&h<t.end&&(s=!0)}if(!s){const s=t||e.getAppendedFrag(i,Gt);if(s){let t=!1,r=s.end;for(;r<h;){const s=e.getPartialFragment(r);if(!s){t=!0;break}r+=s.duration}if(t)return 0}}}const n=Math.max(h+.05,i+.1);if(f.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(a.ERROR,{type:o.MEDIA_ERROR,details:l.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,h=new Error(`Nudging 'currentTime' from ${i} to ${n}`);f.warn(h.message),s.currentTime=n,e.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.BUFFER_NUDGE_ON_STALL,error:h,fatal:!1})}else{const s=new Error(`Playhead still not moving while enough data buffered @${i} after ${t.nudgeMaxRetry} nudges`);f.error(s.message),e.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.BUFFER_STALLED_ERROR,error:s,fatal:!0})}}}class StreamController extends BaseStreamController{constructor(t,e,s){super(t,e,s,"[stream-controller]",Gt),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(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(a.ERROR,this.onError,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(a.ERROR,this.onError,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}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.nextAutoLevel),this.level=s.nextLoadLevel=t,this.loadedmetadata=!1}e>0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=Xe,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=je}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case ns:{var t;const{levels:e,level:s}=this,r=null==e||null==(t=e[s])?void 0:t.details;if(r&&(!r.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(r))break;this.state=Xe;break}break}case Je:{var e;const t=self.performance.now(),s=this.retryDate;(!s||t>=s||null!=(e=this.media)&&e.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=Xe)}}this.state===Xe&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:s,media:r}=this,{config:i,nextLoadLevel:n}=t;if(null===e||!r&&(this.startFragRequested||!i.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;if(null==s||!s[n])return;const o=s[n],l=this.getMainFwdBufferInfo();if(null===l)return;const h=this.getLevelDetails();if(h&&this._streamEnded(l,h)){const t={};return this.altAudio&&(t.type="video"),this.hls.trigger(a.BUFFER_EOS,t),void(this.state=ss)}t.loadLevel!==n&&-1===t.manualLevel&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=t.nextLoadLevel=n;const d=o.details;if(!d||this.state===ns||d.live&&this.levelLastLoaded!==n)return this.level=n,void(this.state=ns);const c=l.len,u=this.getMaxBufferLength(o.maxBitrate);if(c>=u)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:l.end;let g=this.getNextFragment(f,d);if(this.couldBacktrack&&!this.fragPrevious&&g&&"initSegment"!==g.sn&&this.fragmentTracker.getState(g)!==Fe){var m;const t=(null!=(m=this.backtrackFragment)?m:g).sn-d.startSN,e=d.fragments[t-1];e&&g.cc===e.cc&&(g=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,f)){if(!g.gap){const t=this.audioOnly&&!this.altAudio?y:T,e=(t===T?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t,Gt)}g=this.getNextFragmentLoopLoading(g,d,l,Gt,u)}g&&(!g.initSegment||g.initSegment.data||this.bitrateTest||(g=g.initSegment),this.loadFragment(g,o,f))}loadFragment(t,e,s){const r=this.fragmentTracker.getState(t);this.fragCurrent=t,r===Pe?"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)}getAppendedFrag(t){const e=this.fragmentTracker.getAppendedFrag(t,Gt);return e&&"fragment"in e?e.fragment:e}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Gt)}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);if(r&&r.start>1&&this.flushMainBuffer(0,r.start-1),!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 i=this.getBufferedFrag(e.currentTime+s);if(i){const t=this.followingBufferedFrag(i);if(t){this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,s=t.duration,r=Math.max(i.end,e+Math.min(Math.max(s-this.config.maxFragLookUpTolerance,.5*s),.75*s));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 ze:case Qe:case Je:case ts:case es:this.state=Xe}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;n(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(a.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null,this.backtrackFragment=null}onManifestParsed(t,e){let s,r=!1,i=!1;e.levels.forEach(t=>{s=t.audioCodec,s&&(-1!==s.indexOf("mp4a.40.2")&&(r=!0),-1!==s.indexOf("mp4a.40.5")&&(i=!0))}),this.audioCodecSwitch=r&&i&&!function(){var t;const e=os();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!==Xe)return;const r=s[e.level];(!r.details||r.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(r.details))&&(this.state=ns)}onLevelLoaded(t,e){var s;const{levels:r}=this,i=e.level,n=e.details,o=n.totalduration;if(!r)return void this.warn("Levels were reset while loading level "+i);this.log(`Level ${i} loaded [${n.startSN},${n.endSN}], cc [${n.startCC}, ${n.endCC}] duration:${o}`);const l=r[i],h=this.fragCurrent;!h||this.state!==Qe&&this.state!==Je||h.level===e.level&&h.urlId===l.urlId||!h.loader||this.abortCurrentFrag();let d=0;if(n.live||null!=(s=l.details)&&s.live){if(n.fragments[0]||(n.deltaUpdateFailed=!0),n.deltaUpdateFailed)return;d=this.alignPlaylists(n,l.details)}if(l.details=n,this.levelLastLoaded=i,this.hls.trigger(a.LEVEL_UPDATED,{details:n,level:i}),this.state===ns){if(this.waitForCdnTuneIn(n))return;this.state=Xe}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,d),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,Gt,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(a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),t.trigger(a.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!==Gt)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===es&&(this.state=Xe));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=rs;else switch(e.details){case l.FRAG_GAP:case l.FRAG_PARSING_ERROR:case l.FRAG_DECRYPT_ERROR:case l.FRAG_LOAD_ERROR:case l.FRAG_LOAD_TIMEOUT:case l.KEY_LOAD_ERROR:case l.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Gt,e);break;case l.LEVEL_LOAD_ERROR:case l.LEVEL_LOAD_TIMEOUT:case l.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==ns||(null==(s=e.context)?void 0:s.type)!==Ut||(this.state=Xe);break;case l.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case l.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!==Xe?this.fragCurrent:null;e.poll(this.lastCurrentTime,t)}this.lastCurrentTime=t.currentTime}}onFragLoadEmergencyAborted(){this.state=Xe,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==y||this.audioOnly&&!this.altAudio){const t=(e===T?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(t,e,Gt)}}onLevelsUpdated(t,e){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=Xe,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(a.FRAG_LOADED,s),t.bitrateTest=!1})}_handleTransmuxComplete(t){var e;const s="main",{hls:r}=this,{remuxResult:i,chunkMeta:o}=t,l=this.getCurrentContext(o);if(!l)return void this.resetWhenMissingContext(o);const{frag:h,part:d,level:c}=l,{video:u,text:f,id3:g,initSegment:m}=i,{details:p}=c,T=this.altAudio?void 0:i.audio;if(this.fragContextChanged(h))this.fragmentTracker.removeFragment(h);else{if(this.state=ts,m){m.tracks&&(this._bufferInitSegment(c,m.tracks,h,o),r.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:h,id:s,tracks:m.tracks}));const t=m.initPTS,e=m.timescale;n(t)&&(this.initPTS[h.cc]={baseTime:t,timescale:e},r.trigger(a.INIT_PTS_FOUND,{frag:h,id:s,initPTS:t,timescale:e}))}if(u&&!1!==i.independent){if(p){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=u;if(d)d.elementaryStreams[u.type]={startPTS:t,endPTS:e,startDTS:s,endDTS:r};else if(u.firstKeyFrame&&u.independent&&1===o.id&&(this.couldBacktrack=!0),u.dropped&&u.independent){const s=this.getMainFwdBufferInfo();if((s?s.end:this.getLoadPosition())+this.config.maxBufferHole<(u.firstKeyFramePTS?u.firstKeyFramePTS:t)-this.config.maxBufferHole)return void this.backtrack(h);h.setElementaryStreamInfo(u.type,h.start,e,h.start,r,!0)}h.setElementaryStreamInfo(u.type,t,e,s,r),this.backtrackFragment&&(this.backtrackFragment=h),this.bufferFragmentData(u,h,d,o)}}else if(!1===i.independent)return void this.backtrack(h);if(T){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=T;d&&(d.elementaryStreams[y]={startPTS:t,endPTS:e,startDTS:s,endDTS:r}),h.setElementaryStreamInfo(y,t,e,s,r),this.bufferFragmentData(T,h,d,o)}if(p&&null!=g&&null!=(e=g.samples)&&e.length){const t={id:s,frag:h,details:p,samples:g.samples};r.trigger(a.FRAG_PARSING_METADATA,t)}if(p&&f){const t={id:s,frag:h,details:p,samples:f.samples};r.trigger(a.FRAG_PARSING_USERDATA,t)}}}_bufferInitSegment(t,e,s,r){if(this.state!==ts)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&delete e.audio;const{audio:i,video:n,audiovideo:o}=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")),-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}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.attrs.CODECS||""}/${o.codec}]`),this.hls.trigger(a.BUFFER_CODECS,e),Object.keys(e).forEach(t=>{const i=e[t].initSegment;null!=i&&i.byteLength&&this.hls.trigger(a.BUFFER_APPENDING,{type:t,data:i,frag:s,part:null,chunkMeta:r,parent:s.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,Gt)}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=Xe}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&&e.urlId===t.urlId||(this.fragPlaying=e,this.hls.trigger(a.FRAG_CHANGED,{frag:e}),t&&t.level===s||this.hls.trigger(a.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&&n(e)&&n(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 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(){}}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 zs(t,e){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!Qs(t[s].attrs,e[s].attrs))return!1;return!0}function Qs(t,e){const s=t["STABLE-RENDITION-ID"];return s?s===e["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some(s=>t[s]!==e[s])}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)}}}function Js(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}class BufferOperationQueue{constructor(t){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=t}append(t,e){const s=this.queues[e];s.push(t),1===s.length&&this.buffers[e]&&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{buffers:e,queues:s}=this,r=e[t],i=s[t];if(i.length){const e=i[0];try{e.execute()}catch(s){f.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),e.onError(s),null!=r&&r.updating||(i.shift(),this.executeNext(t))}}}shiftAndExecuteNext(t){this.queues[t].shift(),this.executeNext(t)}current(t){return this.queues[t][0]}}const Zs=as(),tr=/([ha]vc.)(?:\.[^.,]+)+/;const er={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},sr=function(t){let e=t;return er.hasOwnProperty(t)&&(e=er[t]),String.fromCharCode(e)},rr={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},ir={17:2,18:4,21:6,22:8,23:10,19:13,20:15},nr={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},ar={25:2,26:4,29:6,30:8,31:10,27:13,28:15},or=["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;f.log(`${this.time} [${t}] ${s}`)}}}const lr=function(t){const e=[];for(let s=0;s<t.length;s++)e.push(t[s].toString(16));return e};class PenState{constructor(t,e,s,r,i){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=t||"white",this.underline=e||!1,this.italics=s||!1,this.background=r||"black",this.flash=i||!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(t,e,s,r,i,n){this.uchar=void 0,this.penState=void 0,this.uchar=t||" ",this.penState=new PenState(e,s,r,i,n)}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=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let t=0;t<100;t++)this.chars.push(new StyledUnicodeChar);this.logger=t,this.pos=0,this.currPenState=new PenState}equals(t){let e=!0;for(let s=0;s<100;s++)if(!this.chars[s].equals(t.chars[s])){e=!1;break}return e}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=sr(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=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let e=0;e<15;e++)this.rows.push(new Row(t));this.logger=t,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}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(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=void 0,this.logger=void 0;const r=new CaptionsLogger;this.channels=[null,new Cea608Channel(t,e,r),new Cea608Channel(t+1,s,r)],this.cmdHistory={a:null,b:null},this.logger=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,"["+lr([e[t],e[t+1]])+"] -> ("+lr([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 "+lr([r,i])+" orig: "+lr([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(dr(t,e,s))return hr(null,null,s),this.logger.log(3,"Repeated command ("+lr([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 ("+lr([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(dr(t,e,r))return hr(null,null,r),!0;const i=t<=23?1:2;s=e>=64&&e<=95?1===i?rr[t]:nr[t]:1===i?ir[t]:ar[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 '"+sr(t)+"' in channel "+s),r=[t]}else t>=32&&t<=127&&(r=0===e?[t]:[t,e]);if(r){const s=lr(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=or[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 dr(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 cr=function(){if("undefined"!=typeof self&&self.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",T="start",v=50,E="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 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,"position",i({},l,{get:function(){return v},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",i({},l,{get:function(){return E},set:function(t){const e=r(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");E=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 ur(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 fr(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 gr=new cr(0,0,""),mr="middle"===gr.align?"middle":"center";function pr(t,e,s){const r=t;function i(){const e=ur(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;fr(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",mr,"end"]);break;case"position":i=e.split(","),r.percent(t,i[0]),2===i.length&&r.alt("positionAlign",i[1],["start",mr,"end","line-left","line-right","auto"]);break;case"size":r.percent(t,e);break;case"align":r.alt(t,e,["start",mr,"end","left","right"])}}),/:/,/\s/),e.region=r.get("region",null),e.vertical=r.get("vertical","");let i=r.get("line","auto");"auto"===i&&-1===gr.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",mr);let n=r.get("position","auto");"auto"===n&&50===gr.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function yr(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=yr(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)?fr(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 cr(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{pr(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 Tr=/\r\n|\n\r|\n|\r/g,vr=function(t,e,s=0){return t.slice(s,s+e.length)===e},Er=function(t){let e=5381,s=t.length;for(;s;)e=33*e^t.charCodeAt(--s);return(e>>>0).toString()};function Sr(t,e,s){return Er(t.toString())+Er(e.toString())+Er(s)}function Lr(t,e,s,r,i,a,o){const l=new VTTParser,h=q(new Uint8Array(t)).trim().replace(Tr,"\n").split("\n"),d=[],c=function(t,e=1){return Os(t,9e4,1/e)}(e.baseTime,e.timescale);let u,f="00:00.000",g=0,m=0,p=!0;l.oncue=function(t){const e=s[r];let n=s.ccOffset;const a=(g-c)/9e4;null!=e&&e.new&&(void 0!==m?n=s.ccOffset=e.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,a)),a&&(n=a-s.presentationOffset);const o=t.endTime-t.startTime,l=Gs(9e4*(t.startTime+n-m),9e4*i)/9e4;t.startTime=Math.max(l,0),t.endTime=Math.max(l+o,0);const h=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(h)),t.id||(t.id=Sr(t.startTime,t.endTime,h)),t.endTime>0&&d.push(t)},l.onparsingerror=function(t){u=t},l.onflush=function(){u?o(u):a(d)},h.forEach(t=>{if(p){if(vr(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach(t=>{vr(t,"LOCAL:")?f=t.slice(6):vr(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(!(n(e)&&n(s)&&n(r)&&n(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)}l.parse(t+"\n")}),l.flush()}const Ar=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Rr=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,br={left:"start",center:"center",right:"end",start:"start",end:"end"};function kr(t,e,s,r){const n=nt(new Uint8Array(t),["mdat"]);if(0===n.length)return void r(new Error("Could not parse IMSC1 mdat"));const a=n.map(t=>q(t)),o=function(t,e,s=1,r=!1){return Os(t,e,1/s,r)}(e.baseTime,1,e.timescale);try{a.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 n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((t,e)=>(t[e]=r.getAttribute("ttp:"+e)||n[e],t),{}),o="preserve"!==r.getAttribute("xml:space"),l=Ir(Dr(r,"styling","style")),h=Ir(Dr(r,"layout","region")),d=Dr(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,o);if(!s||!t.hasAttribute("begin"))return null;const r=_r(t.getAttribute("begin"),a),n=_r(t.getAttribute("dur"),a);let d=_r(t.getAttribute("end"),a);if(null===r)throw wr(t);if(null===d){if(null===n)throw wr(t);d=r+n}const c=new cr(r-e,d-e,s);c.id=Sr(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=Cr(e,r,n)||Cr(t,r,n)||Cr(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=br[f];t&&(c.lineAlign=t),c.align=f}return i(c,u),c}).filter(t=>null!==t)}(t,o)))}catch(t){r(t)}}function Dr(t,e,s){const r=t.getElementsByTagName(e)[0];return r?[].slice.call(r.querySelectorAll(s)):[]}function Ir(t){return t.reduce((t,e)=>{const s=e.getAttribute("xml:id");return s&&(t[s]=e),t},{})}function Cr(t,e,s){return t&&t.hasAttributeNS(e,s)?t.getAttributeNS(e,s):null}function wr(t){return new Error("Could not parse ttml timestamp "+t)}function _r(t,e){if(!t)return null;let s=ur(t);return null===s&&(Ar.test(t)?s=function(t,e){const s=Ar.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):Rr.test(t)&&(s=function(t,e){const s=Rr.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 Pr(t,e){return!!t&&t.label===e.name&&!(t.textTrack1||t.textTrack2)}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.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on(a.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(a.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.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}onManifestParsed(t,e){const s=this.hls;this.restrictedLevels=[],this.firstLevel=e.firstLevel,s.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onBufferCodecs(t,e){this.hls.config.capLevelToPlayerSize&&e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){const t=this.hls.levels;if(t.length){const e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),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,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),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;for(let a=0;a<t.length;a+=1){const o=t[a];if((o.width>=e||o.height>=s)&&(i=o,!(n=t[a+1])||i.width!==n.width||i.height!==n.height)){r=a;break}}var i,n;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=f.debug.bind(f,"[eme]"),this.log=f.log.bind(f,"[eme]"),this.warn=f.warn.bind(f,"[eme]"),this.error=f.error.bind(f,"[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(a.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(a.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(a.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(a.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(a.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:e,widevineLicenseUrl:s}=this.config,r=e[t];if(r)return r.licenseUrl;if(t===A.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:o.KEY_SYSTEM_ERROR,details:l.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===P&&"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 A.FAIRPLAY:i=["cenc","sinf"];break;case A.WIDEVINE:case A.PLAYREADY:i=["cenc"];break;case A.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||"not-allowed",distinctiveIdentifier:r.distinctiveIdentifier||"not-allowed",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: ${z(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 z(t.keyId)}updateKeySession(t,e){var s;const r=t.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${z((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=_(this.config),i=t.map(I).filter(t=>!!t&&-1!==r.indexOf(t));return this.getKeySystemSelectionPromise(i).then(({keySystem:t})=>{const r=w(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(a.ERROR,t.data):this.hls.trigger(a.ERROR,{type:o.KEY_SYSTEM_ERROR,details:l.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const e=this.getKeyIdString(t),s=this.keyIdToKeySessionPromise[e];if(!s){const e=I(t.keyFormat),s=e?[e]:_(this.config);return this.attemptKeySystemAccess(s)}return s}getKeySystemSelectionPromise(t){if(t.length||(t=_(this.config)),0===t.length)throw new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.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[A.FAIRPLAY]){const t=tt(new Uint8Array(s));try{const e=E(JSON.parse(t).sinf),s=lt(new Uint8Array(e));if(!s)return;r=s.subarray(8,24),i=A.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=z(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===C&&t.data&&(r=t.data.subarray(8,24)),i=function(t){if(t===C)return A.WIDEVINE}(t.systemId)}if(!i||!r)return;const n=z(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=z(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=w(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 h;if(this.warn(t.message),null!=(h=this.hls)&&h.config.debug)throw t}if(null===s)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const d=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${r}": ${d} (init data type: ${e} length: ${s?s.byteLength:null})`);const c=new js;t.mediaKeysSession.onmessage=e=>{const s=t.mediaKeysSession;if(!s)return void c.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),c.emit("error",t)}):"license-release"===r?t.keySystem===A.FAIRPLAY&&(this.updateKeySession(t,L("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${r}"`)},t.mediaKeysSession.onkeystatuseschange=e=>{if(!t.mediaKeysSession)return void c.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const s=t.keyStatus;c.emit("keyStatus",s),"expired"===s&&(this.warn(`${t.keySystem} expired for key ${d}`),this.renewKeySession(t))};const u=new Promise((t,e)=>{c.on("error",e),c.on("keyStatus",s=>{s.startsWith("usable")?t():"output-restricted"===s?e(new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===s?e(new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.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: ${d}`)}).catch(t=>{throw new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.KEY_SYSTEM_NO_SESSION,error:t,fatal:!1},"Error generating key-session request: "+t)}).then(()=>u).catch(e=>{throw c.removeAllListeners(),this.removeSession(t),e}).then(()=>(c.removeAllListeners(),t))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach((e,s)=>{this.log(`key status change "${e}" for keyStatuses keyId: ${z("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${z(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=e})}fetchServerCertificate(t){const e=this.config,r=new(0,e.loader)(e),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching serverCertificate for "${t}"`),new Promise((n,a)=>{const h={responseType:"arraybuffer",url:i},d=e.certLoadPolicy.default,c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(t,e,s,r)=>{n(t.data)},onError:(e,r,n,d)=>{a(new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:s({url:h.url,data:void 0},e)},`"${t}" certificate request failed (${i}). Status: ${e.code} (${e.text})`))},onTimeout:(e,s,r)=>{a(new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:h.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(t,e,s)=>{a(new Error("aborted"))}};r.load(h,c,u)})):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:o.KEY_SYSTEM_ERROR,details:l.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:o.KEY_SYSTEM_ERROR,details:l.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:t,fatal:!0},t.message)}))}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 h=s.errorRetry,d=h?h.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||a.status>=400&&a.status<500)i(new EMEKeyError({type:o.KEY_SYSTEM_ERROR,details:l.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=d-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:t,licenseChallenge:e})=>{t.send(e)})})}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(e=>{this.log(`Could not clear media keys: ${e}. media.src: ${null==t?void 0:t.src}`)}))).then(()=>{s&&(this.log("finished closing key sessions and clearing media keys"),e.length=0)}).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}. media.src: ${null==t?void 0:t.src}`)})}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),e.onmessage=null,e.onkeystatuseschange=null,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 Mr="m",xr="a",Fr="v",Or="av",Nr="i",Ur="tt";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.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:Mr,su:!this.initialized})}catch(t){f.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!==Fr&&r!==xr&&r!=Or||(i.br=s.bitrate/1e3,i.tb=this.getTopBandwidth(r)/1e3,i.bl=this.getBufferLength(r)),this.apply(t,i)}catch(t){f.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||CMCDController.uuid(),this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.registerListeners())}registerListeners(){const t=this.hls;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHED,this.onMediaDetached,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHED,this.onMediaDetached,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=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:"h",sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,e={}){i(e,this.createData());const s=e.ot===Nr||e.ot===Fr||e.ot===Or;if(this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering),this.useHeaders){const s=CMCDController.toHeaders(e);if(!Object.keys(s).length)return;t.headers||(t.headers={}),i(t.headers,s)}else{const s=CMCDController.toQuery(e);if(!s)return;t.url=CMCDController.appendQueryToUri(t.url,s)}}getObjectType(t){const{type:e}=t;return"subtitle"===e?Ur:"initSegment"===t.sn?Nr:"audio"===e?xr:"main"===e?this.hls.audioTracks.length?Fr:Or:void 0}getTopBandwidth(t){let e,s=0;const r=this.hls;if(t===xr)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===xr?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)}}}static uuid(){const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}static serialize(t){const e=[],s=t=>!Number.isNaN(t)&&null!=t&&""!==t&&!1!==t,r=t=>Math.round(t),i=t=>100*r(t/100),n={br:r,d:r,bl:i,dl:i,mtp:i,nor:t=>encodeURIComponent(t),rtp:i,tb:r},a=Object.keys(t||{}).sort();for(const r of a){let i=t[r];if(!s(i))continue;if("v"===r&&1===i)continue;if("pr"==r&&1===i)continue;const a=n[r];a&&(i=a(i));const o=typeof i;let l;l="ot"===r||"sf"===r||"st"===r?`${r}=${i}`:"boolean"===o?r:"number"===o?`${r}=${i}`:`${r}=${JSON.stringify(i)}`,e.push(l)}return e.join(",")}static toHeaders(t){const e=Object.keys(t),s={},r=["Object","Request","Session","Status"],i=[{},{},{},{}],n={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const s of e){i[null!=n[s]?n[s]:1][s]=t[s]}for(let t=0;t<i.length;t++){const e=CMCDController.serialize(i[t]);e&&(s["CMCD-"+r[t]]=e)}return s}static toQuery(t){return"CMCD="+encodeURIComponent(CMCDController.serialize(t))}static appendQueryToUri(t,e){if(!e)return t;const s=t.includes("?")?"&":"?";return`${t}${s}${e}`}}function Br(t,e,s,r){t&&Object.keys(e).forEach(n=>{const a=t.filter(t=>t.groupId===n).map(t=>{const a=i({},t);return a.details=void 0,a.attrs=new AttrList(a.attrs),a.url=a.attrs.URI=$r(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",s),a.groupId=a.attrs["GROUP-ID"]=e[n],a.attrs["PATHWAY-ID"]=r,a});t.push(...a)})}function $r(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 Gr=/^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=void 0,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}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)return;const s=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0;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=this.context.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:a}=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&&n(i)?i:a,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,r)?this.retry(n):(f.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{f.warn("timeout while loading "+this.context.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=me(t,s.retry),s.retry++,f.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${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&&Gr.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 Kr=/(\d+)-(\d+)\/(\d+)/;class FetchLoader{constructor(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Hr,this.controller=new self.AbortController,this.stats=new LoadStats}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const t=this.response;null!=t&&t.ok||(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 a=function(t,e){const s={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(i({},t.headers))};t.rangeEnd&&s.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return s}(t,this.controller.signal),o=s.onProgress,l="arraybuffer"===t.responseType,h=l?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:c}=e.loadPolicy;this.context=t,this.config=e,this.callbacks=s,this.request=this.fetchSetup(t,a),self.clearTimeout(this.requestTimeout),e.timeout=d&&n(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 a=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-(a-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=a,r.total=function(t){const e=t.get("Content-Range");if(e){const t=function(t){const e=Kr.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(n(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(i.headers)||r.total,o&&n(e.highWaterMark)?this.loadProgressively(i,r,t,e.highWaterMark,o):l?i.arrayBuffer():"json"===t.responseType?i.json():i.text()}).then(i=>{const{response:a}=this;self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const l=i[h];l&&(r.loaded=r.total=l);const d={url:a.url,data:i,code:a.status};o&&!n(e.highWaterMark)&&o(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 Hr(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 Vr=/\s/,Yr={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++)Vr.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=yr(h.trim()),f=Sr(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=>qt(t,e))),i}},Wr=s(s({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength: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=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=t;const e=t.config;this.bwEstimator=new EwmaBandWidthEstimator(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:t}=this;t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(t,e){var s;const r=e.frag;this.ignoreFragment(r)||(this.fragCurrent=r,this.partCurrent=null!=(s=e.part)?s:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(t,e){this.clearTimer()}getTimeToLoadFrag(t,e,s,r){return t+s/e+(r?this.lastLevelLoadSec:0)}onLevelLoaded(t,e){const s=this.hls.config,{total:r,bwEstimate:i}=e.stats;n(r)&&n(i)&&(this.lastLevelLoadSec=8*r/i),e.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:t,partCurrent:e,hls:s}=this,{autoLevelEnabled:r,media:i}=s;if(!t||!i)return;const o=performance.now(),l=e?e.stats:t.stats,h=e?e.duration:t.duration,d=o-l.loading.start;if(l.aborted||l.loaded&&l.loaded===l.total||0===t.level)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||i.paused||!i.playbackRate||!i.readyState)return;const c=s.mainForwardBufferInfo;if(null===c)return;const u=this.bwEstimator.getEstimateTTFB(),g=Math.abs(i.playbackRate);if(d<=Math.max(u,h/(2*g)*1e3))return;const m=c.len/g;if(m>=2*h/g)return;const p=l.loading.first?l.loading.first-l.loading.start:-1,y=l.loaded&&p>-1,T=this.bwEstimator.getEstimate(),{levels:v,minAutoLevel:E}=s,S=v[t.level],L=l.total||Math.max(l.loaded,Math.round(h*S.maxBitrate/8));let A=d-p;A<1&&y&&(A=Math.min(d,8*l.loaded/T));const R=y?1e3*l.loaded/A:0,b=R?(L-l.loaded)/R:8*L/T+u/1e3;if(b<=m)return;const k=R?8*R:T;let D,I=Number.POSITIVE_INFINITY;for(D=t.level-1;D>E;D--){const t=v[D].maxBitrate;if(I=this.getTimeToLoadFrag(u/1e3,k,h*t,!v[D].details),I<m)break}I>=b||I>10*h||(s.nextLoadLevel=D,y?this.bwEstimator.sample(d-Math.min(u,p),l.loaded):this.bwEstimator.sampleTTFB(d),this.clearTimer(),f.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: ${I.toFixed(3)} s\n TTFB estimate: ${p}\n Current BW estimate: ${n(T)?(T/1024).toFixed(3):"Unknown"} Kb/s\n New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s\n Aborting and switching to level ${D}`),t.loader&&(this.fragCurrent=this.partCurrent=null,t.abortRequests()),s.trigger(a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:l}))}onFragLoaded(t,{frag:e,part:s}){const r=s?s.stats:e.stats;if(e.type===Gt&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(e)){if(this.clearTimer(),this.lastLoadedFragLevel=e.level,this._nextAutoLevel=-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(a.FRAG_BUFFERED,t),e.bitrateTest=!1}}}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.bwEstimator.getEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==Gt||"initSegment"===t.sn}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const t=this._nextAutoLevel,e=this.bwEstimator;if(-1!==t&&!e.canEstimate())return t;let s=this.getNextABRAutoLevel();if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,s)&&e[t].loadError<=e[s].loadError)return t}return-1!==t&&(s=Math.min(t,s)),s}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:s}=this,{maxAutoLevel:r,config:i,minAutoLevel:n,media:a}=s,o=e?e.duration:t?t.duration:0,l=a&&0!==a.playbackRate?Math.abs(a.playbackRate):1,h=this.bwEstimator?this.bwEstimator.getEstimate():i.abrEwmaDefaultEstimate,d=s.mainForwardBufferInfo,c=(d?d.len:0)/l;let u=this.findBestLevel(h,n,r,c,i.abrBandWidthFactor,i.abrBandWidthUpFactor);if(u>=0)return u;f.trace(`[abr] ${c?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let g=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay,m=i.abrBandWidthFactor,p=i.abrBandWidthUpFactor;if(!c){const t=this.bitrateTestDelay;if(t){g=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-t,f.trace(`[abr] bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*g)} ms`),m=p=1}}return u=this.findBestLevel(h,n,r,c+g,m,p),Math.max(u,0)}findBestLevel(t,e,s,r,i,a){var o;const{fragCurrent:l,partCurrent:h,lastLoadedFragLevel:d}=this,{levels:c}=this.hls,u=c[d],g=!(null==u||null==(o=u.details)||!o.live),m=null==u?void 0:u.codecSet,p=h?h.duration:l?l.duration:0,y=this.bwEstimator.getEstimateTTFB()/1e3;let T=e,v=-1;for(let o=s;o>=e;o--){const e=c[o];if(!e||m&&e.codecSet!==m){e&&(T=Math.min(o,T),v=Math.max(o,v));continue}-1!==v&&f.trace(`[abr] Skipped level(s) ${T}-${v} with CODECS:"${c[v].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);const s=e.details,l=(h?null==s?void 0:s.partTarget:null==s?void 0:s.averagetargetduration)||p;let E;E=o<=d?i*t:a*t;const S=c[o].maxBitrate,L=this.getTimeToLoadFrag(y,E,S*l,void 0===s);if(f.trace(`[abr] level:${o} adjustedbw-bitrate:${Math.round(E-S)} avgDuration:${l.toFixed(1)} maxFetchDuration:${r.toFixed(1)} fetchDuration:${L.toFixed(1)}`),E>S&&(0===L||!n(L)||g&&!this.bitrateTestDelay||L<r))return o}return-1}set nextAutoLevel(t){this._nextAutoLevel=t}},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.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:t,mediaSource:e}=this;f.log("[buffer-controller]: Media source opened"),t&&(t.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(a.MEDIA_ATTACHED,{media:t})),e&&e.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{f.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{f.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:t,_objectUrl:e}=this;t&&t.src!==e&&f.error(`Media element src was set while attaching MediaSource (${e} > ${t.src})`)},this.hls=t,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}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.BUFFER_RESET,this.onBufferReset,this),t.on(a.BUFFER_APPENDING,this.onBufferAppending,this),t.on(a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.BUFFER_EOS,this.onBufferEos,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.FRAG_PARSED,this.onFragParsed,this),t.on(a.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.BUFFER_RESET,this.onBufferReset,this),t.off(a.BUFFER_APPENDING,this.onBufferAppending,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.BUFFER_EOS,this.onBufferEos,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.FRAG_PARSED,this.onFragParsed,this),t.off(a.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new BufferOperationQueue(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestParsed(t,e){let s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.details=null,f.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")}onMediaAttaching(t,e){const s=this.media=e.media;if(s&&Zs){const t=this.mediaSource=new Zs;t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),s.src=self.URL.createObjectURL(t),this._objectUrl=s.src,s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:t,mediaSource:e,_objectUrl:s}=this;if(e){if(f.log("[buffer-controller]: media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){f.warn(`[buffer-controller]: onMediaDetaching: ${t.message} while calling endOfStream`)}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(t.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),t.src===s?(t.removeAttribute("src"),t.load()):f.warn("[buffer-controller]: media.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(a.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(t=>{const e=this.sourceBuffer[t];try{e&&(this.removeBufferListeners(t),this.mediaSource&&this.mediaSource.removeSourceBuffer(e),this.sourceBuffer[t]=void 0)}catch(e){f.warn(`[buffer-controller]: Failed to reset the ${t} buffer`,e)}}),this._initSourceBuffer()}onBufferCodecs(t,e){const s=this.getSourceBufferTypes().length;Object.keys(e).forEach(t=>{if(s){const s=this.tracks[t];if(s&&"function"==typeof s.buffer.changeType){const{id:r,codec:i,levelCodec:n,container:a,metadata:o}=e[t],l=(s.levelCodec||s.codec).replace(tr,"$1"),h=(n||i).replace(tr,"$1");if(l!==h){const e=`${a};codecs=${n||i}`;this.appendChangeType(t,e),f.log(`[buffer-controller]: switching codec ${l} to ${h}`),this.tracks[t]={buffer:s.buffer,codec:i,container:a,levelCodec:n,metadata:o,id:r}}}}else this.pendingTracks[t]=e[t]}),s||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())}appendChangeType(t,e){const{operationQueue:s}=this,r={execute:()=>{const r=this.sourceBuffer[t];r&&(f.log(`[buffer-controller]: changing ${t} sourceBuffer type to ${e}`),r.changeType(e)),s.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{f.warn(`[buffer-controller]: Failed to change ${t} SourceBuffer type`,e)}};s.append(r,t)}onBufferAppending(t,e){const{hls:s,operationQueue:r,tracks:i}=this,{data:n,type:h,frag:d,part:c,chunkMeta:u}=e,g=u.buffering[h],m=self.performance.now();g.start=m;const p=d.stats.buffering,y=c?c.stats.buffering:null;0===p.start&&(p.start=m),y&&0===y.start&&(y.start=m);const T=i.audio;let v=!1;"audio"===h&&"audio/mpeg"===(null==T?void 0:T.container)&&(v=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);const E=d.start,S={execute:()=>{if(g.executeStart=self.performance.now(),v){const t=this.sourceBuffer[h];if(t){const e=E-t.timestampOffset;Math.abs(e)>=.1&&(f.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${E} (delta: ${e}) sn: ${d.sn})`),t.timestampOffset=E)}}this.appendExecutor(n,h)},onStart:()=>{},onComplete:()=>{const t=self.performance.now();g.executeEnd=g.end=t,0===p.first&&(p.first=t),y&&0===y.first&&(y.first=t);const{sourceBuffer:e}=this,s={};for(const t in e)s[t]=BufferHelper.getBuffered(e[t]);this.appendError=0,this.hls.trigger(a.BUFFER_APPENDED,{type:h,frag:d,part:c,chunkMeta:u,parent:d.type,timeRanges:s})},onError:t=>{f.error(`[buffer-controller]: Error encountered while trying to append to the ${h} SourceBuffer`,t);const e={type:o.MEDIA_ERROR,parent:d.type,details:l.BUFFER_APPEND_ERROR,frag:d,part:c,chunkMeta:u,error:t,err:t,fatal:!1};t.code===DOMException.QUOTA_EXCEEDED_ERR?e.details=l.BUFFER_FULL_ERROR:(this.appendError++,e.details=l.BUFFER_APPEND_ERROR,this.appendError>s.config.appendErrorMaxRetry&&(f.error(`[buffer-controller]: Failed ${s.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),e.fatal=!0)),s.trigger(a.ERROR,e)}};r.append(S,h)}onBufferFlushing(t,e){const{operationQueue:s}=this,r=t=>({execute:this.removeExecutor.bind(this,t,e.startOffset,e.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(a.BUFFER_FLUSHED,{type:t})},onError:e=>{f.warn(`[buffer-controller]: 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[v]?i.push("audiovideo"):(n[y]&&i.push("audio"),n[T]&&i.push("video"));0===i.length&&f.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(a.FRAG_BUFFERED,{frag:s,part:r,stats:e,id:s.type})},i)}onFragChanged(t,e){this.flushBackBuffer()}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,f.log(`[buffer-controller]: ${s} sourceBuffer now EOS`))),t&&!(r&&!r.ended)},!0)&&(f.log("[buffer-controller]: 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?(f.log("[buffer-controller]: Calling mediaSource.endOfStream()"),t.endOfStream()):t&&f.info("[buffer-controller]: 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())}flushBackBuffer(){const{hls:t,details:e,media:s,sourceBuffer:r}=this;if(!s||null===e)return;const i=this.getSourceBufferTypes();if(!i.length)return;const o=e.live&&null!==t.config.liveBackBufferLength?t.config.liveBackBufferLength:t.config.backBufferLength;if(!n(o)||o<0)return;const l=s.currentTime,h=e.levelTargetDuration,d=Math.max(o,h),c=Math.floor(l/h)*h-d;i.forEach(s=>{const i=r[s];if(i){const r=BufferHelper.getBuffered(i);if(r.length>0&&c>r.start(0)){if(t.trigger(a.BACK_BUFFER_REACHED,{bufferEnd:c}),e.live)t.trigger(a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:c});else if(i.ended&&r.end(r.length-1)-l<2*h)return void f.info(`[buffer-controller]: Cannot flush ${s} back buffer while SourceBuffer is in ended state`);t.trigger(a.BUFFER_FLUSHING,{startOffset:0,endOffset:c,type:s})}}})}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,a=s.duration,o=n(r.duration)?r.duration:0;t.live&&e.config.liveDurationInfinity?(f.log("[buffer-controller]: Media Source duration is set to Infinity"),r.duration=1/0,this.updateSeekableRange(t)):(i>o&&i>a||!n(a))&&(f.log("[buffer-controller]: 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);e.setLiveSeekableRange(r,i)}}checkPendingTracks(){const{bufferCodecEventsExpected:t,operationQueue:e,pendingTracks:s}=this,r=Object.keys(s).length;if(r&&!t||2===r){this.createSourceBuffers(s),this.pendingTracks={};const t=this.getSourceBufferTypes();if(t.length)this.hls.trigger(a.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(a.ERROR,{type:o.MEDIA_ERROR,details:l.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 r in t)if(!e[r]){const i=t[r];if(!i)throw Error(`source buffer exists for track ${r}, however track does not`);const n=i.levelCodec||i.codec,h=`${i.container};codecs=${n}`;f.log(`[buffer-controller]: creating sourceBuffer(${h})`);try{const t=e[r]=s.addSourceBuffer(h),a=r;this.addBufferListener(a,"updatestart",this._onSBUpdateStart),this.addBufferListener(a,"updateend",this._onSBUpdateEnd),this.addBufferListener(a,"error",this._onSBUpdateError),this.tracks[r]={buffer:t,codec:n,container:i.container,levelCodec:i.levelCodec,metadata:i.metadata,id:i.id}}catch(t){f.error("[buffer-controller]: error while trying to add sourceBuffer: "+t.message),this.hls.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,mimeType:h})}}}_onSBUpdateStart(t){const{operationQueue:e}=this;e.current(t).onStart()}_onSBUpdateEnd(t){const{operationQueue:e}=this;e.current(t).onComplete(),e.shiftAndExecuteNext(t)}_onSBUpdateError(t,e){const s=new Error(t+" SourceBuffer error");f.error("[buffer-controller]: "+s,e),this.hls.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.BUFFER_APPENDING_ERROR,error:s,fatal:!1});const r=this.operationQueue.current(t);r&&r.onError(e)}removeExecutor(t,e,s){const{media:r,mediaSource:i,operationQueue:a,sourceBuffer:o}=this,l=o[t];if(!r||!i||!l)return f.warn(`[buffer-controller]: Attempting to remove from the ${t} SourceBuffer, but it does not exist`),void a.shiftAndExecuteNext(t);const h=n(r.duration)?r.duration:1/0,d=n(i.duration)?i.duration:1/0,c=Math.max(0,e),u=Math.min(s,h,d);u>c&&!l.ending?(l.ended=!1,f.log(`[buffer-controller]: Removing [${c},${u}] from the ${t} SourceBuffer`),l.remove(c,u)):a.shiftAndExecuteNext(t)}appendExecutor(t,e){const{operationQueue:s,sourceBuffer:r}=this,i=r[e];if(!i)return f.warn(`[buffer-controller]: Attempting to append to the ${e} SourceBuffer, but it does not exist`),void s.shiftAndExecuteNext(e);i.ended=!1,i.appendBuffer(t)}blockBuffers(t,e=this.getSourceBufferTypes()){if(!e.length)return f.log("[buffer-controller]: 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=f.log.bind(f,"[info]:"),this.warn=f.warn.bind(f,"[warning]:"),this.error=f.error.bind(f,"[error]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(a.ERROR,this.onError,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this)}unregisterListeners(){const t=this.hls;t&&(t.off(a.ERROR,this.onError,this),t.off(a.ERROR,this.onErrorOut,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(t){this.playlistError=0}stopLoad(){}getVariantLevelIndex(t){return(null==t?void 0:t.type)===Gt?t.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onError(t,e){var s;if(e.fatal)return;const r=this.hls,i=e.context;switch(e.details){case l.FRAG_LOAD_ERROR:case l.FRAG_LOAD_TIMEOUT:case l.KEY_LOAD_ERROR:case l.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case l.FRAG_GAP:case l.FRAG_PARSING_ERROR:case l.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=Ae);case l.LEVEL_EMPTY_ERROR:case l.LEVEL_PARSING_ERROR:{var n,a;const t=e.parent===Gt?e.level:r.loadLevel;e.details===l.LEVEL_EMPTY_ERROR&&null!=(n=e.context)&&null!=(a=n.levelDetails)&&a.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case l.LEVEL_LOAD_ERROR:case l.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==i?void 0:i.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,i.level)));case l.AUDIO_TRACK_LOAD_ERROR:case l.AUDIO_TRACK_LOAD_TIMEOUT:case l.SUBTITLE_LOAD_ERROR:case l.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const t=r.levels[r.loadLevel];if(t&&(i.type===Bt&&i.groupId===t.audioGroupId||i.type===$t&&i.groupId===t.textGroupId))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,r.loadLevel),e.errorAction.action=Ae,void(e.errorAction.flags=ke)}return;case l.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const t=r.levels[r.loadLevel],s=null==t?void 0:t.attrs["HDCP-LEVEL"];s&&(e.errorAction={action:Ae,flags:De,hdcpLevel:s})}return;case l.BUFFER_ADD_CODEC_ERROR:case l.REMUX_ALLOC_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(s=e.level)?s:r.loadLevel));case l.INTERNAL_EXCEPTION:case l.BUFFER_APPENDING_ERROR:case l.BUFFER_APPEND_ERROR:case l.BUFFER_FULL_ERROR:case l.LEVEL_SWITCH_ERROR:case l.BUFFER_STALLED_ERROR:case l.BUFFER_SEEK_OVER_HOLE:case l.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:Le,flags:be})}if(e.type===o.KEY_SYSTEM_ERROR){const t=this.getVariantLevelIndex(e.frag);return e.levelRetry=!1,void(e.errorAction=this.getLevelSwitchAction(e,t))}}getPlaylistRetryOrSwitchAction(t,e){var s,r;const i=ge(this.hls.config.playlistLoadPolicy,t),n=this.playlistError++,a=null==(s=t.response)?void 0:s.code;return ye(i,n,fe(t),a)?{action:Re,flags:be,retryConfig:i,retryCount:n}:null!=(r=t.context)&&r.deliveryDirectives?{action:Le,flags:be,retryConfig:i||{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},retryCount:n}:this.getLevelSwitchAction(t,e)}getFragRetryOrSwitchAction(t){const e=this.hls,s=this.getVariantLevelIndex(t.frag),r=e.levels[s],{fragLoadPolicy:i,keyLoadPolicy:n}=e.config,a=ge(t.details.startsWith("key")?n:i,t),o=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(r){var h;t.details!==l.FRAG_GAP&&r.fragmentError++;const e=null==(h=t.response)?void 0:h.code;if(ye(a,o,fe(t),e))return{action:Re,flags:be,retryConfig:a,retryCount:o}}const d=this.getLevelSwitchAction(t,s);return a&&(d.retryConfig=a,d.retryCount=o),d}getLevelSwitchAction(t,e){const s=this.hls;null==e&&(e=s.loadLevel);const r=this.hls.levels[e];if(r&&(r.loadError++,s.autoLevelEnabled)){var i,n;let e=-1;const a=s.levels,o=null==(i=t.frag)?void 0:i.type,{type:h,groupId:d}=null!=(n=t.context)?n:{};for(let i=a.length;i--;){const n=(i+s.loadLevel)%a.length;if(n!==s.loadLevel&&0===a[n].loadError){const s=a[n];if(t.details===l.FRAG_GAP&&t.frag){const e=a[n].details;if(e){const s=ve(t.frag,e.fragments,t.frag.start);if(null!=s&&s.gap)continue}}else{if(h===Bt&&d===s.audioGroupId||h===$t&&d===s.textGroupId)continue;if(o===Kt&&r.audioGroupId===s.audioGroupId||o===Ht&&r.textGroupId===s.textGroupId)continue}e=n;break}}if(e>-1&&s.loadLevel!==e)return t.levelRetry=!0,{action:Ae,flags:be,nextAutoLevel:e}}return{action:Ae,flags:ke}}onErrorOut(t,e){var s;switch(null==(s=e.errorAction)?void 0:s.action){case Le:break;case Ae:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===l.FRAG_GAP||(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 be:this.switchLevel(t,n);break;case ke:s.resolved||(s.resolved=this.redundantFailover(t));break;case De:i&&(e.maxHdcpLevel=se[se.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)}redundantFailover(t){const{hls:e,penalizedRenditions:s}=this,r=t.parent===Gt?t.level:e.loadLevel,i=e.levels[r],n=i.url.length,a=t.frag?t.frag.urlId:i.urlId;i.urlId!==a||t.frag&&!i.details||this.penalizeRendition(i,t);for(let o=1;o<n;o++){const l=(a+o)%n,h=s[l];if(!h||Ie(h,t,s[a]))return this.warn(`Switching to Redundant Stream ${l+1}/${n}: "${i.url[l]}" after ${t.details}`),this.playlistError=0,e.levels.forEach(t=>{t.urlId=l}),e.nextLoadLevel=r,!0}return!1}penalizeRendition(t,e){const{penalizedRenditions:s}=this,r=s[t.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};r.lastErrorPerfMs=performance.now(),r.errors.push(e),r.details=t.details,s[t.urlId]=r}},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(a.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(a.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,o=1e3*i/t,l=this.hls;if(l.trigger(a.FPS_DROP,{currentDropped:i,currentDecoded:n,totalDroppedFrames:s}),o>0&&i>l.config.fpsDroppedMonitoringThreshold*n){let t=l.currentLevel;f.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=t)&&(t-=1,l.trigger(a.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:l.currentLevel}),l.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,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:P,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!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:Yr,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]",Ht),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.ERROR,this.onError,this),t.on(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(a.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.ERROR,this.onError,this),t.off(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(a.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(t){this.stopLoad(),this.state=Xe,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=Xe,!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)}onBufferFlushing(t,e){const{startOffset:s,endOffset:r}=e;if(0===s&&r!==Number.POSITIVE_INFINITY){const{currentTrackId:t,levels:i}=this;if(!i.length||!i[t]||!i[t].details)return;const n=r-i[t].details.targetduration;if(n<=0)return;e.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach(t=>{for(let e=0;e<t.length;)if(t[e].end<=n)t.shift();else{if(!(t[e].start<n))break;t[e].start=n,e++}}),this.fragmentTracker.removeFragmentsInRange(s,n,Ht)}}onFragBuffered(t,e){var s;this.loadedmetadata||e.frag.type!==Gt||null!=(s=this.media)&&s.buffered.length&&(this.loadedmetadata=!0)}onError(t,e){const s=e.frag;(null==s?void 0:s.type)===Ht&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==je&&(this.state=Xe))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){zs(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,Ht),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){if(this.currentTrackId=e.id,!this.levels.length||-1===this.currentTrackId)return void this.clearInterval();const s=this.levels[this.currentTrackId];null!=s&&s.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,s&&this.setInterval(500)}onSubtitleTrackLoaded(t,e){var s;const{details:r,id:i}=e,{currentTrackId:n,levels:a}=this;if(!a.length)return;const o=a[n];if(i>=a.length||i!==n||!o)return;this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(r.live||null!=(s=o.details)&&s.live){const t=this.mainDetails;if(r.deltaUpdateFailed||!t)return;const e=t.fragments[0];o.details?(l=this.alignPlaylists(r,o.details),0===l&&e&&(l=e.start,de(r,l))):r.hasProgramDateTime&&t.hasProgramDateTime?(We(r,t),l=r.fragments[0].start):e&&(l=e.start,de(r,l))}if(o.details=r,this.levelLastLoaded=i,this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(o.details,l),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===Xe){ve(null,r.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&&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(a.ERROR,{type:o.MEDIA_ERROR,details:l.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(s=>{const r=performance.now();i.trigger(a.FRAG_DECRYPTED,{frag:e,payload:s,stats:{tstart:t,tdecrypt:r}})}).catch(t=>{this.warn(`${t.name}: ${t.message}`),this.state=Xe})}}doTick(){if(this.media){if(this.state===Xe){const{currentTrackId:t,levels:e}=this,s=e[t];if(!e.length||!s||!s.details)return;const r=s.details,i=r.targetduration,{config:n}=this,a=this.getLoadPosition(),o=BufferHelper.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a-i,n.maxBufferHole),{end:l,len:h}=o,d=this.getFwdBufferInfo(this.media,Gt);if(h>this.getMaxBufferLength(null==d?void 0:d.len)+i)return;const c=r.fragments,u=c.length,f=r.edge;let g=null;const m=this.fragPrevious;if(l<f){const{maxFragLookUpTolerance:t}=n;g=ve(m,c,Math.max(c[0].start,l),t),!g&&m&&m.start<c[0].start&&(g=c[0])}else g=c[u-1];if(!g)return;g=this.mapToInitFragWhenRequired(g),this.fragmentTracker.getState(g)===Pe&&this.loadFragment(g,s,l)}}else this.state=Xe}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.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(a.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.trackChangeListener,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);Js(this.media.textTracks).forEach(t=>{jt(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:s,details:r}=e,{trackId:i}=this,n=this.tracksInGroup[i];if(!n)return void this.warn("Invalid subtitle track id "+s);const a=n.details;n.details=e.details,this.log(`subtitle track ${s} loaded [${r.startSN}-${r.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(null==e||!e.textGroupIds)return;const s=e.textGroupIds[e.urlId],r=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==s){const t=this.tracks.filter(t=>!s||t.groupId===s);this.tracksInGroup=t;const e=this.findTrackId(null==r?void 0:r.name)||this.findTrackId();this.groupId=s||null;const i={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${s}" group-id`),this.hls.trigger(a.SUBTITLE_TRACKS_UPDATED,i),-1!==e&&this.setSubtitleTrack(e,r)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId,r)}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const r=e[s];if((!this.selectDefaultTrack||r.default)&&(!t||t===r.name))return r.id}return-1}onError(t,e){!e.fatal&&e.context&&e.context.type===$t&&e.context.id===this.trackId&&e.context.groupId===this.groupId&&this.checkRetry(e)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1;const e=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(t,e)}loadPlaylist(t){super.loadPlaylist();const e=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(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(a.SUBTITLE_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null})}}toggleTrackModes(t){const{media:e,trackId:s}=this;if(!e)return;const r=Js(e.textTracks),i=r.filter(t=>t.groupId===this.groupId);if(-1===t)[].slice.call(r).forEach(t=>{t.mode="disabled"});else{const t=i[s];t&&(t.mode="disabled")}const n=i[t];n&&(n.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(t,e){var s;const r=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=t);if(this.trackId!==t&&this.toggleTrackModes(t),this.trackId===t&&(-1===t||null!=(s=r[t])&&s.details)||t<-1||t>=r.length)return;this.clearTimer();const i=r[t];if(this.log("Switching to subtitle-track "+t+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:"")),this.trackId=t,i){const{id:t,groupId:s="",name:r,type:n,url:o}=i;this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:t,groupId:s,name:r,type:n,url:o});const l=this.switchParams(i.url,null==e?void 0:e.details);this.loadPlaylist(l)}else this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:t})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1;const e=Js(this.media.textTracks);for(let s=0;s<e.length;s++)if("hidden"===e[s].mode)t=s;else if("showing"===e[s].mode){t=s;break}this.subtitleTrack!==t&&(this.subtitleTrack=t)}},timelineController:class TimelineController{constructor(t){if(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.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}},this.config.enableCEA708Captions){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)}t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(a.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(a.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(t,e,s,r,i){let n=!1;for(let t=i.length;t--;){const r=i[t],a=(o=r[0],l=r[1],h=e,d=s,Math.min(l,d)-Math.max(o,h));if(a>=0&&(r[0]=Math.min(r[0],e),r[1]=Math.max(r[1],s),n=!0,a/(s-e)>.5))return}var o,l,h,d;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(a.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(a.FRAG_LOADED,t)}))}getExistingTrack(t){const{media:e}=this;if(e)for(let s=0;s<e.textTracks.length;s++){const r=e.textTracks[s];if(r[t])return r}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(t);if(a)s[t]=a,jt(s[t]),Wt(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(a.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=>{jt(t[e]),delete t[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){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.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++)jt(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(zs(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const t=this.media?this.media.textTracks:null;this.tracks.forEach((e,s)=>{let r;if(t&&s<t.length){let s=null;for(let r=0;r<t.length;r++)if(Pr(t[r],e)){s=t[r];break}s&&(r=s)}if(r)jt(r);else{const t=this._captionsOrSubtitlesFromCharacteristics(e);r=this.createTextTrack(t,e.name,e.lang),r&&(r.mode="disabled")}r&&(r.groupId=e.groupId,this.textTracks.push(r))})}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(a.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}}}_captionsOrSubtitlesFromCharacteristics(t){if(t.attrs.CHARACTERISTICS){const e=/transcribes-spoken-dialog/gi.test(t.attrs.CHARACTERISTICS),s=/describes-music-and-sound/gi.test(t.attrs.CHARACTERISTICS);if(e&&s)return"captions"}return"subtitles"}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){const{cea608Parser1:s,cea608Parser2:r,lastSn:i,lastPartIndex:n}=this;if(this.enabled&&s&&r&&e.frag.type===Gt){var a,o;const t=e.frag.sn,l=null!=(a=null==e||null==(o=e.part)?void 0:o.index)?a:-1;t===i+1||t===i&&l===n+1||(s.reset(),r.reset()),this.lastSn=t,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:s,payload:r}=e,{initPTS:i,unparsedVttFrags:n}=this;if(s.type===Ht)if(r.byteLength){if(!i[s.cc])return n.push(e),void(i.length&&this.hls.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Missing initial subtitle PTS")}));const t=s.decryptdata,o="stats"in e;if(null==t||!t.encrypted||o){const t=this.tracks[s.level],e=this.vttCCs;e[s.cc]||(e[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(s,r,e)}}else this.hls.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,e){const s=this.hls;kr(e,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),s.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},e=>{f.log("Failed to parse IMSC1: "+e),s.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:e})})}_parseVTTs(t,e,s){var r;const i=this.hls;Lr(null!=(r=t.initSegment)&&r.data?dt(t.initSegment.data,new Uint8Array(e)):e,this.initPTS[t.cc],s,t.cc,t.start,e=>{this._appendCues(e,t.level),i.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},s=>{this._fallbackToIMSC1(t,e),f.log("Failed to parse VTT cue: "+s),i.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:s})})}_fallbackToIMSC1(t,e){const s=this.tracks[t.level];s.textCodec||kr(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=>qt(s,t))}else{const r=this.tracks[e];if(!r)return;const i=r.default?"default":"subtitles"+e;s.trigger(a.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,e){const{frag:s}=e;if(s.type===Ht){if(!this.initPTS[s.cc])return void this.unparsedVttFrags.push(e);this.onFragLoaded(a.FRAG_LOADED,e)}}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){const{cea608Parser1:s,cea608Parser2:r}=this;if(!this.enabled||!s||!r)return;const{frag:i,samples:n}=e;if(i.type!==Gt||"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=>Xt(t[r],e,s))}if(this.config.renderTextTracksNatively&&0===e&&void 0!==r){const{textTracks:t}=this;Object.keys(t).forEach(s=>Xt(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]",Kt),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.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(a.ERROR,this.onError,this),t.on(a.BUFFER_RESET,this.onBufferReset,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(a.ERROR,this.onError,this),t.off(a.BUFFER_RESET,this.onBufferReset,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.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===is&&this.tick()}}startLoad(t){if(!this.levels)return this.startPosition=t,void(this.state=je);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=Xe):(this.loadedmetadata=!1,this.state=Ze),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}doTick(){switch(this.state){case Xe:this.doTickIdle();break;case Ze:{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=is}break}case Je:{var e;const t=performance.now(),s=this.retryDate;(!s||t>=s||null!=(e=this.media)&&e.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=Xe);break}case is:{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=Qe;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);Ee(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=Xe}}this.onTickEnd()}clearWaitingFragment(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Xe)}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(null==e||!e[r])return;if(!s&&(this.startFragRequested||!i.startFragPrefetch))return;const n=e[r],o=n.details;if(!o||o.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(o))return void(this.state=Ze);const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,y,Kt));const h=this.getFwdBufferInfo(l,Kt);if(null===h)return;const{bufferedTrack:d,switchingTrack:c}=this;if(!c&&this._streamEnded(h,o))return t.trigger(a.BUFFER_EOS,{type:"audio"}),void(this.state=ss);const u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,Gt),f=h.len,g=this.getMaxBufferLength(null==u?void 0:u.len);if(f>=g&&!c)return;const m=o.fragments[0].start;let p=h.end;if(c&&s){const t=this.getLoadPosition();d&&c.attrs!==d.attrs&&(p=t),o.PTSKnown&&t<m&&(h.end>m||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=m+.05)}let T=this.getNextFragment(p,o),v=!1;if(T&&this.isLoopLoading(T,p)&&(v=!!T.gap,T=this.getNextFragmentLoopLoading(T,o,h,Gt,g)),!T)return void(this.bufferFlushed=!0);const E=u&&T.start>u.end+o.targetduration;if(E||(null==u||!u.len)&&h.len){const t=this.fragmentTracker.getBufferedFrag(T.start,Gt);if(null===t)return;if(v||(v=!!t.gap||!!E&&0===u.len),E&&!v||v&&h.nextStart&&h.nextStart<t.end)return}this.loadFragment(T,n,p)}getMaxBufferLength(t){const e=super.getMaxBufferLength();return t?Math.min(Math.max(e,t),this.config.maxMaxBufferLength):e}onMediaDetaching(){this.videoBuffer=null,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=Xe):(this.switchingTrack=null,this.bufferedTrack=e,this.state=je),this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.bufferedTrack=null,this.switchingTrack=null}onLevelLoaded(t,e){this.mainDetails=e.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(a.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(`Track ${n} loaded [${i.startSN},${i.endSN}],duration:${i.totalduration}`);const a=r[n];let o=0;if(i.live||null!=(s=a.details)&&s.live){const t=this.mainDetails;if(i.fragments[0]||(i.deltaUpdateFailed=!0),i.deltaUpdateFailed||!t)return;!a.details&&i.hasProgramDateTime&&t.hasProgramDateTime?(We(i,t),o=i.fragments[0].start):o=this.alignPlaylists(i,a.details)}a.details=i,this.levelLastLoaded=n,this.startFragRequested||!this.mainDetails&&i.live||this.setStartPosition(a.details,o),this.state!==Ze||this.waitForCdnTuneIn(i)||(this.state=Xe),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,Kt,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=is}}_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:r,part:i}=e;var n;if(r.type===Kt)if(this.fragContextChanged(r))this.warn(`Fragment ${r.sn}${i?" p: "+i.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==r.sn){this.fragPrevious=r;const t=this.switchingTrack;t&&(this.bufferedTrack=t,this.switchingTrack=null,this.hls.trigger(a.AUDIO_TRACK_SWITCHED,s({},t)))}this.fragBufferedComplete(r,i)}else this.loadedmetadata||r.type!==Gt||null!=(n=this.videoBuffer||this.media)&&n.buffered.length&&(this.loadedmetadata=!0)}onError(t,e){var s;if(e.fatal)this.state=rs;else switch(e.details){case l.FRAG_GAP:case l.FRAG_PARSING_ERROR:case l.FRAG_DECRYPT_ERROR:case l.FRAG_LOAD_ERROR:case l.FRAG_LOAD_TIMEOUT:case l.KEY_LOAD_ERROR:case l.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Kt,e);break;case l.AUDIO_TRACK_LOAD_ERROR:case l.AUDIO_TRACK_LOAD_TIMEOUT:case l.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Ze||(null==(s=e.context)?void 0:s.type)!==Bt||(this.state=Xe);break;case l.BUFFER_FULL_ERROR:if(!e.parent||"audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case l.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushed(t,{type:e}){e===y&&(this.bufferFlushed=!0,this.state===ss&&(this.state=Xe))}_handleTransmuxComplete(t){var e;const s="audio",{hls:r}=this,{remuxResult:n,chunkMeta:o}=t,l=this.getCurrentContext(o);if(!l)return void this.resetWhenMissingContext(o);const{frag:h,part:d,level:c}=l,{details:u}=c,{audio:f,text:g,id3:m,initSegment:p}=n;if(!this.fragContextChanged(h)&&u){if(this.state=ts,this.switchingTrack&&f&&this.completeAudioSwitch(this.switchingTrack),null!=p&&p.tracks&&(this._bufferInitSegment(p.tracks,h,o),r.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:h,id:s,tracks:p.tracks})),f){const{startPTS:t,endPTS:e,startDTS:s,endDTS:r}=f;d&&(d.elementaryStreams[y]={startPTS:t,endPTS:e,startDTS:s,endDTS:r}),h.setElementaryStreamInfo(y,t,e,s,r),this.bufferFragmentData(f,h,d,o)}if(null!=m&&null!=(e=m.samples)&&e.length){const t=i({id:s,frag:h,details:u},m);r.trigger(a.FRAG_PARSING_METADATA,t)}if(g){const t=i({id:s,frag:h,details:u},g);r.trigger(a.FRAG_PARSING_USERDATA,t)}}else this.fragmentTracker.removeFragment(h)}_bufferInitSegment(t,e,s){if(this.state!==ts)return;t.video&&delete t.video;const r=t.audio;if(!r)return;r.levelCodec=r.codec,r.id="audio",this.log(`Init audio buffer, container:${r.container}, codecs[parsed]=[${r.codec}]`),this.hls.trigger(a.BUFFER_CODECS,t);const i=r.initSegment;if(null!=i&&i.byteLength){const t={type:"audio",frag:e,part:null,chunkMeta:s,parent:e.type,data:i};this.hls.trigger(a.BUFFER_APPENDING,t)}this.tick()}loadFragment(t,e,s){const r=this.fragmentTracker.getState(t);var i;(this.fragCurrent=t,this.switchingTrack||r===Pe||r===xe)?"initSegment"===t.sn?this._loadInitSegment(t,e):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=is):(this.startFragRequested=!0,super.loadFragment(t,e,s)):this.clearTrackerIfNeeded(t)}completeAudioSwitch(t){const{hls:e,media:r,bufferedTrack:i}=this,n=null==i?void 0:i.attrs,o=t.attrs;r&&n&&(n.CHANNELS!==o.CHANNELS||n.NAME!==o.NAME||n.LANGUAGE!==o.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=t,this.switchingTrack=null,e.trigger(a.AUDIO_TRACK_SWITCHED,s({},t))}},audioTrackController:class AudioTrackController extends BasePlaylistController{constructor(t){super(t,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(a.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,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(`Track with id:${s} and group:${r} not found in active group ${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(null==e||!e.audioGroupIds)return;const s=e.audioGroupIds[e.urlId];if(this.groupId!==s){this.groupId=s||null;const t=this.tracks.filter(t=>!s||t.groupId===s);this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=t;const e={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group:${s}`),this.hls.trigger(a.AUDIO_TRACKS_UPDATED,e),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(t,e){!e.fatal&&e.context&&e.context.type===Bt&&e.context.id===this.trackId&&e.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(e))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioTrack(t){const e=this.tracksInGroup;if(t<0||t>=e.length)return void this.warn("Invalid id passed to audio-track controller");this.clearTimer();const r=this.currentTrack;e[this.trackId];const i=e[t],{groupId:n,name:o}=i;if(this.log(`Switching to audio-track ${t} "${o}" lang:${i.lang} group:${n}`),this.trackId=t,this.currentTrack=i,this.selectDefaultTrack=!1,this.hls.trigger(a.AUDIO_TRACK_SWITCHING,s({},i)),i.details&&!i.details.live)return;const l=this.switchParams(i.url,null==r?void 0:r.details);this.loadPlaylist(l)}selectInitialTrack(){const t=this.tracksInGroup,e=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(-1!==e)this.setAudioTrack(e);else{const e=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(a.ERROR,{type:o.MEDIA_ERROR,details:l.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}findTrackId(t){const e=this.tracksInGroup;for(let s=0;s<e.length;s++){const r=e[s];if(!this.selectDefaultTrack||r.default){if(!t||t.attrs["STABLE-RENDITION-ID"]===r.attrs["STABLE-RENDITION-ID"])return r.id;if(t.name===r.name&&t.lang===r.lang)return r.id}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(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 audio-track playlist ${s} "${e.name}" lang:${e.lang} group:${r}`),this.clearTimer(),this.hls.trigger(a.AUDIO_TRACK_LOADING,{url:i,id:s,groupId:r,deliveryDirectives:t||null})}}},emeController:EMEController,cmcdController:CMCDController,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=f.log.bind(f,"[content-steering]:"),this.registerListeners()}registerListeners(){const t=this.hls;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.ERROR,this.onError,this))}startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){const t=Math.max(1e3*this.timeToLoad-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,t)}else this.loadSteeringManifest(this.uri)}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),self.clearTimeout(this.reloadTimer)}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)===Ae&&s.flags===ke){let t=this.pathwayPriority;const e=this.pathwayId;this.penalizedPathways[e]||(this.penalizedPathways[e]=performance.now()),!t&&this.levels&&(t=this.levels.reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])),t&&t.length>1&&(this.updatePathwayPriority(t),s.resolved=this.pathwayId!==e)}}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(s[i])continue;if(i===this.pathwayId)return;const n=this.hls.nextLoadLevel,o=this.hls.levels[n];if(e=this.getLevelsForPathway(i),e.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,this.hls.trigger(a.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];o&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}clonePathways(t){const e=this.levels;if(!e)return;const s={},r={};t.forEach(t=>{const{ID:n,"BASE-ID":a,"URI-REPLACEMENT":o}=t;if(e.some(t=>t.pathwayId===n))return;const l=this.getLevelsForPathway(a).map(t=>{const e=i({},t);e.details=void 0,e.url=$r(t.uri,t.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",o);const a=new AttrList(t.attrs);a["PATHWAY-ID"]=n;const l=a.AUDIO&&`${a.AUDIO}_clone_${n}`,h=a.SUBTITLES&&`${a.SUBTITLES}_clone_${n}`;l&&(s[a.AUDIO]=l,a.AUDIO=l),h&&(r[a.SUBTITLES]=h,a.SUBTITLES=h),e.attrs=a;const d=new Level(e);return we(d,"audio",l),we(d,"text",h),d});e.push(...l),Br(this.audioTracks,s,o,n),Br(this.subtitleTracks,r,o,n)})}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),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){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(t)},e)}}});function qr(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(qr):Object.keys(t).reduce((e,s)=>(e[s]=qr(t[s]),e),{}):t}function jr(t){const e=t.loader;if(e!==FetchLoader&&e!==XhrLoader)f.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,f.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Hls{static get version(){return"1.4.0"}static isSupported(){return function(){const t=as();if(!t)return!1;const e=os(),s=t&&"function"==typeof t.isTypeSupported&&t.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),r=!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove;return!!s&&!!r}()}static get Events(){return a}static get ErrorTypes(){return o}static get ErrorDetails(){return l}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:Wr}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._emitter=new js,this._autoLevelCapping=void 0,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,function(t,e){if(self.console&&!0===t||"object"==typeof t){u(t,"debug","log","info","warn","error");try{c.log(`Debug logs enabled for "${e}" in hls.js version 1.4.0`)}catch(t){c=d}}else c=d}(t.debug||!1,"Hls instance");const e=this.config=function(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=qr(t),i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const s=("level"===t?"playlist":t)+"LoadPolicy",n=void 0===e[s],a=[];i.forEach(i=>{const o=`${t}Loading${i}`,l=e[o];if(void 0!==l&&n){a.push(o);const t=r[s].default;switch(e[s]={default:t},i){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&&f.warn(`hls.js config: "${a.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(e[s])}`)}),s(s({},r),e)}(Hls.DefaultConfig,t);this.userConfig=t,this._autoLevelCapping=-1,e.progressive&&jr(e);const{abrController:r,bufferController:i,capLevelController:n,errorController:o,fpsController:l}=e,h=new o(this),g=this.abrController=new r(this),m=this.bufferController=new i(this),p=this.capLevelController=new n(this),y=new l(this),T=new PlaylistLoader(this),v=new ID3TrackController(this),E=e.contentSteeringController,S=E?new E(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);p.setStreamController(b),y.setStreamController(b);const k=[T,L,b];S&&k.splice(1,0,S),this.networkControllers=k;const D=[g,m,p,y,v,A];this.audioTrackController=this.createController(e.audioTrackController,k);const I=e.audioStreamController;I&&k.push(new I(this,A,R)),this.subtitleTrackController=this.createController(e.subtitleTrackController,k);const C=e.subtitleStreamController;C&&k.push(new C(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(h);const w=h.onErrorOut;"function"==typeof w&&this.on(a.ERROR,w,h)}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){f.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),this.trigger(a.ERROR,{type:o.OTHER_ERROR,details:l.INTERNAL_EXCEPTION,fatal:!1,event:t,error:e})}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){f.log("destroy"),this.trigger(a.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){f.log("attachMedia"),this._media=t,this.trigger(a.MEDIA_ATTACHING,{media:t})}detachMedia(){f.log("detachMedia"),this.trigger(a.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const s=this.media,r=this.url,i=this.url=t.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});f.log("loadSource:"+i),s&&r&&r!==i&&this.bufferController.hasSourceTypes()&&(this.detachMedia(),this.attachMedia(s)),this.trigger(a.MANIFEST_LOADING,{url:e})}startLoad(t=-1){f.log(`startLoad(${t})`),this.networkControllers.forEach(e=>{e.startLoad(t)})}stopLoad(){f.log("stopLoad"),this.networkControllers.forEach(t=>{t.stopLoad()})}swapAudioCodec(){f.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){f.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t,e=0){this.levelController.removeLevel(t,e)}get levels(){const t=this.levelController.levels;return t||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){f.log("set currentLevel:"+t),this.loadLevel=t,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){f.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){f.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){f.log("set firstLevel:"+t),this.levelController.firstLevel=t}get startLevel(){return this.levelController.startLevel}set startLevel(t){f.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}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(f.log("set autoLevelCapping:"+t),this._autoLevelCapping=t)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){se.indexOf(t)>-1&&(this._maxHdcpLevel=t)}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&&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 nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}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 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 Xr=Object.freeze({__proto__:null,ATTACHED:"hls:attached"});function zr(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 Qr="application/vnd.apple.mpegURL",Jr=[Qr,"application/x-mpegurl"],Zr=document.createElement("video").canPlayType(Qr);function ti(t){const{pathname:e}=function(t){const e=document.createElement("a");return e.href=t,e}(t);return e.endsWith(".m3u8")}const ei=window&&window.Hls||Hls;var si="audio:set",ri="audio:update",ii="audio:tracks";var ni=Object.assign(Object.assign({},{"http.404":"the video was not found","http.403":"access to this video was denied","http.410":"the video no longer exists","http.live.404":"stream is offline","http.0":"no internet connection detected"}),{keySystemNoKeys:"no keys",keySystemNoAccess:"no access to key system",keySystemNoSession:"no session for key system",keySystemLicenseRequestFailed:"license request failed",keyLoadError:"decrypt key load failed",keyLoadTimeOut:"decrypt key load timed outs"});var ai,oi;function li(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}!function(t){t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=4]="HIGH"}(ai||(ai={})),function(t){t[t.FRAGMENT_ERRORS=0]="FRAGMENT_ERRORS",t[t.STALE_MANIFEST=1]="STALE_MANIFEST"}(oi||(oi={}));const hi=li("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;this.reset();const s=this.hls;if(!s)return;const r=s.levels[s.currentLevel];if(!r)return;if(r.url.length<2)return;const i=s.levels[s.currentLevel].details,n=(r.urlId+1)%r.url.length;s.levels.forEach(t=>{t.urlId=n}),null===(e=s.media)||void 0===e||e.dispatchEvent(new CustomEvent("hls/failover",{detail:{reason:t,from:null==i?void 0:i.url}}))}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||(hi(`${t} / no change in ${s.count} tries`,this.playlistCounts),this.failover(oi.STALE_MANIFEST)))}trackFragmentError(t){const e=this.fragmentFailures[t]||0;this.fragmentFailures[t]=e+1,this.fragmentFailures[t]>2&&this.failover(oi.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 di=li("hls");function ci(t,e,s,r){if(!t.reaper||!s.src)return;t.hls&&t.hls.destroy();const i="live"in e==0,n={is_audio_only:!1,fragDuration:-1,media_recovers:0,audio_swaps:0};if(s.drm&&"https:"!==location.protocol&&"localhost"!==location.hostname&&"127.0.0.1"!==location.hostname)return t.emit("error",{message:"Secure page required for DRM"});const a=new FailoverLoaderController,o=function(t){return Object.assign(Object.assign({autoStartLoad:!1,levelLoadingMaxRetry:1},t.hls),{startPosition:t.start_time||-1})}(e);o.renderTextTracksNatively=!1,o.pLoader=a.createPlaylistLoader(r),o.fLoader=a.createFragmentLoader();const l=t.hls=new ei(o);a.setHls(l),l.subtitleDisplay=!1,l.attachMedia(t),l.loadSource(s.src),t.emit("hls:attached",{hls:l}),function(t,e){t.on(Hls.Events.AUDIO_TRACKS_UPDATED,(function(t,s){e.emit(ii,s.audioTracks)})),t.on(Hls.Events.AUDIO_TRACK_SWITCHING,(function(t,s){e.emit(ri,s)})),t.on(Hls.Events.MANIFEST_PARSED,(function(t,s){s.audioTracks&&e.emit(ii,s.audioTracks)})),t.on(Hls.Events.LEVEL_SWITCHED,(function(s,r){const i=t.levels[r.level];i&&e.emit(ii,t.audioTracks.filter((function(t){return t.groupId&&~(i.audioGroupIds||[]).indexOf(t.groupId)})))}))}(l,t),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)})}(l,t);const h=function(t){var e;const s=null===(e=t.data)||void 0===e?void 0:e.level;"number"==typeof s&&(l.levels[s]||-1===s?l.nextLevel=s:console.error(new Error("skipping invalid quality: "+t.data)))},d=function(t){var e;const s=null===(e=t.data)||void 0===e?void 0:e.id;"number"==typeof s&&s!=l.audioTrack&&setTimeout((function(){l.audioTrack=s}),0)};t.on("quality:set",h),t.on(si,d),t.on("src",(function(){t.off("quality:set",h),t.off(si,d),t.hls&&(t.hls.destroy(),delete t.hls,r.manifest=void 0)}));let c=0;t.on("error",e=>{var s;++c,c>=5||!t.hls||(null===(s=null==t?void 0:t.error)||void 0===s?void 0:s.code)!==MediaError.MEDIA_ERR_DECODE||(e.preventDefault(),l.config.autoStartLoad=!0,l.recoverMediaError())}),t.on("canplay",()=>c=0),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?ui(t,e.start_time||-1):void t.hls.once(ei.Events.MANIFEST_PARSED,()=>{setTimeout(()=>{ui(t,e.start_time||-1)},0)})}),t.on("tracks:video:select",(function(e){var s;const r=e.detail.track,i=null===(s=t.tracks)||void 0===s?void 0:s.find(t=>t.selected&&t!==r),n=t.hls;if(!i||!r||!n)return;i.selected=!1;const a=r.data.slice(0).map(t=>(t.details=void 0,t));n.stopLoad(),n.levelController._levels=n.streamController.levels=a,n.currentLevel=-1,n.levelController.currentLevelIndex=-1,t.emit("qualities",fi(a)),t.hasState("is-starting")&&!t.hasState("is-loading")||n.startLoad()})),t.on("audioonlysource",(function(){n.is_audio_only=!0})),t.on("reap",(function(){l&&l.destroy()})),t.on("remotesession:started",()=>{t.hls&&t.hls.stopLoad()}),t.on("remotesession:ended",()=>{t.hls&&ui(t)}),t.on("retry",r=>{if(t.hls){if(r.preventDefault(),s.src&&l.loadSource(t.original_src),e.autoplay)return t.togglePlay(!0);t.setState("is-waiting",!1),t.emit("retry/done")}}),i&&l.on(ei.Events.LEVEL_LOADED,(function(e,s){t.setOpts({live:s.details.live})})),l.on(ei.Events.MANIFEST_PARSED,(function(i,n){const a=fi(n.levels);t.emit("qualities",a),t.emit("parse:video:tracks",{url:s.src,manifest:r.manifest}),function(t,e,s){var r,i;if(!t.hls)return;di("Initializer::maybe_start_load_with_quality (start_quality, preload): (%d, %s)",e.start_quality,e.preload),void 0!==e.start_quality&&(ai.HIGH&e.start_quality&&(t.hls.startLevel=s[0].level),ai.LOW&e.start_quality&&(t.hls.startLevel=s[s.length-1].level),ai.MEDIUM&e.start_quality&&(t.hls.startLevel=s[Math.ceil(s.length/2)-1].level));const n=(null===(r=e.hls)||void 0===r?void 0:r.maxBufferSize)||1024,a=(null===(i=e.hls)||void 0===i?void 0:i.maxBufferLength)||30;di("Setting maxBufferSize to %d",n),t.hls.config.maxBufferSize=n,"metadata"===e.preload&&di("preload === metadata, setting maxBufferLength to 1sec");t.hls.config.maxBufferLength="metadata"===e.preload?1:a,t.once("playing",()=>{di("Playback started, set maxBufferLenght to %d",a),t.hls&&(t.hls.config.maxBufferLength=a)}),("none"!==e.preload||e.autoplay&&t.hasState("is-in-viewport"))&&ui(t,e.start_time||-1)}(t,e,a.slice(0,-1));const o=a.find(t=>!!t.videoCodec);o||t.emit("audioonlysource"),!t.opt("ratio")&&o&&0!=o.width&&0!=o.height&&t.setOpts({ratio:o.width+":"+o.height})})),l.on(ei.Events.INIT_PTS_FOUND,(function(t,e){n.fragDuration=e.frag.duration})),l.on(ei.Events.ERROR,(function(e,s){!function(t,e,s){var r,i,n,a;if(0==t.reaper)return;if(0==e.fatal)return;switch(e.type){case ei.ErrorTypes.MEDIA_ERROR:return di("recovering from "+e.type),s.media_recovers+5e3>Date.now()&&0==s.audio_swaps?(null===(r=t.hls)||void 0===r||r.swapAudioCodec(),di(`calling swapAudioCodec() : {count=${s.audio_swaps}}`),s.audio_swaps++,s.media_recovers=Date.now(),null===(i=t.hls)||void 0===i?void 0:i.recoverMediaError()):(s.media_recovers=Date.now(),s.audio_swaps=0,null===(n=t.hls)||void 0===n?void 0:n.recoverMediaError());case ei.ErrorTypes.NETWORK_ERROR:return function(t,e){var s;const r=(null===(s=e.networkDetails)||void 0===s?void 0:s.status)||e.details;let i=t.opts.live?"http.live.":"http.";i+=r.toString();const n=t.i18n("error."+i,ni[i]||"an error occurred while loading this video");t.emit("error",{code:i,message:n,fatal:!0})}(t,e);case ei.ErrorTypes.KEY_SYSTEM_ERROR:return function(t,e){var s;t.emit("error",{fatal:!0,message:ni[e.details]||"an error occurred while accessing this video"}),null===(s=t.hls)||void 0===s||s.destroy()}(t,e);default:null===(a=t.hls)||void 0===a||a.destroy()}}(t,s,n)})),l.on(ei.Events.LEVEL_PTS_UPDATED,(function(e,s){var r;if("video"!==s.type&&(!n.is_audio_only||"audio"!==s.type))return;const i=null===(r=null==s?void 0:s.details)||void 0===r?void 0:r.fragments;if(!i)return;const a=i[0].start||0,o=(l.liveSyncPosition||i[i.length-1].start)+i[i.length-1].duration;t.emit("dvr/window",o-a)})),l.on(ei.Events.LEVEL_SWITCHING,(e,s)=>{const r=l.levels[l.currentLevel],i=l.levels[s.level];t.emit("qualitychange",{before:r,after:i,kind:"hls"})});const u=t.opt("start_time");u&&t.once("loadedmetadata",(function(){t.currentTime=u}))}function ui(t,e){var s;!t.hasState("is-loaded")&&t.setState("is-loading",!0),null===(s=t.hls)||void 0===s||s.startLoad(e)}function fi(t){const e=t.map((t,e)=>({level:e,text:t.name||t.width+"",width:t.width,height:t.height,videoCodec:t.videoCodec||""})).sort((t,e)=>e.width-t.width);return t.length>1&&t.every(t=>void 0!==t.bitrate)&&e.push({text:"AUTO",level:-1,width:0,height:0,videoCodec:""}),e}class HLS{init(){}onload(t,e,s,r){ci(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="native"in i&&i.native;return(!Zr||!n)&&(!(s&&!Object.keys(s).find(t=>zr(t)))&&(!(!e||!Jr.includes(e))||ti(t)))}(e,s)}}return HLS.events=Xr,HLS.version=Hls.version,HLS.failover={Reasons:oi},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;"function"==typeof s?s(e):(Array.isArray(s.extensions)||(s.extensions=[]),~s.extensions.indexOf(e)||s.extensions.push(e))}(window,HLS),HLS}));
|