1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[888],{50664:(e,t,i)=>{let r,s,a;i.d(t,{A:()=>sm});var n,l,o,h,d,u,c,f,g,m={exports:{}};n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,l=/^(?=([^\/?#]*))\1([^]*)$/,o=/(?:\/|^)\.(?=\/)/g,h=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,m.exports=d={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var r=d.parseURL(e);if(!r)throw Error("Error trying to parse base URL.");return r.path=d.normalizePath(r.path),d.buildURLFromParts(r)}var s=d.parseURL(t);if(!s)throw Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=d.normalizePath(s.path),d.buildURLFromParts(s)):t;var a=d.parseURL(e);if(!a)throw Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var n=l.exec(a.path);a.netLoc=n[1],a.path=n[2]}a.netLoc&&!a.path&&(a.path="/");var o={scheme:a.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(o.netLoc=a.netLoc,"/"!==s.path[0]))if(s.path){var h=a.path,u=h.substring(0,h.lastIndexOf("/")+1)+s.path;o.path=d.normalizePath(u)}else o.path=a.path,!s.params&&(o.params=a.params,s.query||(o.query=a.query));return null===o.path&&(o.path=i.alwaysNormalize?d.normalizePath(s.path):s.path),d.buildURLFromParts(o)},parseURL:function(e){var t=n.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(o,"");e.length!==(e=e.replace(h,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};var p=m.exports;function y(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function T(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?y(Object(i),!0).forEach(function(t){var r,s,a;r=e,s=t,a=i[t],(s=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t||"default");if("object"!=typeof r)return r;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}(s))in r?Object.defineProperty(r,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):r[s]=a}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):y(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function E(){return(E=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)Object.prototype.hasOwnProperty.call(i,r)&&(e[r]=i[r])}return e}).apply(this,arguments)}let v=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},S=((u={}).MEDIA_ATTACHING="hlsMediaAttaching",u.MEDIA_ATTACHED="hlsMediaAttached",u.MEDIA_DETACHING="hlsMediaDetaching",u.MEDIA_DETACHED="hlsMediaDetached",u.BUFFER_RESET="hlsBufferReset",u.BUFFER_CODECS="hlsBufferCodecs",u.BUFFER_CREATED="hlsBufferCreated",u.BUFFER_APPENDING="hlsBufferAppending",u.BUFFER_APPENDED="hlsBufferAppended",u.BUFFER_EOS="hlsBufferEos",u.BUFFER_FLUSHING="hlsBufferFlushing",u.BUFFER_FLUSHED="hlsBufferFlushed",u.MANIFEST_LOADING="hlsManifestLoading",u.MANIFEST_LOADED="hlsManifestLoaded",u.MANIFEST_PARSED="hlsManifestParsed",u.LEVEL_SWITCHING="hlsLevelSwitching",u.LEVEL_SWITCHED="hlsLevelSwitched",u.LEVEL_LOADING="hlsLevelLoading",u.LEVEL_LOADED="hlsLevelLoaded",u.LEVEL_UPDATED="hlsLevelUpdated",u.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",u.LEVELS_UPDATED="hlsLevelsUpdated",u.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",u.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",u.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",u.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",u.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",u.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUp
1dated",u.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",u.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",u.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",u.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",u.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",u.CUES_PARSED="hlsCuesParsed",u.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",u.INIT_PTS_FOUND="hlsInitPtsFound",u.FRAG_LOADING="hlsFragLoading",u.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",u.FRAG_LOADED="hlsFragLoaded",u.FRAG_DECRYPTED="hlsFragDecrypted",u.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",u.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",u.FRAG_PARSING_METADATA="hlsFragParsingMetadata",u.FRAG_PARSED="hlsFragParsed",u.FRAG_BUFFERED="hlsFragBuffered",u.FRAG_CHANGED="hlsFragChanged",u.FPS_DROP="hlsFpsDrop",u.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",u.ERROR="hlsError",u.DESTROYING="hlsDestroying",u.KEY_LOADING="hlsKeyLoading",u.KEY_LOADED="hlsKeyLoaded",u.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",u.BACK_BUFFER_REACHED="hlsBackBufferReached",u),L=((c={}).NETWORK_ERROR="networkError",c.MEDIA_ERROR="mediaError",c.KEY_SYSTEM_ERROR="keySystemError",c.MUX_ERROR="muxError",c.OTHER_ERROR="otherError",c),R=((f={}).KEY_SYSTEM_NO_KEYS="keySystemNoKeys",f.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",f.KEY_SYSTEM_NO_SESSION="keySystemNoSession",f.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",f.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",f.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",f.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",f.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",f.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",f.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",f.MANIFEST_LOAD_ERROR="manifestLoadError",f.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",f.MANIFEST_PARSING_ERROR="manifestParsingError",f.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",f.LEVEL_EMPTY_ERROR="levelEmptyError",f.LEVEL_LOAD_ERROR="levelLoadError",f.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",f.LEVEL_PARSING_ERROR="levelParsingError",f.LEVEL_SWITCH_ERROR="levelSwitchError",f.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",f.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",f.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",f.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",f.FRAG_LOAD_ERROR="fragLoadError",f.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",f.FRAG_DECRYPT_ERROR="fragDecryptError",f.FRAG_PARSING_ERROR="fragParsingError",f.FRAG_GAP="fragGap",f.REMUX_ALLOC_ERROR="remuxAllocError",f.KEY_LOAD_ERROR="keyLoadError",f.KEY_LOAD_TIMEOUT="keyLoadTimeOut",f.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",f.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",f.BUFFER_APPEND_ERROR="bufferAppendError",f.BUFFER_APPENDING_ERROR="bufferAppendingError",f.BUFFER_STALLED_ERROR="bufferStalledError",f.BUFFER_FULL_ERROR="bufferFullError",f.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",f.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",f.INTERNAL_EXCEPTION="internalException",f.INTERNAL_ABORTED="aborted",f.UNKNOWN="unknown",f),A=function(){},b={trace:A,debug:A,log:A,warn:A,info:A,error:A},D=b,k=D,I=/^(\d+)x(\d+)$/,C=/(.+?)=(".*?"|.*?)(?:,|$)/g;class _{constructor(e){for(const t in"string"==typeof e&&(e=_.parseAttrList(e)),e)e.hasOwnProperty(t)&&("X-"===t.substring(0,2)&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(t)),this[t]=e[t])}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(!this[e])return null;{let t=(this[e]||"0x").slice(2),i=new Uint8Array((t=(1&t.length?"0":"")+t).length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+2),16);return i}}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return"YES"===this[e]}decimalResolution(e){let t=I.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,i={};for(C.lastIndex=0;null!==(t=C.exec(e));){let e=t[2];0===e.indexOf('"')&&e.lastIndexOf('"')===e.length-1&&(e=e.slice(1,-1)),i[t[1].trim()]=e}return i}}class w{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){k.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=E(new _({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=new Date(this.attr["END-DATE"]);v(e.getTime())&&(this._endDate=e)}}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;let e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if(v(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&v(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class x{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var P="audio",F="video",M="audiovideo";class O{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[P]:null,[F]:null,[M]:null},this.baseurl=e}setByteRange(e,t){let i=e.split("@",2),r=[];1===i.length?r[0]=t?t.byteRangeEndOffset:0:r[0]=parseInt(i[1]),r[1]=parseInt(i[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=p.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class N extends O{constructor(e,t){super(t),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 x,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=e}get decryptdata(){let{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){let e=this.levelkeys.identity;if(e)this._decryptdata=e.getDecryptData(this.sn);else{let e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime||!v(this.programDateTime))return null;let e=v(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;
1if(this.levelkeys){let e=Object.keys(this.levelkeys),t=e.length;if(t>1||1===t&&this.levelkeys[e[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){let t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,r,s,a=!1){let{elementaryStreams:n}=this,l=n[e];if(!l){n[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:s,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,s)}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[P]=null,e[F]=null,e[M]=null}}class U extends O{constructor(e,t,i,r,s){super(i),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 x,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}class B{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.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=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&v(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}
1get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.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 e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function $(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function G(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}var K="org.w3.clearkey",H="com.apple.fps",V="com.microsoft.playready",W="com.widevine.alpha",Y="org.w3.clearkey",q="com.apple.streamingkeydelivery",j="com.microsoft.playready",X="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function z(e){switch(e){case q:return H;case j:return V;case X:return W;case Y:return K}}var Q="edef8ba979d64acea3c827dcd51d21ed";function J(e){switch(e){case H:return q;case V:return j;case W:return X;case K:return Y}}function Z(e){let{drmSystems:t,widevineLicenseUrl:i}=e,r=t?[H,W,V,K].filter(e=>!!t[e]):[];return!r[W]&&i&&r.push(W),r}let ee="u">typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function et(e,t,i){return Uint8Array.prototype.slice?e.slice(t,i):new Uint8Array(Array.prototype.slice.call(e,t,i))}let ei=(e,t)=>t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128||!1,er=(e,t)=>t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128||!1,es=(e,t)=>{let i=t,r=0;for(;ei(e,t);)r+=10,r+=ea(e,t+6),er(e,t+10)&&(r+=10),t+=r;if(r>0)return e.subarray(i,i+r)},ea=(e,t)=>(127&e[t])<<21|(127&e[t+1])<<14|(127&e[t+2])<<7|127&e[t+3],en=(e,t)=>ei(e,t)&&ea(e,t+6)+10<=e.length-t,el=e=>e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,eo=e=>{let t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=ea(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}},eh=e=>{let t=0,i=[];for(;ei(e,t);){let r=ea(e,t+6),s=(t+=10)+r;for(;t+8<s;){let r=eo(e.subarray(t)),s=ed(r);s&&i.push(s),t+=r.size+10}er(e,t)&&(t+=10)}return i},ed=e=>"PRIV"===e.type?eu(e):"W"===e.type[0]?ef(e):ec(e),eu=e=>{if(e.size<2)return;let t=em(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}},ec=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1,i=em(e.data.subarray(t),!0);t+=i.length+1;let r=em(e.data.subarray(t));return{key:e.type,info:i,data:r}}let t=em(e.data.subarray(1));return{key:e.type,data:t}},ef=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1,i=em(e.data.subarray(t),!0);t+=i.length+1;let r=em(e.data.subarray(t));return{key:e.type,info:i,data:r}}let t=em(e.data);return{key:e.type,data:t}},eg=e=>{if(8===e.data.byteLength){let t=new Uint8Array(e.data),i=1&t[3],r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}},em=(e,t=!1)=>{let i,s,a=(r||void 0===self.TextDecoder||(r=new self.TextDecoder("utf-8")),r);if(a){let i=a.decode(e);if(t){let e=i.indexOf("\0");return -1!==e?i.substring(0,e):i}return i.replace(/\0/g,"")}let n=e.length,l="",o=0;for(;o<n&&(0!==(i=e[o++])||!t);)if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(i);break;case 12:case 13:l+=String.fromCharCode((31&i)<<6|63&(s=e[o++]));break;case 14:l+=String.fromCharCode((15&i)<<12|(63&(s=e[o++]))<<6|63&e[o++])}return l},ep=function(e){let t="";for(let i=0;i<e.length;i++){let r=e[i].toString(16);r.length<2&&(r="0"+r),t+=r}return t},ey=[].push,eT={video:1,audio:2,id3:3,text:4};function eE(e){return String.fromCharCode.apply(null,e)}function ev(e,t){let i=e[t]<<8|e[t+1];return i<0?65536+i:i}function eS(e,t){let i=eL(e,t);return i<0?0x100000000+i:i}function eL(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function eR(e,t,i){e[t]=i>>24,e[t+1]=i>>16&255,e[t+2]=i>>8&255,e[t+3]=255&i}function eA(e,t){let i=[];if(!t.length)return i;let r=e.byteLength;for(let s=0;s<r;){let a=eS(e,s),n=eE(e.subarray(s+4,s+8)),l=a>1?s+a:r;if(n===t[0])if(1===t.length)i.push(e.subarray(s+8,l));else{let r=eA(e.subarray(s+8,l),t.slice(1));r.length&&ey.apply(i,r)}s=l}return i}function eb(e){let t=[],i=eA(e,["moov","trak"]);for(let e=0;e<i.length;e++){let r=i[e],s=eA(r,["tkhd"])[0];if(s){let e=s[0],i=0===e?12:20,a=eS(s,i),n=eA(r,["mdia","mdhd"])[0];if(n){i=0===(e=n[0])?12:20;let s=eS(n,i),l=eA(r,["mdia","hdlr"])[0];if(l){let e={soun:P,vide:F}[eE(l.subarray(8,12))];if(e){let i,n=eA(r,["mdia","minf","stbl","stsd"])[0];n&&(i=eE(n.subarray(12,16))),t[a]={timescale:s,type:e},t[e]={timescale:s,id:a,codec:i}}}}}}
1return eA(e,["moov","mvex","trex"]).forEach(e=>{let i=t[eS(e,4)];i&&(i.default={duration:eS(e,12),flags:eS(e,20)})}),t}function eD(e){let t=eA(e,["schm"])[0];if(t){let i=eE(t.subarray(4,8));if("cbcs"===i||"cenc"===i)return eA(e,["schi","tenc"])[0]}return k.error("[eme] missing 'schm' box"),null}function ek(e,t){let i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function eI(e,t){let i=[],r=t.samples,s=t.timescale,a=t.id,n=!1;return eA(r,["moof"]).map(l=>{let o=l.byteOffset-8;eA(l,["traf"]).map(l=>{let h=eA(l,["tfdt"]).map(e=>{let t=e[0],i=eS(e,4);return 1===t&&(i*=0x100000000,i+=eS(e,8)),i/s})[0];return void 0!==h&&(e=h),eA(l,["tfhd"]).map(h=>{let d=eS(h,4),u=0xffffff&eS(h,0),c=0,f=0,g=8;d===a&&((1&u)!=0&&(g+=8),(2&u)!=0&&(g+=4),(8&u)!=0&&(c=eS(h,g),g+=4),(16&u)!=0&&(f=eS(h,g),g+=4),(32&u)!=0&&(g+=4),"video"===t.type&&(n=function(e){if(!e)return!1;let t=e.indexOf("."),i=t<0?e:e.substring(0,t);return"hvc1"===i||"hev1"===i||"dvh1"===i||"dvhe"===i}(t.codec)),eA(l,["trun"]).map(a=>{let l=a[0],h=0xffffff&eS(a,0),d=0,u=(256&h)!=0,g=0,m=(512&h)!=0,p=0,y=(1024&h)!=0,T=(2048&h)!=0,E=0,v=eS(a,4),S=8;(1&h)!=0&&(d=eS(a,S),S+=4),(4&h)!=0&&(S+=4);let L=d+o;for(let o=0;o<v;o++){if(u?(g=eS(a,S),S+=4):g=c,m?(p=eS(a,S),S+=4):p=f,y&&(S+=4),T&&(E=0===l?eS(a,S):eL(a,S),S+=4),t.type===F){let t=0;for(;t<p;){let a=eS(r,L);L+=4,function(e,t){if(!e)return 6==(31&t);{let e=t>>1&63;return 39===e||40===e}}(n,r[L])&&eC(r.subarray(L,L+a),n?2:1,e+E/s,i),L+=a,t+=a+4}}e+=g/s}}))})})}),i}function eC(e,t,i,r){let s,a=e_(e);s=0+t;let n=0,l=0,o=!1,h=0;for(;s<a.length;){n=0;do{if(s>=a.length)break;n+=h=a[s++]}while(255===h);l=0;do{if(s>=a.length)break;l+=h=a[s++]}while(255===h);let e=a.length-s;if(!o&&4===n&&s<a.length){if(o=!0,181===a[s++]){let e=ev(a,s);if(s+=2,49===e){let e=eS(a,s);if(s+=4,0x47413934===e){let e=a[s++];if(3===e){let t=a[s++],l=31&t,o=64&t,h=o?2+3*l:0,d=new Uint8Array(h);if(o){d[0]=t;for(let e=1;e<h;e++)d[e]=a[s++]}r.push({type:e,payloadType:n,pts:i,bytes:d})}}}}}else if(5===n&&l<e){if(o=!0,l>16){let e=[];for(let t=0;t<16;t++){let i=a[s++].toString(16);e.push(1==i.length?"0"+i:i),(3===t||5===t||7===t||9===t)&&e.push("-")}let t=l-16,o=new Uint8Array(t);for(let e=0;e<t;e++)o[e]=a[s++];r.push({payloadType:n,pts:i,uuid:e.join(""),userData:em(o),userDataBytes:o})}}else if(l<e)s+=l;else if(l>e)break}}function e_(e){let t=e.byteLength,i=[],r=1;for(;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return e;let s=t-i.length,a=new Uint8Array(s),n=0;for(r=0;r<s;n++,r++)n===i[0]&&(n++,i.shift()),a[r]=e[n];return a}let ew={};class ex{static clearKeyUriToKeyIdMap(){ew={}}constructor(e,t,i,r=[1],s=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=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&"AES-128"!==e}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 q:case X:case j:case Y:return -1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof e&&("AES-128"!==this.method||this.iv||k.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);let t=function(e){let t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(e);return new ex(this.method,this.uri,"identity",this.keyFormatVersions,t)}let t=function(e){let t=e.split(":"),i=null;if("data"===t[0]&&2===t.length){let e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){let t="base64"===r[0],s=r[1];if(t)e.splice(-1,1),i=$(s);else{let e,t;e=G(s).subarray(0,16),(t=new Uint8Array(16)).set(e,16-e.length),i=t}}}return i}(this.uri);if(t)switch(this.keyFormat){case X:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case j:{let e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);
1this.pssh=function(e,t){let i,r;if(16!==e.byteLength)throw RangeError("Invalid system id");i=new Uint8Array,r=new Uint8Array;let s=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(s.buffer).setUint32(0,t.byteLength,!1),function(e,...t){let i=t.length,r=8,s=i;for(;s--;)r+=t[s].byteLength;let a=new Uint8Array(r);for(a[0]=r>>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=255&r,a.set(e,4),s=0,r=8;s<i;s++)a.set(t[s],r),r+=t[s].byteLength;return a}([112,115,115,104],new Uint8Array([0,0,0,0]),e,r,i,s,t||new Uint8Array)}(e,t);let i=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=String.fromCharCode.apply(null,Array.from(i)),s=r.substring(r.indexOf("<"),r.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){let e=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(e){let t,i=$(e).subarray(0,16);(t=function(e,t,i){let r=e[t];e[t]=e[i],e[i]=r})(i,0,3),t(i,1,2),t(i,4,5),t(i,6,7),this.keyId=i}}break}default:{let e=t.subarray(0,16);if(16!==e.length){let t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e}}if(!this.keyId||16!==this.keyId.byteLength){let e=ew[this.uri];if(!e){let t=Object.keys(ew).length%Number.MAX_SAFE_INTEGER;new DataView((e=new Uint8Array(16)).buffer,12,4).setUint32(0,t),ew[this.uri]=e}this.keyId=e}return this}}let eP=/\{\$([a-zA-Z0-9-_]+)\}/g;function eF(e,t,i){if(null!==e.variableList||e.hasVariableRefs)for(let r=i.length;r--;){let s=i[r],a=t[s];a&&(t[s]=eM(e,a))}}function eM(e,t){if(null!==e.variableList||e.hasVariableRefs){let i=e.variableList;return t.replace(eP,t=>{let r=t.substring(2,t.length-1),s=null==i?void 0:i[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):s})}return t}function eO(e,t,i){let r,s,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{let e=new self.URL(i).searchParams;if(e.has(r))s=e.get(r);else throw Error(`"${r}" does not match any query parameter in URI: "${i}"`)}catch(t){e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,s=t.VALUE;r in a?e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):a[r]=s||""}function eN(){if("u">typeof self)return self.MediaSource||self.WebKitMediaSource}let eU={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}},eB=eN();function e$(e,t){var i;return null!=(i=null==eB?void 0:eB.isTypeSupported(`${t||"video"}/mp4;codecs="${e}"`))&&i}let eG=/#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,eK=/#EXT-X-MEDIA:(.*)/g,eH=/^#EXT(?:INF|-X-TARGETDURATION):/m,eV=RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),eW=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 eY{static findGroup(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r.id===t)return r}}static convertAVC1ToAVCOTI(e){let t=e.split(".");if(t.length>2){let e=t.shift()+".";return e+=parseInt(t.shift()).toString(16),e+=("000"+parseInt(t.shift()).toString(16)).slice(-4)}return e}static resolve(e,t){return p.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return eH.test(e)}static parseMasterPlaylist(e,t){var i;let r,s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:eP.test(e)},a=[];for(eG.lastIndex=0;null!=(r=eG.exec(e));)if(r[1]){let e=new _(r[1]);eF(s,e,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);let n=eM(s,r[2]),l={attrs:e,bitrate:e.decimalInteger("AVERAGE-BANDWIDTH")||e.decimalInteger("BANDWIDTH"),name:e.NAME,url:eY.resolve(n,t)},o=e.decimalResolution("RESOLUTION");o&&(l.width=o.width,l.height=o.height),function(e,t){["video","audio","text"].forEach(i=>
1{let r=e.filter(e=>{let t;return!!(t=eU[i])&&!0===t[e.slice(0,4)]});if(r.length){let s=r.filter(e=>0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0));t[`${i}Codec`]=s.length>0?s[0]:r[0],e=e.filter(e=>-1===r.indexOf(e))}}),t.unknownCodecs=e}((e.CODECS||"").split(/[ ,]+/).filter(e=>e),l),l.videoCodec&&-1!==l.videoCodec.indexOf("avc1")&&(l.videoCodec=eY.convertAVC1ToAVCOTI(l.videoCodec)),null!=(i=l.unknownCodecs)&&i.length||a.push(l),s.levels.push(l)}else if(r[3]){let e=r[3],i=r[4];switch(e){case"SESSION-DATA":{let e=new _(i);eF(s,e,["DATA-ID","LANGUAGE","VALUE","URI"]);let t=e["DATA-ID"];t&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[t]=e);break}case"SESSION-KEY":{let e=eq(i,t,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):k.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":{let e=new _(i);eF(s,e,["NAME","VALUE","QUERYPARAM"]),eO(s,e,t)}break;case"CONTENT-STEERING":{let e=new _(i);eF(s,e,["SERVER-URI","PATHWAY-ID"]),s.contentSteering={uri:eY.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=ej(i)}}let n=a.length>0&&a.length<s.levels.length;return s.levels=n?a:s.levels,0===s.levels.length&&(s.playlistParsingError=Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,i){let r,s={},a=i.levels,n={AUDIO:a.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:a.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(eK.lastIndex=0;null!==(r=eK.exec(e));){let e=new _(r[1]),a=e.TYPE;if(a){let r=n[a],o=s[a]||[];s[a]=o,eF(i,e,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);let h={attrs:e,bitrate:0,id:l++,groupId:e["GROUP-ID"]||"",instreamId:e["INSTREAM-ID"],name:e.NAME||e.LANGUAGE||"",type:a,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:e.LANGUAGE,url:e.URI?eY.resolve(e.URI,t):""};if(null!=r&&r.length){let e=eY.findGroup(r,h.groupId)||r[0];eX(h,e,"audioCodec"),eX(h,e,"textCodec")}o.push(h)}}return s}static parseLevelPlaylist(e,t,i,r,s,a){let n,l,o,h=new B(t),d=h.fragments,u=null,c=0,f=0,g=0,m=0,p=null,y=new N(r,t),T=-1,S=!1;for(eV.lastIndex=0,h.m3u8=e,h.hasVariableRefs=eP.test(e);null!==(n=eV.exec(e));){S&&(S=!1,(y=new N(r,t)).start=g,y.sn=c,y.cc=m,y.level=i,u&&(y.initSegment=u,y.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null));let e=n[1];if(e){y.duration=parseFloat(e);let t=(" "+n[2]).slice(1);y.title=t||null,y.tagList.push(t?["INF",e,t]:["INF",e])}else if(n[3]){if(v(y.duration)){y.start=g,o&&eJ(y,o,h),y.sn=c,y.level=i,y.cc=m,y.urlId=s,d.push(y);let e=(" "+n[3]).slice(1);y.relurl=eM(h,e),ez(y,p),p=y,g+=y.duration,c++,f=0,S=!0}}else if(n[4]){let e=(" "+n[4]).slice(1);p?y.setByteRange(e,p):y.setByteRange(e)}else if(n[5])y.rawProgramDateTime=(" "+n[5]).slice(1),y.tagList.push(["PROGRAM-DATE-TIME",y.rawProgramDateTime]),-1===T&&(T=d.length);else{if(!(n=n[0].match(eW))){k.warn("No matches on slow regex match for level playlist!");continue}for(l=1;l<n.length&&void 0===n[l];l++);let e=(" "+n[l]).slice(1),s=(" "+n[l+1]).slice(1),g=n[l+2]?(" "+n[l+2]).slice(1):"";switch(e){case"PLAYLIST-TYPE":h.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":c=h.startSN=parseInt(s);break;case"SKIP":{let e=new _(s);eF(h,e,["RECENTLY-REMOVED-DATERANGES"]);let t=e.decimalInteger("SKIPPED-SEGMENTS");if(v(t)){h.skippedSegments=t;for(let e=t;e--;)d.unshift(null);c+=t}let i=e.enumeratedString("RECENTLY-REMOVED-DATERANGES");i&&(h.recentlyRemovedDateranges=i.split(" "));break}case"TARGETDURATION":h.targetduration=Math.max(parseInt(s),1);break;case"VERSION":h.version=parseInt(s);break;case"EXTM3U":break;case"ENDLIST":h.live=!1;break;case"#":(s||g)&&y.tagList.push(g?[s,g]:[s]);break;case"DISCONTINUITY":m++,y.tagList.push(["DIS"]);break;case"GAP":y.gap=!0,y.tagList.push([e]);break;case"BITRATE":y.tagList.push([e,s]);break;case"DATERANGE":{let e=new _(s);eF(h,e,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),eF(h,e,e.clientAttrs);let t=new w(e,h.dateRanges[e.ID]);t.isValid||h.skippedSegments?h.dateRanges[t.id]=t:k.warn(`Ignoring invalid DATERANGE tag: "${s}"`),y.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{let e=new _(s);eF(h,e,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in e?function(e,t,i){let r=t.IMPORT;if(i&&r in i){let t=e.variableList;t||(e.variableList=t={}),t[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}(h,e,a):eO(h,e,t)}break;case"DISCONTINUITY-SEQUENCE":m=parseInt(s);break;case"KEY":{let e=eq(s,t,h);
1if(e.isSupported()){if("NONE"===e.method){o=void 0;break}o||(o={}),o[e.keyFormat]&&(o=E({},o)),o[e.keyFormat]=e}else k.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":h.startTimeOffset=ej(s);break;case"MAP":{let e=new _(s);if(eF(h,e,["BYTERANGE","URI"]),y.duration){let s=new N(r,t);eQ(s,e,i,o),u=s,y.initSegment=u,u.rawProgramDateTime&&!y.rawProgramDateTime&&(y.rawProgramDateTime=u.rawProgramDateTime)}else eQ(y,e,i,o),u=y,S=!0;break}case"SERVER-CONTROL":{let e=new _(s);h.canBlockReload=e.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=e.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&e.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=e.optionalFloat("PART-HOLD-BACK",0),h.holdBack=e.optionalFloat("HOLD-BACK",0);break}case"PART-INF":h.partTarget=new _(s).decimalFloatingPoint("PART-TARGET");break;case"PART":{let e=h.partList;e||(e=h.partList=[]);let i=f>0?e[e.length-1]:void 0,r=f++,a=new _(s);eF(h,a,["BYTERANGE","URI"]);let n=new U(a,y,t,r,i);e.push(n),y.duration+=n.duration;break}case"PRELOAD-HINT":{let e=new _(s);eF(h,e,["URI"]),h.preloadHint=e;break}case"RENDITION-REPORT":{let e=new _(s);eF(h,e,["URI"]),h.renditionReports=h.renditionReports||[],h.renditionReports.push(e);break}default:k.warn(`line parsed but not handled: ${n}`)}}}p&&!p.relurl?(d.pop(),g-=p.duration,h.partList&&(h.fragmentHint=p)):h.partList&&(ez(y,p),y.cc=m,h.fragmentHint=y,o&&eJ(y,o,h));let L=d.length,R=d[0],A=d[L-1];if((g+=h.skippedSegments*h.targetduration)>0&&L&&A){h.averagetargetduration=g/L;let e=A.sn;h.endSN="initSegment"!==e?e:0,h.live||(A.endList=!0),R&&(h.startCC=R.cc)}else h.endSN=0,h.startCC=0;return h.fragmentHint&&(g+=h.fragmentHint.duration),h.totalduration=g,h.endCC=m,T>0&&function(e,t){let i=e[t];for(let r=t;r--;){let t=e[r];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(d,T),h}}function eq(e,t,i){var r,s;let a=new _(e);eF(i,a,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);let n=null!=(r=a.METHOD)?r:"",l=a.URI,o=a.hexadecimalInteger("IV"),h=a.KEYFORMATVERSIONS,d=null!=(s=a.KEYFORMAT)?s:"identity";return l&&a.IV&&!o&&k.error(`Invalid IV: ${a.IV}`),new ex(n,l?eY.resolve(l,t):"",d,(h||"1").split("/").map(Number).filter(Number.isFinite),o)}function ej(e){let t=new _(e).decimalFloatingPoint("TIME-OFFSET");return v(t)?t:null}function eX(e,t,i){let r=t[i];r&&(e[i]=r)}function ez(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),v(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function eQ(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function eJ(e,t,i){e.levelkeys=t;let{encryptedFragments:r}=i;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(e=>t[e].isCommonEncryption)&&r.push(e)}var eZ="manifest",e0="level",e1="audioTrack",e2="subtitleTrack",e4="main",e3="audio",e5="subtitle";function e8(e){let{type:t}=e;switch(t){case e1:return e3;case e2:return e5;default:return e4}}function e6(e,t){let i=e.url;return(void 0===i||0===i.indexOf("data:"))&&(i=t.url),i}class e9{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.LEVEL_LOADING,this.onLevelLoading,this),e.on(S.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(S.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){let{hls:e}=this;e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.LEVEL_LOADING,this.onLevelLoading,this),e.off(S.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(S.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,r=t.loader,s=new(i||r)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:eZ,url:i,deliveryDirectives:null})}onLevelLoading(e,t){let{id:i,level:r,url:s,deliveryDirectives:a}=t;this.load({id:i,level:r,responseType:"text",type:e0,url:s,deliveryDirectives:a})}onAudioTrackLoading(e,t){let{id:i,groupId:r,url:s,deliveryDirectives:a}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:e1,url:s,deliveryDirectives:a})}onSubtitleTrackLoading(e,t){let{id:i,groupId:r,url:s,deliveryDirectives:a}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:e2,url:s,deliveryDirectives:a})}load(e){var t;let i,r=this.hls.config,s=this.getInternalLoader(e);if(s){let t=s.context;if(t&&t.url===e.url)return void k.trace("[playlist-loader]: playlist request ongoing");k.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(i=e.type===eZ?r.manifestLoadPolicy.default:E({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),null!=(t=e.deliveryDirectives)&&t.part){let t;if(e.type===e0&&null!==e.level?t=this.hls.levels[e.level].details:e.type===e1&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===e2&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,r=t.targetduration;if(e&&r){let t=1e3*Math.max(3*e,.8*r);i=E({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}let a=i.errorRetry||i.timeoutRetry||{},n={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0};s.load(e,n,{onSuccess:(e,t,i,r)=>{let s=this.getInternalLoader(i);this.resetInternalLoader(i.type);let a=e.data;0!==a.indexOf("#EXTM3U")?this.handleManifestParsingError(e,i,Error("no EXTM3U delimiter"),r||null,t):(t.parsing.start=performance.now(),eY.isMediaPlaylist(a)?this.handleTrackOrLevelPlaylist(e,t,i,r||null,s):this.handleMasterPlaylist(e,t,i,r))},onError:(e,t,i,r)=>{this.handleNetworkError(t,i,!1,e,r)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}})}handleMasterPlaylist(e,t,i,r){let s=this.hls,a=e.data,n=e6(e,i),l=eY.parseMasterPlaylist(a,n);if(l.playlistParsingError)return void this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);let{contentSteering:o,levels:h,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:f}=l;this.variableList=f;let{AUDIO:g=[],SUBTITLES:m,"CLOSED-CAPTIONS":p}=eY.parseMasterPlaylistMedia(a,n,l);g.length&&(g.some(e=>!e.url)||!h[0].audioCodec||h[0].attrs.AUDIO||(k.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new _({}),bitrate:0,url:""}))),s.trigger(S.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:m,captions:p,contentSteering:o,url:n,stats:t,networkDetails:r,sessionData:d,sessionKeys:u,startTimeOffset:c,variableList:f})}handleTrackOrLevelPlaylist(e,t,i,r,s){let a=this.hls,{id:n,level:l,type:o}=i,h=e6(e,i),d=v(n)?n:0,u=v(l)?l:d,c=e8(i),f=eY.parseLevelPlaylist(e.data,h,u,c,d,this.variableList);if(o===eZ){let e={attrs:new _({}),bitrate:0,details:f,name:"",url:h};a.trigger(S.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:h,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,r,s)}handleManifestParsingError(e,t,i,r,s){this.hls.trigger(S.ERROR,{type:L.NETWORK_E
1RROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===eZ,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,i=!1,r,s){let a=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===e0?a+=`: ${e.level} id: ${e.id}`:(e.type===e1||e.type===e2)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let n=Error(a);k.warn(`[playlist-loader]: ${a}`);let l=R.UNKNOWN,o=!1,h=this.getInternalLoader(e);switch(e.type){case eZ:l=i?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,o=!0;break;case e0:l=i?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,o=!1;break;case e1:l=i?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,o=!1;break;case e2:l=i?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,o=!1}h&&this.resetInternalLoader(e.type);let d={type:L.NETWORK_ERROR,details:l,fatal:o,url:e.url,loader:h,context:e,error:n,networkDetails:t,stats:s};r&&(d.response=T({url:(null==t?void 0:t.url)||e.url,data:void 0},r)),this.hls.trigger(S.ERROR,d)}handlePlaylistLoaded(e,t,i,r,s,a){let n=this.hls,{type:l,level:o,id:h,groupId:d,deliveryDirectives:u}=r,c=e6(t,r),f=e8(r),g="number"==typeof r.level&&f===e4?o:void 0;if(!e.fragments.length){let e=Error("No Segments found in Playlist");n.trigger(S.ERROR,{type:L.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:e,reason:e.message,response:t,context:r,level:g,parent:f,networkDetails:s,stats:i});return}e.targetduration||(e.playlistParsingError=Error("Missing Target Duration"));let m=e.playlistParsingError;if(m)return void n.trigger(S.ERROR,{type:L.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:t,context:r,level:g,parent:f,networkDetails:s,stats:i});switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case eZ:case e0:n.trigger(S.LEVEL_LOADED,{details:e,level:g||0,id:h||0,stats:i,networkDetails:s,deliveryDirectives:u});break;case e1:n.trigger(S.AUDIO_TRACK_LOADED,{details:e,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u});break;case e2:n.trigger(S.SUBTITLE_TRACK_LOADED,{details:e,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u})}}}function e7(e,t){let i;try{i=new Event("addtrack")}catch(e){(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function te(e,t){let i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw Error(`addCue is failed for: ${t}`)}catch(i){k.debug(`[texttrack-utils]: ${i}`);try{let i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){k.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function tt(e){let t=e.mode;if("disabled"===t&&(e.mode="hidden"),e.cues)for(let t=e.cues.length;t--;)e.removeCue(e.cues[t]);"disabled"===t&&(e.mode=t)}function ti(e,t,i,r){let s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){let s=function(e,t,i){let r=[],s=function(e,t){if(t<e[0].startTime)return 0;let i=e.length-1;if(t>e[i].endTime)return -1;let r=0,s=i;for(;r<=s;){let a=Math.floor((s+r)/2);if(t<e[a].startTime)s=a-1;else{if(!(t>e[a].startTime)||!(r<i))return a;r=a+1}}return e[r].startTime-t<t-e[s].startTime?r:s}(e,t);if(s>-1)for(let a=s,n=e.length;a<n;a++){let s=e[a];if(s.startTime>=t&&s.endTime<=i)r.push(s);else if(s.startTime>i)break}return r}(e.cues,t,i);for(let t=0;t<s.length;t++)(!r||r(s[t]))&&e.removeCue(s[t])}"disabled"===s&&(e.mode=s)}var tr="org.id3",ts="https://aomedia.org/emsg/ID3";function ta(){if("u">typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}let tn=(()=>{let e=ta();try{new e(0,1/0,"")}catch(e){return Number.MAX_VALUE}return 1/0})();function tl(e,t){return e.getTime()/1e3-t}class to{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){let{hls:e}=this;
1e.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(S.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(S.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){let{hls:e}=this;e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(S.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(S.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(tt(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let i=e[t];if("metadata"===i.kind&&"id3"===i.label)return e7(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;let{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:r}}}=this;if(!i&&!r)return;let{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=ta();for(let e=0;e<s.length;e++){let t=s[e].type;if(t===ts&&!i||!r)continue;let n=eh(s[e].data);if(n){let i=s[e].pts,r=i+s[e].duration;r>tn&&(r=tn),r-i<=0&&(r=i+.25);for(let e=0;e<n.length;e++){let s=n[e];if(!el(s)){this.updateId3CueEnds(i,t);let e=new a(i,r,"");e.value=s,t&&(e.type=t),this.id3Track.addCue(e)}}}}}updateId3CueEnds(e,t){var i;let r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(let i=r.length;i--;){let s=r[i];s.type===t&&s.startTime<e&&s.endTime===tn&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:r}){let{id3Track:s,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:n,enableID3MetadataCues:l}}=a;s&&(n||l)&&ti(s,t,i,"audio"===r?e=>e.type===tr&&l:"video"===r?e=>e.type===ts&&n:e=>e.type===tr&&l||e.type===ts&&n)}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;let{dateRangeCuesAppended:i,id3Track:r}=this,{dateRanges:s}=t,a=Object.keys(s);if(r){let e=Object.keys(i).filter(e=>!a.includes(e));for(let t=e.length;t--;){let s=e[t];Object.keys(i[s].cues).forEach(e=>{r.removeCue(i[s].cues[e])}),delete i[s]}}let n=t.fragments[t.fragments.length-1];if(0===a.length||!v(null==n?void 0:n.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));let l=n.programDateTime/1e3-n.start,o=ta();for(let e=0;e<a.length;e++){let t=a[e],r=s[t],n=i[t],d=(null==n?void 0:n.cues)||{},u=(null==n?void 0:n.durationKnown)||!1,c=tl(r.startDate,l),f=tn,g=r.endDate;if(g)f=tl(g,l),u=!0;else if(r.endOnNext&&!u){let e=a.reduce((e,t)=>{let i=s[t];return i.class===r.class&&i.id!==t&&i.startDate>r.startDate&&e.push(i),e},[]).sort((e,t)=>e.startDate.getTime()-t.startDate.getTime())[0];e&&(f=tl(e.startDate,l),u=!0)}let m=Object.keys(r.attr);for(let e=0;e<m.length;e++){var h;let i=m[e];if("ID"===i||"CLASS"===i||"START-DATE"===i||"DURATION"===i||"END-DATE"===i||"END-ON-NEXT"===i)continue;let s=d[i];if(s)u&&!n.durationKnown&&(s.endTime=f);else{let e=r.attr[i];s=new o(c,f,""),("SCTE35-OUT"===i||"SCTE35-IN"===i)&&(h=e,e=Uint8Array.from(h.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer),s.value={key:i,data:e},s.type="com.apple.quicktime.HLS",s.id=t,this.id3Track.addCue(s),d[i]=s}}i[t]={cues:d,dateRange:r,durationKnown:u}}}}class th{constructor(e){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=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){let{config:e,levelDetails:t}=this;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let{levelDetails:e}=this;if(null===e)return null;let{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:s,liveSyncDurationCount:a,lowLatencyMode:n}=this.config,l=this.hls.userConfig,o=n&&i||t;return(l.liveSyncDuration||l.liveSyncDurationCount||0===o)&&(o=void 0!==s?s:a*r),o+Math.min(+this.stallCount,r)}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(null===e||null===t||null===i)return null;let r=i.edge,s=e-t-this.edgeStalled;return Math.min(Math.max(r-i.totalduration,s),r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration))}get drift(){let{levelDetails:e}=this;return null===e?1:e.drift}get edgeStalled(){let{levelDetails:e}=this;if(null===e)return 0;let t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e,levelDetails:t}=this;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}
1registerListeners(){this.hls.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(S.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(S.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(S.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(S.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(S.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(S.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.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(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(i=this.levelDetails)&&i.live&&k.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){let{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;let i=this.computeLatency();if(null===i)return;this._latency=i;let{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s)return;let a=this.targetLatency;if(null===a)return;let n=i-a,l=Math.min(this.maxLatency,a+t.targetduration);t.live&&n<l&&n>.05&&this.forwardBufferLength>1?e.playbackRate=Math.min(Math.min(2,Math.max(1,s)),Math.max(1,Math.round(2/(1+Math.exp(-.75*n-this.edgeStalled))*20)/20)):1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}estimateLiveEdge(){let{levelDetails:e}=this;return null===e?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}let td=["NONE","TYPE-0","TYPE-1",null];class tu{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){let t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class tc{constructor(e){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=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.unknownCodecs=e.unknownCodecs,this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>e).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(e){let t=e%this.url.length;this._urlId!==t&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=t)}get audioGroupId(){var e;return null==(e=this.audioGroupIds)?void 0:e[this.urlId]}get textGroupId(){var e;return null==(e=this.textGroupIds)?void 0:e[this.urlId]}addFallback(e){this.url.push(e.url),this._attrs.push(e.attrs)}}function tf(e,t){let i=t.startPTS;if(v(i)){let r,s=0;t.sn>e.sn?(s=i-e.start,r=e):(s=e.start-i,r=t),r.duration!==s&&(r.duration=s)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration:t.start=Math.max(e.start-t.duration,0)}function tg(e,t,i,r,s,a){let n;r-i<=0&&(k.warn("Fragment should have a positive duration",t),r=i+t.duration,a=s+t.duration);let l=i,o=r,h=t.startPTS,d=t.endPTS;if(v(h)){let e=Math.abs(h-i);v(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,l=Math.max(i,h),i=Math.min(i,h),s=Math.min(s,t.startDTS),o=Math.min(r,d),r=Math.max(r,d),a=Math.max(a,t.endDTS)}let u=i-t.start;0!==t.start&&(t.start=i),t.duration=r-t.start,t.startPTS=i,t.maxStartPTS=l,t.startDTS=s,t.endPTS=r,t.minEndPTS=o,t.endDTS=a;let c=t.sn;if(!e||c<e.startSN||c>e.endSN)return 0;let f=c-e.startSN,g=e.fragments;for(g[f]=t,n=f;n>0;n--)tf(g[n],g[n-1]);for(n=f;n<g.length-1;n++)tf(g[n],g[n+1]);return e.fragmentHint&&tf(g[g.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,u}function tm(e,t){let i=t.startSN+t.skippedSegments-e.startSN,r=e.fragments;i<0||i>=r.length||tp(t,r[i].start)}function tp(e,t){if(t){let i=e.fragments;for(let r=e.skippedSegments;r<i.length;r++)i[r].start+=t;e.fragmentHint&&(e.fragmentHint.start+=t)}}function ty(e,t,i){var r;return null!=e&&e.details?tT(null==(r=e.details)?void 0:r.partList,t,i):null}function tT(e,t,i){if(e)for(let r=e.length;r--;){let s=e[r];if(s.index===i&&s.fragment.sn===t)return s}return null}function tE(e){switch(e.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function tv(e,t){let i=tE(t);return e.default[`${i?"timeout":"error"}Retry`]}function tS(e,t){return Math.min(("linear"===e.backoff?1:Math.pow(2,t))*e.retryDelayMs,e.maxRetryDelayMs)}function tL(e){return T(T({},e),{errorRetry:null,timeoutRetry:null})}function tR(e,t,i,r){var s;return!!e&&t<e.maxNumRetry&&(0===(s=r)&&!1===navigator.onLine||!!s&&(s<400||s>499)||!!i)}let tA=function(e,t){let i=0,r=e.length-1,s=null,a=null;for(;i<=r;){let n=t(a=e[s=(i+r)/2|0]);if(n>0)i=s+1;else{if(!(n<0))return a;r=s-1}}return null};function tb(e,t,i=0,r=0){let s=null;if(e?s=t[e.sn-t[0].sn+1]||null:0===i&&0===t[0].start&&(s=t[0]),s&&0===tD(i,r,s))return s;let a=tA(t,tD.bind(null,i,r));return a&&(a!==e||!s)?a:s}
1function tD(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;let r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}class tk{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=k.log.bind(k,"[info]:"),this.warn=k.warn.bind(k,"[warning]:"),this.error=k.error.bind(k,"[error]:"),this.registerListeners()}registerListeners(){let e=this.hls;e.on(S.ERROR,this.onError,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(S.ERROR,this.onError,this),e.off(S.ERROR,this.onErrorOut,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){this.playlistError=0}stopLoad(){}getVariantLevelIndex(e){return(null==e?void 0:e.type)===e4?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,r,s,a;if(t.fatal)return;let n=this.hls,l=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case R.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap){t.errorAction={action:0,flags:0};return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=2;return;case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{let e=t.parent===e4?t.level:n.loadLevel;t.details===R.LEVEL_EMPTY_ERROR&&null!=(s=t.context)&&null!=(a=s.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:"number"==typeof(null==l?void 0:l.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l.level));return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(l){let e=n.levels[n.loadLevel];e&&(l.type===e1&&l.groupId===e.audioGroupId||l.type===e2&&l.groupId===e.textGroupId)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=2,t.errorAction.flags=1)}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{let e=n.levels[n.loadLevel],i=null==e?void 0:e.attrs["HDCP-LEVEL"];i&&(t.errorAction={action:2,flags:2,hdcpLevel:i})}return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:t.errorAction=this.getLevelSwitchAction(t,null!=(r=t.level)?r:n.loadLevel);return;case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_APPEND_ERROR:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:t.errorAction={action:0,flags:0};return}if(t.type===L.KEY_SYSTEM_ERROR){let e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e);return}}getPlaylistRetryOrSwitchAction(e,t){var i;let r=tv(this.hls.config.playlistLoadPolicy,e),s=this.playlistError++,a=null==(i=e.response)?void 0:i.code;if(tR(r,s,tE(e),a))return{action:5,flags:0,retryConfig:r,retryCount:s};let n=this.getLevelSwitchAction(e,t);return r&&(n.retryConfig=r,n.retryCount=s),n}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:a}=t.config,n=tv(e.details.startsWith("key")?a:s,e),l=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(r){var o;e.details!==R.FRAG_GAP&&r.fragmentError++;let t=null==(o=e.response)?void 0:o.code;if(tR(n,l,tE(e),t))return{action:5,flags:0,retryConfig:n,retryCount:l}}let h=this.getLevelSwitchAction(e,i);return n&&(h.retryConfig=n,h.retryCount=l),h}getLevelSwitchAction(e,t){let i=this.hls;null==t&&(t=i.loadLevel);let r=this.hls.levels[t];if(r&&(r.loadError++,i.autoLevelEnabled)){var s,a;let t=-1,{levels:n,loadLevel:l,minAutoLevel:o,maxAutoLevel:h}=i,d=null==(s=e.frag)?void 0:s.type,{type:u,groupId:c}=null!=(a=e.context)?a:{};for(let i=n.length;i--;){let s=(i+l)%n.length;if(s!==l&&s>=o&&s<=h&&0===n[s].loadError){let i=n[s];if(e.details===R.FRAG_GAP&&e.frag){let t=n[s].details;if(t){let i=tb(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else if(u===e1&&c===i.audioGroupId||u===e2&&c===i.textGroupId)continue;else if(d===e3&&r.audioGroupId===i.audioGroupId||d===e5&&r.textGroupId===i.textGroupId)continue;t=s;break}}if(t>-1&&i.loadLevel!==t)return e.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:t}}return{action:2,flags:1}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case 0:break;case 2:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===R.FRAG_GAP||(t.fatal=!0)}if(t.fatal)return void this.hls.stopLoad()}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let{flags:r,hdcpLevel:s,nextAutoLevel:a}=i;switch(r){case 0:this.switchLevel(e,a);break;case 1:i.resolved||(i.resolved=this.redundantFailover(e));break;case 2:s&&(t.maxHdcpLevel=td[td.indexOf(s)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}i.resolved||this.switchLevel(e,a)}switchLevel(e,t){void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}redundantFailover(e){let{hls:t,penalizedRenditions:i}=this,r=e.parent===e4?e.level:t.loadLevel,s=t.levels[r],a=s.url.length,n=e.frag?e.frag.urlId:s.urlId;s.urlId===n&&(!e.frag||s.details)&&this.penalizeRendition(s,e);for(let l=1;l<a;l++){let o=(n+l)%a,h=i[o];if(!h||function(e,t,i){if(performance.now()-e.lastErrorPerfMs>3e5)return!0;let r=e.details;if(t.details===R.FRAG_GAP&&r&&t.frag){let e=t.frag.start,i=tb(null,r.fragments,e);if(i&&!i.gap)return!0}if(i&&e.errors.length<i.errors.length){let i=e.errors[e.errors.length-1];if(r&&i.frag&&t.frag&&Math.abs(i.frag.start-t.frag.start)>3*r.targetduration)return!0}return!1}(h,e,i[n]))return this.warn(`Switching to Redundant Stream ${o+1}/${a}: "${s.url[o]}" after ${e.details}
1`),this.playlistError=0,t.levels.forEach(e=>{e.urlId=o}),t.nextLoadLevel=r,!0}return!1}penalizeRendition(e,t){let{penalizedRenditions:i}=this,r=i[e.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};r.lastErrorPerfMs=performance.now(),r.errors.push(t),r.details=e.details,i[e.urlId]=r}}class tI{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=k.log.bind(k,`${t}:`),this.warn=k.warn.bind(k,`${t}:`),this.hls=e}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(e,t){let i=null==t?void 0:t.renditionReports;if(i){let r=-1;for(let s=0;s<i.length;s++){let a,n=i[s];try{a=new self.URL(n.URI,t.url).href}catch(e){k.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){r=s;break}a===e.substring(0,a.length)&&(r=s)}if(-1!==r){let e=i[r],s=parseInt(e["LAST-MSN"])||(null==t?void 0:t.lastPartSn),a=parseInt(e["LAST-PART"])||(null==t?void 0:t.lastPartIndex);if(this.hls.config.lowLatencyMode){let e=Math.min(t.age-t.partTarget,t.targetduration);a>=0&&e>t.partTarget&&(a+=1)}return new tu(s,a>=0?a:void 0,"")}}}loadPlaylist(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return -1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){let{details:r,stats:s}=t,a=self.performance.now(),n=s.loading.first?Math.max(0,a-s.loading.first):0;if(r.advancedDateTime=Date.now()-n,r.live||null!=i&&i.live){let n,l,o;if(r.reloaded(i),i&&this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),i&&r.fragments.length>0&&function(e,t){let i,r=null,s=e.fragments;for(let e=s.length-1;e>=0;e--){let t=s[e].initSegment;if(t){r=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let a=0;if(function(e,t,i){let r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,a=+!!e.fragmentHint+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,n=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let e=s;e<=a;e++){let s=o[n+e],a=l[e];r&&!a&&e<r&&(a=t.fragments[e]=s),s&&a&&i(s,a)}}(e,t,(e,s)=>{e.relurl&&(a=e.cc-s.cc),v(e.startPTS)&&v(e.endPTS)&&(s.start=s.startPTS=e.startPTS,s.startDTS=e.startDTS,s.maxStartPTS=e.maxStartPTS,s.endPTS=e.endPTS,s.endDTS=e.endDTS,s.minEndPTS=e.minEndPTS,s.duration=e.endPTS-e.startPTS,s.duration&&(i=s),t.PTSKnown=t.alignedSliding=!0),s.elementaryStreams=e.elementaryStreams,s.loader=e.loader,s.stats=e.stats,s.urlId=e.urlId,e.initSegment&&(s.initSegment=e.initSegment,r=e.initSegment)}),r&&(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEach(e=>{var t;e.initSegment&&e.initSegment.relurl!==(null==(t=r)?void 0:t.relurl)||(e.initSegment=r)}),t.skippedSegments)if(t.deltaUpdateFailed=t.fragments.some(e=>!e),t.deltaUpdateFailed){k.warn("[level-helper] Previous playlist missing segments ski
1pped in delta playlist");for(let e=t.skippedSegments;e--;)t.fragments.shift();t.startSN=t.fragments[0].sn,t.startCC=t.fragments[0].cc}else{var n,l,o;let i;t.canSkipDateRanges&&(n=e.dateRanges,l=t.dateRanges,o=t.recentlyRemovedDateranges,i=E({},n),o&&o.forEach(e=>{delete i[e]}),Object.keys(l).forEach(e=>{let t=new w(l[e].attr,i[e]);t.isValid?i[e]=t:k.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(l[e].attr)}"`)}),t.dateRanges=i)}let h=t.fragments;if(a){k.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e<h.length;e++)h[e].cc+=a}t.skippedSegments&&(t.startCC=t.fragments[0].cc),function(e,t,i){if(e&&t){let r=0;for(let s=0,a=e.length;s<=a;s++){let a=e[s],n=t[s+r];a&&n&&a.index===n.index&&a.fragment.sn===n.fragment.sn?i(a,n):r--}}}(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),i?tg(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):tm(e,t),h.length&&(t.totalduration=t.edge-h[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let d=t.advancedDateTime;if(t.advanced&&d){let e=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=e),t.driftEndTime=d,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}(i,r),!this.canLoad||!r.live)return;if(r.canBlockReload&&r.endSN&&r.advanced){let e=this.hls.config.lowLatencyMode,s=r.lastPartSn,a=r.endSN,h=r.lastPartIndex,d=s===a;-1!==h?(l=d?a+1:s,o=d?e?0:h:h+1):l=a+1;let u=r.age,c=Math.min(u+r.ageHeader-r.partTarget,1.5*r.targetduration);if(c>0){if(i&&c>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${c} with playlist age: ${r.age}`),c=0;else{let e=Math.floor(c/r.targetduration);l+=e,void 0!==o&&(o+=Math.round(c%r.targetduration/r.partTarget)),this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${c} skip sn ${e} to part ${o}`)}r.tuneInGoal=c}if(n=this.getDeliveryDirectives(r,t.deliveryDirectives,l,o),e||!d)return void this.loadPlaylist(n)}else(r.canBlockReload||r.canSkipUntil)&&(n=this.getDeliveryDirectives(r,t.deliveryDirectives,l,o));let h=this.hls.mainForwardBufferInfo,d=h?h.end-h.len:0,u=(r.edge-d)*1e3,c=function(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){let r=e.fragments;if(r.length&&4*i>t){let e=1e3*r[r.length-1].duration;e<i&&(i=e)}}else i/=2;return Math.round(i)}(r,u);r.updated&&a>this.requestScheduled+c&&(this.requestScheduled=s.loading.start),void 0!==l&&r.canBlockReload?this.requestScheduled=s.loading.first+c-(1e3*r.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+c<a?this.requestScheduled=a:this.requestScheduled-a<=0&&(this.requestScheduled+=c);let f=this.requestScheduled-a;f=Math.max(0,f),this.log(`reload live playlist ${e} in ${Math.round(f)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(n),f)}else this.clearTimer()}getDeliveryDirectives(e,t,i,r){let s=function(e,t){let{canSkipUntil:i,canSkipDateRanges:r,endSN:s}=e;return i&&(void 0!==t?t-s:0)<i?r?"v2":"YES":""}(e,i);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=""),new tu(i,r,s)}checkRetry(e){let t=e.details,i=tE(e),r=e.errorAction,{action:s,retryCount:a=0,retryConfig:n}=r||{},l=!!r&&!!n&&(5===s||!r.resolved&&2===s);if(l){var o;if(this.requestScheduled=-1,a>=n.maxNumRetry)return!1;if(i&&null!=(o=e.context)&&o.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${n.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let e=tS(n,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${a+1}/${n.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return l}}class tC extends tI{constructor(e,t){super(e,"[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=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(S.LEVEL_LOADED,this.onLevelLoaded,this),e.on(S.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(S.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(S.FRAG_LOADED,this.onFragLoaded,this),e.on(S.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(S.LEVEL_LOADED,this.onLevelLoaded,this),e.off(S.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(S.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(S.FRAG_LOADED,this.onFragLoaded,this),e.off(S.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}
1startLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i,r=[],a={};t.levels.forEach(e=>{var t;let n=e.attrs;(null==(t=e.audioCodec)?void 0:t.indexOf("mp4a.40.34"))!==-1&&(s||(s=/chrome|firefox/i.test(navigator.userAgent)),s&&(e.audioCodec=void 0));let{AUDIO:l,CODECS:o,"FRAME-RATE":h,"PATHWAY-ID":d,RESOLUTION:u,SUBTITLES:c}=n,f=`${d||"."}-`,g=`${f}${e.bitrate}-${u}-${h}-${o}`;(i=a[g])?i.addFallback(e):(i=new tc(e),a[g]=i,r.push(i)),t_(i,"audio",l),t_(i,"text",c)}),this.filterAndSortMediaOptions(r,t)}filterAndSortMediaOptions(e,t){let i=[],r=[],s=!1,a=!1,n=!1,l=e.filter(({audioCodec:e,videoCodec:t,width:i,height:r,unknownCodecs:l})=>(s||(s=!!(i&&r)),a||(a=!!t),n||(n=!!e),!(null!=l&&l.length)&&(!e||e$(e,"audio"))&&(!t||e$(t,"video"))));if((s||a)&&n&&(l=l.filter(({videoCodec:e,width:t,height:i})=>!!e||!!(t&&i))),0===l.length)return void Promise.resolve().then(()=>{if(this.hls){let e=Error("no level with compatible codecs found in manifest");this.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}});t.audioTracks&&tw(i=t.audioTracks.filter(e=>!e.audioCodec||e$(e.audioCodec,"audio"))),t.subtitles&&tw(r=t.subtitles);let o=l.slice(0);l.sort((e,t)=>e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"]?(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1:e.bitrate!==t.bitrate?e.bitrate-t.bitrate:e.attrs["FRAME-RATE"]!==t.attrs["FRAME-RATE"]?e.attrs.decimalFloatingPoint("FRAME-RATE")-t.attrs.decimalFloatingPoint("FRAME-RATE"):e.attrs.SCORE!==t.attrs.SCORE?e.attrs.decimalFloatingPoint("SCORE")-t.attrs.decimalFloatingPoint("SCORE"):s&&e.height!==t.height?e.height-t.height:0);let h=o[0];if(this.steering&&(l=this.steering.filterParsedLevels(l)).length!==o.length){for(let e=0;e<o.length;e++)if(o[e].pathwayId===l[0].pathwayId){h=o[e];break}}this._levels=l;for(let e=0;e<l.length;e++)if(l[e]===h){this._firstLevel=e,this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${h.bitrate}`);break}let d=n&&!a,u={levels:l,audioTracks:i,subtitleTracks:r,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:a,altAudio:!d&&i.some(e=>!!e.url)};this.hls.trigger(S.MANIFEST_PARSED,u),(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(e){let t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){let i=Error("invalid level idx"),r=e<0;if(this.hls.trigger(S.ERROR,{type:L.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],n=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&a.details&&r&&s===n)return;this.log(`Switching to level ${e}${n?" with Pathway "+n:""} from level ${i}${s?" with Pathway "+s:""}`);let l=E({},a,{level:e,maxBitrate:a.maxBitrate,attrs:a.attrs,uri:a.uri,urlId:a.urlId});delete l._attrs,delete l._urlId,this.hls.trigger(S.LEVEL_SWITCHING,l);let o=a.details;if(!o||o.live){let e=this.switchParams(a.uri,null==r?void 0:r.details);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0!==this._startLevel)return this._startLevel;{let e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}}set startLevel(e){this._startLevel=e}onError(e,t){!t.fatal&&t.context&&t.context.type===e0&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(void 0!==t&&t.type===e4){let e=this._levels[t.level];void 0!==e&&(e.loadError=0)}}onLevelLoaded(e,t){var i,r;let{level:s,details:a}=t,n=this._levels[s];if(!n){this.warn(`Invalid level index ${s}`),null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0);return}s===this.currentLevelIndex?(0===n.fragmentError&&(n.loadError=0),this.playlistLoaded(s,t,n.details)):null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0)}onAudioTrackSwitched(e,t){let i=this.currentLevel;if(!i)return;let r=this.hls.audioTracks[t.id].groupId;if(i.audioGroupIds&&i.audioGroupId!==r){let e=-1;for(let t=0;t<i.audioGroupIds.length;t++)if(i.audioGroupIds[t]===r){e=t;break}-1!==e&&e!==i.urlId&&(i.urlId=e,this.canLoad&&this.startLoad())}}loadPlaylist(e){super.loadPlaylist();let t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let r=i.urlId,s=i.uri;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}let a=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(null==e?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${a?" Pathway "+a:""} URI ${r+1}/${i.url.length} ${s}`),this.clearTimer(),this.hls.trigger(S.LEVEL_LOADING,{url:s,level:t,id:r,deliveryDirectives:e||null})}}get nextLoadLevel(){return -1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e,t){let i=(e,i)=>i!==t,r=this._levels.filter((r,s)=>s!==e||(r.url.length>1&&void 0!==t?(r.url=r.url.filter(i),r.audioGroupIds&&(r.audioGroupIds=r.audioGroupIds.filter(i)),r.textGroupIds&&(r.textGroupIds=r.textGroupIds.filter(i)),r.urlId=0,!0):(this.steering&&this.steering.removeLevel(r),!1)));this.hls.trigger(S.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){t.forEach((e,t)=>{let{details:i}=e;
1null!=i&&i.fragments&&i.fragments.forEach(e=>{e.level=t})}),this._levels=t}}function t_(e,t,i){i&&("audio"===t?(e.audioGroupIds||(e.audioGroupIds=[]),e.audioGroupIds[e.url.length-1]=i):"text"===t&&(e.textGroupIds||(e.textGroupIds=[]),e.textGroupIds[e.url.length-1]=i))}function tw(e){let t={};e.forEach(e=>{let i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}var tx="NOT_LOADED",tP="APPENDING",tF="PARTIAL";class tM{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(S.BUFFER_APPENDED,this.onBufferAppended,this),e.on(S.FRAG_BUFFERED,this.onFragBuffered,this),e.on(S.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){let{hls:e}=this;e.off(S.BUFFER_APPENDED,this.onBufferAppended,this),e.off(S.FRAG_BUFFERED,this.onFragBuffered,this),e.off(S.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let t=i.length;t--;){let r=i[t];if(!r)break;let s=r.end;if(r.start<=e&&null!==s&&e<=s)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){let{fragments:i}=this,r=Object.keys(i);for(let s=r.length;s--;){let a=i[r[s]];if((null==a?void 0:a.body.type)===t&&a.buffered){let t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,r){this.timeRanges&&(this.timeRanges[e]=t);let s=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(r=>{let a=this.fragments[r];if(!a||s>=a.body.sn)return;if(!a.buffered&&!a.loaded){a.body.type===i&&this.removeFragment(a.body);return}let n=a.range[e];n&&n.time.some(e=>{let i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(a.body),i})})}detectPartialFragments(e){let t=this.timeRanges,{frag:i,part:r}=e;if(!t||"initSegment"===i.sn)return;let s=tN(i),a=this.fragments[s];if(!a||a.buffered&&i.gap)return;let n=!i.relurl;Object.keys(t).forEach(e=>{let s=i.elementaryStreams[e];if(!s)return;let l=t[e],o=n||!0===s.partial;a.range[e]=this.getBufferedTimes(i,r,o,l)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=i.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),tO(a)||this.removeParts(i.sn-1,i.type)):this.removeFragment(a.body)}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter(t=>t.fragment.sn>=e))}fragBuffered(e,t){let i=tN(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,r.buffered=!0)}getBufferedTimes(e,t,i,r){let s={time:[],partial:i},a=e.start,n=e.end,l=e.minEndPTS||n,o=e.maxStartPTS||a;for(let e=0;e<r.length;e++){let t=r.start(e)-this.bufferPadding,i=r.end(e)+this.bufferPadding;if(o>=t&&l<=i){s.time.push({startPTS:Math.max(a,r.start(e)),endPTS:Math.min(n,r.end(e))});break}if(a<i&&n>t)s.partial=!0,s.time.push({startPTS:Math.max(a,r.start(e)),endPTS:Math.min(n,r.end(e))});else if(n<=t)break}return s}getPartialFragment(e){let t,i,r,s=null,a=0,{bufferPadding:n,fragments:l}=this;return Object.keys(l).forEach(o=>{let h=l[o];h&&tO(h)&&(i=h.body.start-n,r=h.body.end+n,e>=i&&e<=r&&a<=(t=Math.min(e-i,r-e))&&(s=h.body,a=t))}),s}isEndListAppended(e){let t=this.endListFragments[e];return void 0!==t&&(t.buffered||tO(t))}getState(e){let t=tN(e),i=this.fragments[t];if(i)if(!i.buffered)return tP;else if(tO(i))return tF;else return"OK";return tx}isTimeBuffered(e,t,i){let r,s;for(let a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,s=i.end(a)+this.bufferPadding,e>=r&&t<=s)return!0;if(t<=r)break}return!1}onFragLoaded(e,t){let{frag:i,part:r}=t;if("initSegment"===i.sn||i.bitrateTest)return;let s=tN(i);this.fragments[s]={body:i,appendedPTS:null,loaded:r?null:t,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:r,timeRanges:s}=t;if("initSegment"===i.sn)return;let a=i.type;if(r){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(r)}
1this.timeRanges=s,Object.keys(s).forEach(e=>{let t=s[e];this.detectEvictedFragments(e,t,a,r)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=tN(e);return!!this.fragments[t]}hasParts(e){var t;return!!(null!=(t=this.activePartLists[e])&&t.length)}removeFragmentsInRange(e,t,i,r,s){(!r||this.hasGaps)&&Object.keys(this.fragments).forEach(a=>{let n=this.fragments[a];if(!n)return;let l=n.body;l.type===i&&(!r||l.gap)&&l.start<t&&l.end>e&&(n.buffered||s)&&this.removeFragment(l)})}removeFragment(e){let t=tN(e);e.stats.loaded=0,e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let t=e.sn;this.activePartLists[e.type]=i.filter(e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function tO(e){var t,i,r;return e.buffered&&(e.body.gap||(null==(t=e.range.video)?void 0:t.partial)||(null==(i=e.range.audio)?void 0:i.partial)||(null==(r=e.range.audiovideo)?void 0:r.partial))}function tN(e){return`${e.type}_${e.level}_${e.urlId}_${e.sn}
1`}class tU{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){let i=e.url;if(!i)return Promise.reject(new tG({type:L.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();let r=this.config,s=r.fLoader,a=r.loader;return new Promise((n,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(e=>"GAP"===e[0]))return void l(t$(e));else e.gap=!1;let o=this.loader=e.loader=s?new s(r):new a(r),h=tB(e),d=tL(r.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:131072};e.stats=o.stats,o.load(h,u,{onSuccess:(t,i,r,s)=>{this.resetLoader(e,o);let a=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),n({frag:e,part:null,payload:a,networkDetails:s})},onError:(t,r,s,a)=>{this.resetLoader(e,o),l(new tG({type:L.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:T({url:i,data:void 0},t),error:Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:a}))},onAbort:(t,i,r)=>{this.resetLoader(e,o),l(new tG({type:L.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,i,r)=>{this.resetLoader(e,o),l(new tG({type:L.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${u.timeout}ms`),networkDetails:r,stats:t}))},onProgress:(i,r,s,a)=>{t&&t({frag:e,part:null,payload:s,networkDetails:a})}})})}loadPart(e,t,i){this.abort();let r=this.config,s=r.fLoader,a=r.loader;return new Promise((n,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void l(t$(e,t));let o=this.loader=e.loader=s?new s(r):new a(r),h=tB(e,t),d=tL(r.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:131072};t.stats=o.stats,o.load(h,u,{onSuccess:(r,s,a,l)=>{this.resetLoader(e,o),this.updateStatsFromPart(e,t);let h={frag:e,part:t,payload:r.data,networkDetails:l};i(h),n(h)},onError:(i,r,s,a)=>{this.resetLoader(e,o),l(new tG({type:L.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:T({url:h.url,data:void 0},i),error:Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:s,stats:a}))},onAbort:(i,r,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,o),l(new tG({type:L.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(e,o),l(new tG({type:L.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${u.timeout}ms`),networkDetails:s,stats:i}))}})})}updateStatsFromPart(e,t){let i=e.stats,r=t.stats,s=r.total;if(i.loaded+=r.loaded,s){let r=Math.round(e.duration/t.duration),a=Math.min(Math.round(i.loaded/s),r),n=(r-a)*Math.round(i.loaded/a);i.total=i.loaded+n}else i.total=Math.max(i.loaded,i.total);let a=i.loading,n=r.loading;a.start?a.first+=n.first-n.start:(a.start=n.start,a.first=n.first),a.end=n.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function tB(e,t=null){let i=t||e,r={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},s=i.byteRangeStartOffset,a=i.byteRangeEndOffset;if(v(s)&&v(a)){var n;let t=s,i=a;if("initSegment"===e.sn&&(null==(n=e.decryptdata)?void 0:n.method)==="AES-128"){let e=a-s;e%16&&(i=a+(16-e%16)),0!==s&&(r.resetIV=!0,t=s-16)}r.rangeStart=t,r.rangeEnd=i}return r}function t$(e,t){let i=Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:L.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new tG(r)}class tG extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class tK{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let t in this.keyUriToKeyInfo){let i=this.keyUriToKeyInfo[t].loader;if(i){if(e&&e!==i.context.frag.type)return;i.abort()}}}detach(){for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){for(let e in this.detach(),this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=R.KEY_LOAD_ERROR,i,r,s){return new tG({type:L.NETWORK_E
1RROR,details:t,fatal:!1,frag:e,response:s,error:i,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){let{sn:i,cc:r}=e;for(let e=0;e<t.length;e++){let s=t[e];if(r<=s.cc&&("initSegment"===i||"initSegment"===s.sn||i<s.sn)){this.emeController.selectKeySystemFormat(s).then(e=>{s.setKeyFormat(e)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r,s;t&&e.setKeyFormat(t);let a=e.decryptdata;if(!a){let i=Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,i))}let n=a.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,Error(`Invalid key URI: "${n}"`)));let l=this.keyUriToKeyInfo[n];if(null!=(i=l)&&i.decryptdata.key)return a.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(null!=(r=l)&&r.keyLoadPromise)switch(null==(s=l.mediaKeySessionContext)?void 0:s.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return l.keyLoadPromise.then(t=>(a.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:l}))}switch(l=this.keyUriToKeyInfo[n]={decryptdata:a,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},a.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":if("identity"===a.keyFormat)return this.loadKeyHTTP(l,e);return this.loadKeyEME(l,e);case"AES-128":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${a.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){let t=this.emeController.loadKey(i);if(t)return(e.keyLoadPromise=t.then(t=>(e.mediaKeySessionContext=t,i))).catch(t=>{throw e.keyLoadPromise=null,t})}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,r=new i.loader(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((s,a)=>{let n={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=i.keyLoadPolicy.default,o={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(n,o,{onSuccess:(e,t,i,r)=>{let{frag:n,keyInfo:l,url:o}=i;if(!n.decryptdata||l!==this.keyUriToKeyInfo[o])return a(this.createKeyLoadError(n,R.KEY_LOAD_ERROR,Error("after key load, decryptdata unset or changed"),r));l.decryptdata.key=n.decryptdata.key=new Uint8Array(e.data),n.keyLoader=null,l.loader=null,s({frag:n,keyInfo:l})},onError:(e,i,r,s)=>{this.resetLoader(i),a(this.createKeyLoadError(t,R.KEY_LOAD_ERROR,Error(`HTTP Error ${e.code} loading key ${e.text}`),r,T({url:n.url,data:void 0},e)))},onTimeout:(e,i,r)=>{this.resetLoader(i),a(this.createKeyLoadError(t,R.KEY_LOAD_TIMEOUT,Error("key loading timed out"),r))},onAbort:(e,i,r)=>{this.resetLoader(i),a(this.createKeyLoadError(t,R.INTERNAL_ABORTED,Error("key loading aborted"),r))}})})}resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,s=i.loader;t.keyLoader===s&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[r],s&&s.destroy()}}class tH{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(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}let tV={length:0,start:()=>0,end:()=>0};class tW{static isBuffered(e,t){try{if(e){let i=tW.getBuffered(e);for(let e=0;e<i.length;e++)if(t>=i.start(e)&&t<=i.end(e))return!0}}catch(e){}return!1}static bufferInfo(e,t,i){try{if(e){let r,s=tW.getBuffered(e),a=[];for(r=0;r<s.length;r++)a.push({start:s.start(r),end:s.end(r)});return this.bufferedInfo(a,t,i)}}catch(e){}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,i){let r;t=Math.max(0,t),e.sort(function(e,t){let i=e.start-t.start;return i||t.end-e.end});let s=[];if(i)for(let t=0;t<e.length;t++){let r=s.length;if(r){let a=s[r-1].end;e[t].start-a<i?e[t].end>a&&(s[r-1].end=e[t].end):s.push(e[t])}else s.push(e[t])}else s=e;let a=0,n=t,l=t;for(let e=0;e<s.length;e++){let o=s[e].start,h=s[e].end;if(t+i>=o&&t<h)n=o,a=(l=h)-t;else if(t+i<o){r=o;break}}return{len:a,start:n||0,end:l||0,nextStart:r}}static getBuffered(e){try{return e.buffered}catch(e){return k.log("failed to get media.buffered",e),tV}}}class tY{constructor(e,t,i,r=0,s=-1,a=!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=tq(),this.buffering={audio:tq(),video:tq(),audiovideo:tq()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=s,this.partial=a}}function tq(){return{start:0,executeStart:0,executeEnd:0,end:0}}function tj(e,t){let i=null;for(let r=0,s=e.length;r<s;r++){let s=e[r];if(s&&s.cc===t){i=s;break}}return i}function tX(e,t){if(e){let i=e.start+t;e.start=e.startPTS=i,e.endPTS=i+e.duration}}function tz(e,t){let i=t.fragments;for(let t=0,r=i.length;t<r;t++)tX(i[t],e);t.fragmentHint&&tX(t.fragmentHint,e),t.alignedSliding=!0}function tQ(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;let i=e.fragments,r=t.fragments;if(!i.length||!r.length)return;let s=Math.round(r.length/2)-1,a=r[s],n=tj(i,a.cc)||i[Math.round(i.length/2)-1],l=a.programDateTime,o=n.programDateTime;null===l||null===o||tz((o-l)/1e3-(n.start-a.start),e)}class tJ{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}
1decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class tZ{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class t0{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),i=new Uint32Array(4);for(let e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],s=i[1],a=i[2],n=i[3],l=this.invSubMix,o=l[0],h=l[1],d=l[2],u=l[3],c=new Uint32Array(256),f=0,g=0,m=0;for(m=0;m<256;m++)m<128?c[m]=m<<1:c[m]=m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,e[f]=i,t[i]=f;let l=c[f],m=c[l],p=c[m],y=257*c[i]^0x1010100*i;r[f]=y<<24|y>>>8,s[f]=y<<16|y>>>16,a[f]=y<<8|y>>>24,n[f]=y,y=0x1010101*p^65537*m^257*l^0x1010100*f,o[i]=y<<24|y>>>8,h[i]=y<<16|y>>>16,d[i]=y<<8|y>>>24,u[i]=y,f?(f=l^c[c[c[p^l]]],g^=c[c[g]]):f=g=1}}expandKey(e){let t,i,r,s,a=this.uint8ArrayToUint32Array_(e),n=!0,l=0;for(;l<a.length&&n;)n=a[l]===this.key[l],l++;if(n)return;this.key=a;let o=this.keySize=a.length;if(4!==o&&6!==o&&8!==o)throw Error("Invalid aes key size="+o);let h=this.ksRows=(o+6+1)*4,d=this.keySchedule=new Uint32Array(h),u=this.invKeySchedule=new Uint32Array(h),c=this.sBox,f=this.rcon,g=this.invSubMix,m=g[0],p=g[1],y=g[2],T=g[3];for(t=0;t<h;t++){if(t<o){r=d[t]=a[t];continue}s=r,t%o==0?s=(c[(s=s<<8|s>>>24)>>>24]<<24|c[s>>>16&255]<<16|c[s>>>8&255]<<8|c[255&s])^f[t/o|0]<<24:o>6&&t%o==4&&(s=c[s>>>24]<<24|c[s>>>16&255]<<16|c[s>>>8&255]<<8|c[255&s]),d[t]=r=(d[t-o]^s)>>>0}for(i=0;i<h;i++)t=h-i,s=3&i?d[t]:d[t-4],i<4||t<=4?u[i]=s:u[i]=m[c[s>>>24]]^p[c[s>>>16&255]]^y[c[s>>>8&255]]^T[c[255&s]],u[i]=u[i]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(0xff0000&e)>>8|e>>>24}decrypt(e,t,i){let r,s,a,n,l,o,h,d,u,c,f,g,m,p,y=this.keySize+6,T=this.invKeySchedule,E=this.invSBox,v=this.invSubMix,S=v[0],L=v[1],R=v[2],A=v[3],b=this.uint8ArrayToUint32Array_(i),D=b[0],k=b[1],I=b[2],C=b[3],_=new Int32Array(e),w=new Int32Array(_.length),x=this.networkToHostOrderSwap;for(;t<_.length;){for(p=1,u=x(_[t]),c=x(_[t+1]),f=x(_[t+2]),g=x(_[t+3]),l=u^T[0],o=g^T[1],h=f^T[2],d=c^T[3],m=4;p<y;p++)r=S[l>>>24]^L[o>>16&255]^R[h>>8&255]^A[255&d]^T[m],s=S[o>>>24]^L[h>>16&255]^R[d>>8&255]^A[255&l]^T[m+1],a=S[h>>>24]^L[d>>16&255]^R[l>>8&255]^A[255&o]^T[m+2],n=S[d>>>24]^L[l>>16&255]^R[o>>8&255]^A[255&h]^T[m+3],l=r,o=s,h=a,d=n,m+=4;r=E[l>>>24]<<24^E[o>>16&255]<<16^E[h>>8&255]<<8^E[255&d]^T[m],s=E[o>>>24]<<24^E[h>>16&255]<<16^E[d>>8&255]<<8^E[255&l]^T[m+1],a=E[h>>>24]<<24^E[d>>16&255]<<16^E[l>>8&255]<<8^E[255&o]^T[m+2],n=E[d>>>24]<<24^E[l>>16&255]<<16^E[o>>8&255]<<8^E[255&h]^T[m+3],w[t]=x(r^D),w[t+1]=x(n^k),w[t+2]=x(a^I),w[t+3]=x(s^C),D=u,k=c,I=f,C=g,t+=4}return w.buffer}}class t1{constructor(e,{removePKCS7Padding:t=!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=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch(e){}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(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let i=new Uint8Array(e);if(this.reset(),this.removePKCS7Padding){let e,t;return(t=(e=i.byteLength)&&new DataView(i.buffer).getUint8(e-1))?et(i,0,e-t):i}return i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i){return this.useSoftware?new Promise((r,s)=>
1{this.softwareDecrypt(new Uint8Array(e),t,i);let a=this.flush();a?r(a.buffer):s(Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i)}softwareDecrypt(e,t,i){let{currentIV:r,currentResult:s,remainderData:a}=this;this.logOnce("JS AES decrypt"),a&&(e=ek(a,e),this.remainderData=null);let n=this.getValidChunk(e);if(!n.length)return null;r&&(i=r);let l=this.softwareDecrypter;return(l||(l=this.softwareDecrypter=new t0),l.expandKey(t),this.currentResult=l.decrypt(n.buffer,0,i),this.currentIV=et(n,-16).buffer,s)?s:null}webCryptoDecrypt(e,t,i){let r=this.subtle;return this.key===t&&this.fastAesKey||(this.key=t,this.fastAesKey=new tZ(r,t)),this.fastAesKey.expandKey().then(t=>r?(this.logOnce("WebCrypto AES decrypt"),new tJ(r,new Uint8Array(i)).decrypt(e.buffer,t)):Promise.reject(Error("web crypto not initialized"))).catch(r=>(k.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i)))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);let r=this.flush();if(r)return r.buffer;throw Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%16;return i!==e.length&&(t=et(e,0,i),this.remainderData=et(e,i)),t}logOnce(e){this.logEnabled&&(k.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}let t2=function(e){let t="",i=e.length;for(let r=0;r<i;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t},t4="STOPPED",t3="IDLE",t5="KEY_LOADING",t8="FRAG_LOADING",t6="FRAG_LOADING_WAITING_RETRY",t9="WAITING_TRACK",t7="PARSING",ie="PARSED",it="ENDED",ii="ERROR",ir="WAITING_INIT_PTS",is="WAITING_LEVEL";class ia extends tH{constructor(e,t,i,r,s){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=t4,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=s,this.logPrefix=r,this.log=k.log.bind(k,`${r}:`),this.warn=k.warn.bind(k,`${r}:`),this.hls=e,this.fragmentLoader=new tU(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new t1(e.config),e.on(S.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=t4}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;let i=t.partList;if(null!=i&&i.length){let e=i[i.length-1];return tW.isBuffered(this.media,e.start+e.duration/2)}let r=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(r)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded){var e;return null==(e=this.levels[this.levelLastLoaded])?void 0:e.details}}onMediaAttached(e,t){let i=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);let r=this.config;this.levels&&r.autoStartLoad&&this.state===t4&&this.startLoad(r.startPosition)}onMediaDetaching(){let e=this.media;null!=e&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.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(){let{config:e,fragCurrent:t,media:i,mediaBuffer:r,state:s}=this,a=i?i.currentTime:0,n=tW.bufferInfo(r||i,a,e.maxBufferHole);if(this.log(`media seeking to ${v(a)?a.toFixed(3):a}, state: ${s}`),this.state===it)this.resetLoadingState();else if(t){let i=e.maxFragLookUpTolerance,r=t.start-i,s=t.start+t.duration+i;if(!n.len||s<n.start||r>n.end){let e=a>s;(a<r||e)&&(e&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),this.loadedmetadata||n.len||(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=t4,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(e,t,i){this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){let r=t=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${t.part?" p: "+t.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(t)};this._doFragLoad(e,t,i,r).then(t=>{if(!t)return;let i=this.state;
1if(this.fragContextChanged(e)){i!==t8&&(this.fragCurrent||i!==t7)||(this.fragmentTracker.removeFragment(e),this.state=t3);return}"payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(S.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t)}).catch(t=>{this.state!==t4&&this.state!==ii&&(this.warn(t),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===tP){let t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,r?r.len:this.config.maxBufferLength);this.reduceMaxBufferLength(s)&&i.removeFragment(e)}else(null==(t=this.mediaBuffer)?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===tF&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,i=null){e-t&&this.hls.trigger(S.BUFFER_FLUSHING,{startOffset:e,endOffset:t,type:i})}_loadInitSegment(e,t){this._doFragLoad(e,t).then(t=>{if(!t||this.fragContextChanged(e)||!this.levels)throw Error("init load aborted");return t}).then(t=>{let{hls:i}=this,{payload:r}=t,s=e.decryptdata;if(r&&r.byteLength>0&&s&&s.key&&s.iv&&"AES-128"===s.method){let a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer).catch(t=>{throw i.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(r=>{let s=self.performance.now();return i.trigger(S.FRAG_DECRYPTED,{frag:e,payload:r,stats:{tstart:a,tdecrypt:s}}),t.payload=r,t})}return t}).then(i=>{let{fragCurrent:r,hls:s,levels:a}=this;if(!a)throw Error("init load aborted, missing levels");let n=e.stats;this.state=t3,t.fragmentError=0,e.data=new Uint8Array(i.payload),n.parsing.start=n.buffering.start=self.performance.now(),n.parsing.end=n.buffering.end=self.performance.now(),i.frag===r&&s.trigger(S.FRAG_BUFFERED,{stats:n,frag:r,part:null,id:e.type}),this.tick()}).catch(t=>{this.state!==t4&&this.state!==ii&&(this.warn(t),this.resetFragmentLoading(e))})}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.level!==t.level||e.sn!==t.sn||e.urlId!==t.urlId}fragBufferedComplete(e,t){var i,r,s,a;let n=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===e4?"level":"track"} ${e.level} (frag:[${(null!=(i=e.startPTS)?i:NaN).toFixed(3)}-${(null!=(r=e.endPTS)?r:NaN).toFixed(3)}] > buffer:${n?t2(tW.getBuffered(n)):"(detached)"})`),this.state=t3,n&&(!this.loadedmetadata&&e.type==e4&&n.buffered.length&&(null==(s=this.fragCurrent)?void 0:s.sn)===(null==(a=this.fragPrevious)?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:i,part:r,partsLoaded:s}=e,a=!s||0===s.length||s.some(e=>!e),n=new tY(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(n)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var s;let a,n=null==t?void 0:t.details;if(!this.levels||!n)throw Error(`frag load aborted, missing level${n?"":" detail"}s`);let l=null;if(e.encrypted&&!(null!=(s=e.decryptdata)&&s.key)?(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${e.level}`),this.state=t5,this.fragCurrent=e,l=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(S.KEY_LOADED,e),this.state===t5&&(this.state=t3),e}),this.hls.trigger(S.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(l=Promise.reject(Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(e,n.encryptedFragments),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&"initSegment"!==e.sn){let s=n.partList;if(s&&r){i>e.end&&n.fragmentHint&&(e=n.fragmentHint);let a=this.getNextPart(s,e,i);if(a>-1){let o,h=s[a];return(this.log(`Loading part sn: ${e.sn} p: ${h.index} cc: ${e.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${a}-${s.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=h.start+h.duration,this.state=t8,o=l?l.then(i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,h,t,r)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,h,t,r).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(S.FRAG_LOADING,{frag:e,part:h,targetBufferTime:i}),null===this.fragCurrent)?Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING parts")):o}if(!e.url||this.loadedEndOfParts(s,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),v(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=t8;let o=this.config.progressive;return(a=o&&l?l.then(t=>!t||this.fragContextChanged(null==t?void 0:t.frag)?null:this.fragmentLoader.load(e,r)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,o?r:void 0),l]).then(([e])=>(!o&&e&&r&&r(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(S.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent)?Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING")):a}doFragPartsLoad(e,t,i,r){return new Promise((s,a)=>{var n;let l=[],o=null==(n=i.details)?void 0:n.partList,h=t=>{this.fragmentLoader.loadPart(e,t,r).then(r=>{l[t.index]=r;let a=r.part;this.hls.trigger(S.FRAG_LOADED,r);let n=ty(i,e.sn,t.index+1)||tT(o,e.sn,t.index+1);if(!n)return s({frag:e,part:a,partsLoaded:l});h(n)}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;e.data&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(S.ERROR,t)}else this.hls.trigger(S.ERROR,{type:L.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==t7){this.fragCurrent||this.state===t4||this.state===ii||(this.state=t3);return}let{frag:i,part:r,level:s}=t,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a),this.updateLevelTiming(i,r,s,e.partial)}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:r,sn:s,part:a}=e;if(!(null!=t&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${s} of level ${r}. The current chunk will not be buffered.`),null;let n=t[r],l=a>-1?ty(n,s,a):null,o=l?l.fragment:function(e,t,i){if(!(null!=e&&e.details))return null;let r=e.details,s=r.fragments[t-r.startSN];return s||(s=r.fragmentHint)&&s.sn===t?s:t<r.startSN&&i&&i.sn===t?i:null}(n,s,i);return o?(i&&i!==o&&(o.stats=i.stats),{frag:o,part:l,level:n}):null}bufferFragmentData(e,t,i,r,s){var a;if(!e||this.state!==t7)return;let{data1:n,data2:l}=e,o=n;if(n&&l&&(o=ek(n,l)),!(null!=(a=o)&&a.length))return;let h={type:e.type,frag:t,part:i,chunkMeta:r,parent:t.type,data:o};if(this.hls.trigger(S.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!tW.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);let i=t.currentTime,r=tW.bufferInfo(t,i,0),s=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),n=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-n>a&&this.flushMainBuffer(n,e.start)}getFwdBufferInfo(e,t){let i=this.getLoadPosition();return v(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){let{config:{maxBufferHole:r}}=this,s=tW.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&s.nextStart<a.end)return tW.bufferInfo(e,t,Math.max(s.nextStart,r))}return s}
1getMaxBufferLength(e){let{config:t}=this;return Math.min(e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,t.maxMaxBufferLength)}reduceMaxBufferLength(e){let t=this.config,i=e||t.maxBufferLength;return t.maxMaxBufferLength>=i&&(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0)}getAppendedFrag(e,t=e4){let i=this.fragmentTracker.getAppendedFrag(e,e4);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){let i,r=t.fragments,s=r.length;if(!s)return null;let{config:a}=this,n=r[0].start;if(t.live){let n=a.initialLiveManifestSize;if(s<n)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${n})`),null;t.PTSKnown||this.startFragRequested||-1!==this.startPosition||(i=this.getInitialLiveFragment(t,r),this.startPosition=i?this.hls.liveSyncPosition||i.start:e)}else e<=n&&(i=r[0]);if(!i){let r=a.lowLatencyMode?t.partEnd:t.fragmentEnd;i=this.getFragmentAtPosition(e,r,t)}return this.mapToInitFragWhenRequired(i)}isLoopLoading(e,t){let i=this.fragmentTracker.getState(e);return("OK"===i||i===tF&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,r,s){let a=e.gap,n=this.getNextFragment(this.nextLoadPosition,t);if(null===n)return n;if(e=n,a&&e&&!e.gap&&i.nextStart){let t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r);if(null!==t&&i.len+t.len>=s)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let r=-1,s=!1,a=!0;for(let n=0,l=e.length;n<l;n++){let l=e[n];if(a=a&&!l.independent,r>-1&&i<l.start)break;let o=l.loaded;o?r=-1:(s||l.independent||a)&&l.fragment===t&&(r=n),s=o}return r}loadedEndOfParts(e,t){let i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){let i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!v(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;i=i||0;for(let r=0;r<e.length;++r){let s=e[r];if(function(e,t,i){let r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}(t,i,s))return s}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let a=i.sn+1;if(a>=e.startSN&&a<=e.endSN){let s=t[a-e.startSN];i.cc===s.cc&&(r=s,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}if(!r){var s;s=i.cc,(r=tA(t,e=>e.cc<s?1:e.cc>s?-1:0))&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`)}}}else{let t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){let r,{config:s}=this,{fragPrevious:a}=this,{fragments:n,endSN:l}=i,{fragmentHint:o}=i,h=s.maxFragLookUpTolerance,d=i.partList,u=!!(s.lowLatencyMode&&null!=d&&d.length&&o);if(u&&o&&!this.bitrateTest&&(n=n.concat(o),l=o.sn),r=e<t?tb(a,n,e,e>t-h?0:h):n[n.length-1]){let e=r.sn-i.startSN,t=this.fragmentTracker.getState(r);
1if(("OK"===t||t===tF&&r.gap)&&(a=r),a&&r.sn===a.sn&&(!u||d[0].fragment.sn>r.sn)&&a&&r.level===a.level){let t=n[e+1];r=r.sn<l&&"OK"!==this.fragmentTracker.getState(t)?t:null}}return r}synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let r=this.hls.liveSyncPosition,s=i.currentTime,a=e.fragments[0].start,n=e.edge,l=s>=a-t.maxFragLookUpTolerance&&s<=n;if(null!==r&&i.duration>r&&(s<r||!l)){let a=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!l&&i.readyState<4||s<n-a)&&(this.loadedmetadata||(this.nextLoadPosition=r),i.readyState&&(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${n}, reset currentTime to : ${r.toFixed(3)}`),i.currentTime=r))}}alignPlaylists(e,t){let{levels:i,levelLastLoaded:r,fragPrevious:s}=this,a=null!==r?i[r]:null,n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;let l=e.fragments[0].start,o=!t,h=e.alignedSliding&&v(l);if(o||!h&&!l){a&&(function(e,t,i){if(i.details&&(t.endCC>t.startCC||e&&e.cc<t.startCC)){let e=function(e,t,i=0){let r=e.fragments,s=t.fragments;if(!s.length||!r.length)return void k.log("No fragments to align");let a=tj(r,s[0].cc);return a&&(!a||a.startPTS)?a:void k.log("No frag in previous level to align on")}(i.details,t);e&&v(e.start)&&(k.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),tz(e.start,t))}}(s,e,a),!e.alignedSliding&&a.details&&function(e,t){if(!t.fragments.length||!e.hasProgramDateTime||!t.hasProgramDateTime)return;let i=t.fragments[0].programDateTime,r=e.fragments[0].programDateTime,s=(r-i)/1e3+t.fragments[0].start;s&&v(s)&&(k.log(`Adjusting PTS using programDateTime delta ${r-i}ms, sliding:${s.toFixed(3)} ${e.url} `),tz(s,e))}(e,a.details),e.alignedSliding||!a.details||e.skippedSegments||tm(a.details,e));let i=e.fragments[0].start;return this.log(`Live playlist sliding: ${i.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${s?s.sn:"na"} fragments: ${n}`),i}return l}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;if(i<t&&(i=-1),-1===i||-1===this.lastCurrentTime){let r=null!==this.startTimeOffset,s=r?this.startTimeOffset:e.startTimeOffset;null!==s&&v(s)?(i=t+s,s<0&&(i+=e.totalduration),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Start time offset ${s} found in ${r?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):e.live?i=this.hls.liveSyncPosition||t:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){let{media:e}=this,t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&"initSegment"!==e.sn&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===t6)||(this.state=t3)}onFragmentOrKeyLoadError(e,t){var i,r;if(t.chunkMeta&&!t.frag){let e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}let s=t.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(i=this.fragCurrent)?void 0:i.url}`);let a=t.details===R.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(s,!0);let n=t.errorAction,{action:l,retryCount:o=0,retryConfig:h}=n||{};if(n&&5===l&&h){this.resetStartWhenNotLoaded(null!=(r=this.levelLastLoaded)?r:s.level);let i=tS(h,o);this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${o+1}/${h.maxNumRetry} in ${i}ms`),n.resolved=!0,this.retryDate=self.performance.now()+i,this.state=t6}else h&&n?(this.resetFragmentErrors(e),o<h.maxNumRetry?a||(n.resolved=!0):k.warn(`${t.details} reached or exceeded max retry (${o})`)):(null==n?void 0:n.action)===2?this.state=is:this.state=ii;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===t7||this.state===ie){let t=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,t),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len);let s=!r;return s&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),s}return!1}resetFragmentErrors(e){e===e3&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==t4&&(this.state=t3)}afterBufferFlushed(e,t,i){if(!e)return;let r=tW.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===it&&this.resetLoadingState()}
1resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=t3}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;let t=this.levels?this.levels[e].details:null;null!=t&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){var t;this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(null!=(t=this.levelLastLoaded)?t:e.level),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){var s;let a=i.details;if(!a)return void this.warn("level.details undefined");if(Object.keys(e.elementaryStreams).reduce((t,s)=>{let n=e.elementaryStreams[s];if(n){let l=n.endPTS-n.startPTS;if(l<=0)return this.warn(`Could not parse fragment ${e.sn} ${s} duration reliably (${l})`),t||!1;let o=r?0:tg(a,e,n.startPTS,n.endPTS,n.startDTS,n.endDTS);return this.hls.trigger(S.LEVEL_PTS_UPDATED,{details:a,level:i,drift:
1o,type:s,frag:e,start:n.startPTS,end:n.endPTS}),!0}return t},!1))i.fragmentError=0;else if((null==(s=this.transmuxer)?void 0:s.error)===null){let t=Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(0===i.fragmentError&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(t.message),this.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=ie,this.hls.trigger(S.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){if("demuxerWorker"===e.event){var t,i,r;this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(null!=(t=null!=(i=this.levelLastLoaded)?i:null==(r=this.fragCurrent)?void 0:r.level)?t:0),this.resetLoadingState()}}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function il(){return self.SourceBuffer||self.WebKitSourceBuffer}function io(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class ih{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){let i;this.cachedData&&(e=ek(this.cachedData,e),this.cachedData=null);let r=es(e,0),s=r?r.length:0,a=this._audioTrack,n=this._id3Track,l=r?(e=>{let t=eh(e);for(let e=0;e<t.length;e++){let i=t[e];if(el(i))return eg(i)}})(r):void 0,o=e.length;for((null===this.basePTS||0===this.frameIndex&&v(l))&&(this.basePTS=id(l,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&n.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:tr,duration:1/0});s<o;){if(this.canParse(e,s)){let t=this.appendFrame(a,e,s);t?(this.frameIndex++,this.lastPTS=t.sample.pts,s+=t.length,i=s):s=o}else en(e,s)?(r=es(e,s),n.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:tr,duration:1/0}),s+=r.length,i=s):s++;if(s===o&&i!==o){let t=et(e,i);this.cachedData?this.cachedData=ek(this.cachedData,t):this.cachedData=t}}return{audioTrack:a,videoTrack:io(),id3Track:n,textTrack:io()}}demuxSampleAes(e,t,i){return Promise.reject(Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:io(),id3Track:this._id3Track,textTrack:io()}}destroy(){}}let id=(e,t,i)=>v(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0);function iu(e,t){return 255===e[t]&&(246&e[t+1])==240}function ic(e,t){return 1&e[t+1]?7:9}function ig(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function im(e,t){return t+1<e.length&&iu(e,t)}function ip(e,t,i,r,s){if(!e.samplerate){let a,n,l,o,h,d,u,c=(h=navigator.userAgent.toLowerCase(),d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],a=((192&i[r+2])>>>6)+1,(u=(60&i[r+2])>>>2)>d.length-1?void t.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${u}`}):(l=(1&i[r+2])<<2|(192&i[r+3])>>>6,k.log(`manifest codec:${s}, ADTS type:${a}, samplingIndex:${u}`),/firefox/i.test(h)?u>=6?(a=5,o=[,,,,],n=u-3):(a=2,o=[,,],n=u):-1!==h.indexOf("android")?(a=2,o=[,,],n=u):(a=5,o=[,,,,],s&&(-1!==s.indexOf("mp4a.40.29")||-1!==s.indexOf("mp4a.40.5"))||!s&&u>=6?n=u-3:((s&&-1!==s.indexOf("mp4a.40.2")&&(u>=6&&1===l||/vivaldi/i.test(h))||!s&&1===l)&&(a=2,o=[,,]),n=u)),o[0]=a<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=l<<3,5===a&&(o[1]|=(14&n)>>1,o[2]=(1&n)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[u],channelCount:l,codec:"mp4a.40."+a,manifestCodec:s}));c&&(e.config=c.config,e.samplerate=c.samplerate,e.channelCount=c.channelCount,e.codec=c.codec,e.manifestCodec=c.manifestCodec,k.log(`parsed codec:${e.codec}, rate:${c.samplerate}, channels:${c.channelCount}`))}}function iy(e,t,i,r,s){let a,n=r+s*(9216e4/e.samplerate),l=function(e,t){let i=ic(e,t);if(t+i<=e.length){let r=ig(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);if(l){let{frameLength:r,headerLength:s}=l,o=s+r,h=Math.max(0,i+o-t.length);h?(a=new Uint8Array(o-s)).set(t.subarray(i+s,t.length),0):a=t.subarray(i+s,i+o);let d={unit:a,pts:n};return h||e.samples.push(d),{sample:d,length:o,missing:h}}let o=t.length-i;return(a=new Uint8Array(o)).set(t.subarray(i,t.length),0),{sample:{unit:a,pts:n},length:o,missing:-1}}class iT extends ih{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=(es(e,0)||[]).length;for(let i=e.length;t<i;t++)if(function(e,t){if(im(e,t)){let i=ic(e,t);if(t+i>=e.length)return!1;let r=ig(e,t);if(r<=i)return!1;let s=t+r;return s===e.length||im(e,s)}return!1}(e,t))return k.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return t+5<e.length&&iu(e,t)&&ig(e,t)<=e.length-t}appendFrame(e,t,i){ip(e,this.observer,t,i,e.manifestCodec);let r=iy(e,t,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}}let iE=/\/emsg[-/]ID3/i;class iv{constructor(e,t){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=t}resetTimeStamp(){}resetInitSegment(e,t,i,r){let s=this.videoTrack=io("video",1),a=this.audioTrack=io("audio",1),n=this.txtTrack=io("text",1);if(this.id3Track=io("id3",1),this.timeOffset=0,!(null!=e&&e.byteLength))return;let l=eb(e);if(l.video){let{id:e,timescale:t,codec:i}=l.video;s.id=e,s.timescale=n.timescale=t,s.codec=i}if(l.audio){let{id:e,timescale:t,codec:i}=l.audio;a.id=e,a.timescale=t,a.codec=i}n.id=eT.text,s.sampleDuration=0,s.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return eA(e=e.length>16384?e.subarray(0,16384):e,["moof"]).length>0}demux(e,t){this.timeOffset=t;let i=e,r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=ek(this.remainderData,e));let t=function(e){let t={valid:null,remainder:null},i=eA(e,["moof"]);if(!i)return t;if(i.length<2)return t.remainder=e,t;let r=i[i.length-1];return t.valid=et(e,0,r.byteOffset-8),t.remainder=et(e,r.byteOffset-8),t}(i);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=i;let a=this.extractID3Track(r,t);return s.samples=eI(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return i.samples=eI(e,t),{videoTrack:t,audioTrack:io(),id3Track:r,textTrack:io()}}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let r=eA(e.samples,["emsg"]);
1r&&r.forEach(e=>{let r=function(e){let t=e[0],i="",r="",s=0,a=0,n=0,l=0,o=0,h=0;if(0===t){for(;"\0"!==eE(e.subarray(h,h+1));)i+=eE(e.subarray(h,h+1)),h+=1;for(i+=eE(e.subarray(h,h+1)),h+=1;"\0"!==eE(e.subarray(h,h+1));)r+=eE(e.subarray(h,h+1)),h+=1;r+=eE(e.subarray(h,h+1)),h+=1,s=eS(e,12),a=eS(e,16),l=eS(e,20),o=eS(e,24),h=28}else if(1===t){h+=4,s=eS(e,h);let t=eS(e,h+=4),a=eS(e,h+=4);for(h+=4,Number.isSafeInteger(n=0x100000000*t+a)||(n=Number.MAX_SAFE_INTEGER,k.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=eS(e,h),h+=4,o=eS(e,h),h+=4;"\0"!==eE(e.subarray(h,h+1));)i+=eE(e.subarray(h,h+1)),h+=1;for(i+=eE(e.subarray(h,h+1)),h+=1;"\0"!==eE(e.subarray(h,h+1));)r+=eE(e.subarray(h,h+1)),h+=1;r+=eE(e.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:n,presentationTimeDelta:a,eventDuration:l,id:o,payload:e.subarray(h,e.byteLength)}}(e);if(iE.test(r.schemeIdUri)){let e=v(r.presentationTime)?r.presentationTime/r.timeScale:t+r.presentationTimeDelta/r.timeScale,s=0xffffffff===r.eventDuration?1/0:r.eventDuration/r.timeScale;s<=.001&&(s=1/0);let a=r.payload;i.samples.push({data:a,len:a.byteLength,dts:e,pts:e,type:ts,duration:s})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}let iS=null,iL=[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],iR=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],iA=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],ib=[0,1,1,4];function iD(e,t,i,r,s){if(i+24>t.length)return;let a=ik(t,i);if(a&&i+a.frameLength<=t.length){let n=r+s*(9e4*a.samplesPerFrame/a.sampleRate),l={unit:t.subarray(i,i+a.frameLength),pts:n,dts:n};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(l),{sample:l,length:a.frameLength,missing:0}}}function ik(e,t){let i=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==a){let n=e[t+2]>>1&1,l=e[t+3]>>6,o=1e3*iL[14*(3===i?3-r:3===r?3:4)+s-1],h=iR[3*(3===i?0:2===i?1:2)+a],d=iA[i][r],u=ib[r],c=Math.floor(d*o/h+n)*u;if(null===iS){let e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);iS=e?parseInt(e[1]):0}return iS&&iS<=87&&2===r&&o>=224e3&&0===l&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:3===l?1:2,frameLength:c,samplesPerFrame:8*d*u}}}function iI(e,t){return 255===e[t]&&(224&e[t+1])==224&&(6&e[t+1])!=0}function iC(e,t){return t+1<e.length&&iI(e,t)}class i_{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw Error("no bytes available");r.set(e.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e||(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord()),this.word<<=e,this.bitsAvailable-=e}readBits(e){let t=Math.min(this.bitsAvailable,e),i=this.word>>>32-t;if(e>32&&k.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw Error("no bits available");return(t=e-t)>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&0x80000000>>>e)!=0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t=8,i=8;for(let r=0;r<e;r++)0!==i&&(i=(t+this.readEG()+256)%256),t=0===i?t:i}readSPS(){let e,t,i,r=0,s=0,a=0,n=0,l=this.readUByte.bind(this),o=this.readBits.bind(this),h=this.readUEG.bind(this),d=this.readBoolean.bind(this),u=this.skipBits.bind(this),c=this.skipEG.bind(this),f=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);l();let m=l();if(o(5),u(3),l(),f(),100===m||110===m||122===m||244===m||44===m||83===m||86===m||118===m||128===m){let e=h();if(3===e&&u(1),f(),f(),u(1),d())for(i=0,t=3!==e?8:12;i<t;i++)d()&&g(i<6?16:64)}f();let p=h();if(0===p)h();else if(1===p)for(u(1),c(),c(),e=h(),i=0;i<e;i++)c();f(),u(1);let y=h(),T=h(),E=o(1);0===E&&u(1),u(1),d()&&(r=h(),s=h(),a=h(),n=h());let v=[1,1];if(d()&&d())switch(l()){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=[l()<<8|l(),l()<<8|l()]}return{width:Math.ceil((y+1)*16-2*r-2*s),height:(2-E)*(T+1)*16-(E?2:4)*(a+n),pixelRatio:v}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class iw{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new t1(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){let r=e[t].unit;if(r.length<=16)return;let s=r.subarray(16,r.length-r.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(a).then(s=>{let a=new Uint8Array(s);r.set(a,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)})}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=new Int8Array(16*Math.floor((e.length-48)/160)+16),i=0;for(let r=32;r<e.length-16;r+=160,i+=16)t.set(e.subarray(r,r+16),i);return t}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(i.subarray(r,r+16),t);return e}decryptAvcSample(e,t,i,r,s){let a=e_(s.data),n=this.getAvcEncryptedData(a);this.decryptBuffer(n.buffer).then(n=>{s.data=this.getAvcDecryptedUnit(a,n),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)})}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();let s=e[t].units;for(;!(i>=s.length);i++){let a=s[i];if(!(a.data.length<=48)&&(1===a.type||5===a.type)&&(this.decryptAvcSample(e,t,i,r,a),!this.decrypter.isSync()))return}}}}class ix{constructor(e,t,i){this.observer=void 0,this.config=void 0,this.typeSupp
1orted=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=e,this.config=t,this.typeSupported=i}static probe(e){let t=ix.syncOffset(e);return t>0&&k.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),-1!==t}static syncOffset(e){let t=e.length,i=Math.min(940,e.length-188)+1,r=0;for(;r<i;){let s=!1,a=-1,n=0;for(let l=r;l<t;l+=188)if(71===e[l]){if(n++,-1===a&&0!==(a=l)&&(i=Math.min(a+18612,e.length-188)+1),s||(s=0===iF(e,l)),s&&n>1&&(0===a&&n>2||l+188>i))return a}else if(n)return -1;else break;r++}return -1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:eT[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=ix.createTrack("video"),this._audioTrack=ix.createTrack("audio",r),this._id3Track=ix.createTrack("id3"),this._txtTrack=ix.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=r}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_avcTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(e,t,i=!1,r=!1){let s;i||(this.sampleAes=null);let a=this._avcTrack,n=this._audioTrack,l=this._id3Track,o=this._txtTrack,h=a.pid,d=a.pesData,u=n.pid,c=l.pid,f=n.pesData,g=l.pesData,m=null,p=this.pmtParsed,y=this._pmtId,T=e.length;if(this.remainderData&&(T=(e=ek(this.remainderData,e)).length,this.remainderData=null),T<188&&!r)return this.remainderData=e,{audioTrack:n,videoTrack:a,id3Track:l,textTrack:o};let E=Math.max(0,ix.syncOffset(e));(T-=(T-E)%188)<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let v=0;for(let t=E;t<T;t+=188)if(71===e[t]){let r,T=!!(64&e[t+1]),v=iF(e,t);if((48&e[t+3])>>4>1){if((r=t+5+e[t+4])===t+188)continue}else r=t+4;switch(v){case h:T&&(d&&(s=iM(d))&&this.parseAVCPES(a,o,s,!1),d={data:[],size:0}),d&&(d.data.push(e.subarray(r,t+188)),d.size+=t+188-r);break;case u:if(T){if(f&&(s=iM(f)))switch(n.segmentCodec){case"aac":this.parseAACPES(n,s);break;case"mp3":this.parseMPEGPES(n,s)}f={data:[],size:0}}f&&(f.data.push(e.subarray(r,t+188)),f.size+=t+188-r);break;case c:T&&(g&&(s=iM(g))&&this.parseID3PES(l,s),g={data:[],size:0}),g&&(g.data.push(e.subarray(r,t+188)),g.size+=t+188-r);break;case 0:var A,b;T&&(r+=e[r]+1),y=this._pmtId=(31&(A=e)[(b=r)+10])<<8|A[b+11];break;case y:{T&&(r+=e[r]+1);let s=function(e,t,i,r){let s={audio:-1,avc:-1,id3:-1,segmentCodec:"aac"},a=(15&e[t+1])<<8|e[t+2],n=t+3+a-4,l=(15&e[t+10])<<8|e[t+11];for(t+=12+l;t<n;){let a=iF(e,t);switch(e[t]){case 207:if(!r){k.log("ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream");break}case 15:-1===s.audio&&(s.audio=a);break;case 21:-1===s.id3&&(s.id3=a);break;case 219:if(!r){k.log("H.264 with AES-128-CBC slice encryption found in unencrypted stream");break}case 27:-1===s.avc&&(s.avc=a);break;case 3:case 4:!0!==i.mpeg&&!0!==i.mp3?k.log("MPEG audio found, not supported in this browser"):-1===s.audio&&(s.audio=a,s.segmentCodec="mp3");break;case 36:k.warn("Unsupported HEVC stream type found")}t+=((15&e[t+3])<<8|e[t+4])+5}return s}(e,r,this.typeSupported,i);(h=s.avc)>0&&(a.pid=h),(u=s.audio)>0&&(n.pid=u,n.segmentCodec=s.segmentCodec),(c=s.id3)>0&&(l.pid=c),null===m||p||(k.warn(`MPEG-TS PMT found at ${t} after unknown PID '${m}'. Backtracking to sync byte @${E} to parse all TS packets.`),m=null,t=E-188),p=this.pmtParsed=!0;break}case 17:case 8191:break;default:m=v}}else v++;if(v>0){let e=Error(`Found ${v} TS packet/s that do not start with 0x47`);this.observer.emit(S.ERROR,S.ERROR,{type:L.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message})}a.pesData=d,n.pesData=f,l.pesData=g;let D={audioTrack:n,videoTrack:a,id3Track:l,textTrack:o};return r&&this.extractRemainingSamples(D),D}flush(){let e,{remainderData:t}=this;
1return(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(e){let t,{audioTrack:i,videoTrack:r,id3Track:s,textTrack:a}=e,n=r.pesData,l=i.pesData,o=s.pesData;if(n&&(t=iM(n))?(this.parseAVCPES(r,a,t,!0),r.pesData=null):r.pesData=n,l&&(t=iM(l))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,t);break;case"mp3":this.parseMPEGPES(i,t)}i.pesData=null}else null!=l&&l.size&&k.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;o&&(t=iM(o))?(this.parseID3PES(s,t),s.pesData=null):s.pesData=o}demuxSampleAes(e,t,i){let r=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new iw(this.observer,this.config,t);return this.decrypt(r,s)}decrypt(e,t){return new Promise(i=>{let{audioTrack:r,videoTrack:s}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,()=>{i(e)}):i(e)}):s.samples&&t.decryptAvcSamples(s.samples,0,0,()=>{i(e)})})}destroy(){this._duration=0}parseAVCPES(e,t,i,r){let s,a=this.parseAVCNALu(e,i.data),n=this.avcSample,l=!1;i.data=null,n&&a.length&&!e.audFound&&(iO(n,e),n=this.avcSample=iP(!1,i.pts,i.dts,"")),a.forEach(r=>{var a,o;switch(r.type){case 1:{let t=!1;s=!0;let a=r.data;if(l&&a.length>4){let e=new i_(a).readSliceType();(2===e||4===e||7===e||9===e)&&(t=!0)}t&&null!=(o=n)&&o.frame&&!n.key&&(iO(n,e),n=this.avcSample=null),n||(n=this.avcSample=iP(!0,i.pts,i.dts,"")),n.frame=!0,n.key=t;break}case 5:s=!0,null!=(a=n)&&a.frame&&!n.key&&(iO(n,e),n=this.avcSample=null),n||(n=this.avcSample=iP(!0,i.pts,i.dts,"")),n.key=!0,n.frame=!0;break;case 6:s=!0,eC(r.data,1,i.pts,t.samples);break;case 7:if(s=!0,l=!0,!e.sps){let t=r.data,i=new i_(t).readSPS();e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t],e.duration=this._duration;let s=t.subarray(1,4),a="avc1.";for(let e=0;e<3;e++){let t=s[e].toString(16);t.length<2&&(t="0"+t),a+=t}e.codec=a}break;case 8:s=!0,e.pps||(e.pps=[r.data]);break;case 9:s=!1,e.audFound=!0,n&&iO(n,e),n=this.avcSample=iP(!1,i.pts,i.dts,"");break;case 12:s=!0;break;default:s=!1,n&&(n.debug+="unknown NAL "+r.type+" ")}n&&s&&n.units.push(r)}),r&&n&&(iO(n,e),this.avcSample=null)}getLastNalUnit(e){var t;let i,r=this.avcSample;if(r&&0!==r.units.length||(r=e[e.length-1]),null!=(t=r)&&t.units){let e=r.units;i=e[e.length-1]}return i}parseAVCNALu(e,t){let i,r,s,a=t.byteLength,n=e.naluState||0,l=n,o=[],h=0,d=-1,u=0;for(-1===n&&(d=0,u=31&t[0],n=0,h=1);h<a;){if(i=t[h++],!n){n=+!i;continue}if(1===n){n=2*!i;continue}if(i)if(1===i){if(d>=0){let e={data:t.subarray(d,h-n-1),type:u};o.push(e)}else{let i=this.getLastNalUnit(e.samples);if(i&&(l&&h<=4-l&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-l)),(r=h-n-1)>0)){let e=new Uint8Array(i.data.byteLength+r);e.set(i.data,0),e.set(t.subarray(0,r),i.data.byteLength),i.data=e,i.state=0}}h<a?(s=31&t[h],d=h,u=s,n=0):n=-1}else n=0;else n=3}if(d>=0&&n>=0){let e={data:t.subarray(d,a),type:u,state:n};o.push(e)}if(0===o.length){let i=this.getLastNalUnit(e.samples);if(i){let e=new Uint8Array(i.data.byteLength+t.byteLength);e.set(i.data,0),e.set(t,i.data.byteLength),i.data=e}}return e.naluState=n,o}parseAACPES(e,t){let i,r,s,a,n=0,l=this.aacOverFlow,o=t.data;if(l){this.aacOverFlow=null;let t=l.missing,i=l.sample.unit.byteLength;if(-1===t){let e=new Uint8Array(i+o.byteLength);e.set(l.sample.unit,0),e.set(o,i),o=e}else l.sample.unit.set(o.subarray(0,t),i-t),e.samples.push(l.sample),n=l.missing}for(i=n,r=o.length;i<r-1&&!im(o,i);i++);if(i!==n){let e,t=i<r-1,s=Error(e=t?`AAC PES did not start with ADTS header,offset:${i}`:"No ADTS header found in AAC PES");if(k.warn(`parsing error: ${e}`),this.observer.emit(S.ERROR,S.ERROR,{type:L.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:s,reason:e}),!t)return}if(ip(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)s=t.pts;else{if(!l)return void k.warn("[tsdemuxer]: AAC PES unknown PTS");let t=9216e4/e.samplerate;s=l.sample.pts+t}let h=0;for(;i<r;){if(a=iy(e,o,i,s,h),i+=a.length,a.missing){this.aacOverFlow=a;break}for(h++;i<r-1&&!im(o,i);i++);}}parseMPEGPES(e,t){let i=t.data,r=i.length,s=0,a=0,n=t.pts;if(void 0===n)return void k.warn("[tsdemuxer]: MPEG PES unknown PTS");for(;a<r;)if(iC(i,a)){let t=iD(e,i,a,n,s);if(t)a+=t.length,s++;else break}else a++}parseID3PES(e,t){if(void 0===t.pts)return void k.warn("[tsdemuxer]: ID3 PES unknown PTS");let i=E({},t,{type:this._avcTrack?ts:tr,duration:1/0});e.samples.push(i)}}function iP(e,t,i,r){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:r,length:0}}function iF(e,t){return((31&e[t+1])<<8)+e[t+2]}function iM(e){let t,i,r,s,a,n=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;){let e=new Uint8Array(l[0].length+l[1].length);e.set(l[0]),e.set(l[1],l[0].length),l[0]=e,l.splice(1,1)}if(1===((t=l[0])[0]<<16)+(t[1]<<8)+t[2]){if((i=(t[4]<<8)+t[5])&&i>e.size-6)return null;let o=t[7];192&o&&(s=(14&t[9])*0x20000000+(255&t[10])*4194304+(254&t[11])*16384+(255&t[12])*128+(254&t[13])/2,64&o?s-(a=(14&t[14])*0x20000000+(255&t[15])*4194304+(254&t[16])*16384+(255&t[17])*128+(254&t[18])/2)>54e5&&(k.warn(`${Math.round((s-a)/9e4)}s delta between PTS and DTS, align them`),s=a):a=s);let h=(r=t[8])+9;if(e.size<=h)return null;e.size-=h;let d=new Uint8Array(e.size);for(let e=0,i=l.length;e<i;e++){let i=(t=l[e]).byteLength;if(h)if(h>i){h-=i;continue}else t=t.subarray(h),i-=h,h=0;d.set(t,n),n+=i}return i&&(i-=r+3),{data:d,pts:s,dts:a,len:i}}return null}function iO(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){let i=t.samples,r=i.length;if(!r)return void t.dropped++;{let t=i[r-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}e.debug.length&&k.log(e.pts+"/"+e.dts+":"+e.debug)}class iN extends ih{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=(es(e,0)||[]).length;for(let i=e.length;t<i;t++)if(function(e,t){if(t+1<e.length&&iI(e,t)){let i=ik(e,t),r=4;null!=i&&i.frameLength&&(r=i.frameLength);let s=t+r;return s===e.length||iC(e,s)}return!1}(e,t))return k.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return iI(e,t)&&4<=e.length-t}appendFrame(e,t,i){if(null!==this.basePTS)return iD(e,t,i,this.basePTS,this.frameIndex)}}class iU{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);else if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);else if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);else if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)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===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}class iB{static init(){let e;for(e in iB.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:[]},iB.types)iB.types.hasOwnProperty(e)&&(iB.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);iB.HDLR_TYPES={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])};let t=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);iB.STTS=iB.STSC=iB.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),iB.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),iB.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),iB.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),iB.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);
1let i=new Uint8Array([105,115,111,109]),r=new Uint8Array([97,118,99,49]),s=new Uint8Array([0,0,0,1]);iB.FTYP=iB.box(iB.types.ftyp,i,s,i,r),iB.DINF=iB.box(iB.types.dinf,iB.box(iB.types.dref,t))}static box(e,...t){let i=8,r=t.length,s=r;for(;r--;)i+=t[r].byteLength;let a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=255&i,a.set(e,4),r=0,i=8;r<s;r++)a.set(t[r],i),i+=t[r].byteLength;return a}static hdlr(e){return iB.box(iB.types.hdlr,iB.HDLR_TYPES[e])}static mdat(e){return iB.box(iB.types.mdat,e)}static mdhd(e,t){let i=Math.floor((t*=e)/0x100000000),r=Math.floor(t%0x100000000);return iB.box(iB.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return iB.box(iB.types.mdia,iB.mdhd(e.timescale,e.duration),iB.hdlr(e.type),iB.minf(e))}static mfhd(e){return iB.box(iB.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?iB.box(iB.types.minf,iB.box(iB.types.smhd,iB.SMHD),iB.DINF,iB.stbl(e)):iB.box(iB.types.minf,iB.box(iB.types.vmhd,i
1B.VMHD),iB.DINF,iB.stbl(e))}static moof(e,t,i){return iB.box(iB.types.moof,iB.mfhd(e),iB.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=iB.trak(e[t]);return iB.box.apply(null,[iB.types.moov,iB.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(iB.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=iB.trex(e[t]);return iB.box.apply(null,[iB.types.mvex,...i])}static mvhd(e,t){let i=Math.floor((t*=e)/0x100000000),r=Math.floor(t%0x100000000),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return iB.box(iB.types.mvhd,s)}static sdtp(e){let t,i,r=e.samples||[],s=new Uint8Array(4+r.length);for(t=0;t<r.length;t++)i=r[t].flags,s[t+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return iB.box(iB.types.sdtp,s)}static stbl(e){return iB.box(iB.types.stbl,iB.stsd(e),iB.box(iB.types.stts,iB.STTS),iB.box(iB.types.stsc,iB.STSC),iB.box(iB.types.stsz,iB.STSZ),iB.box(iB.types.stco,iB.STCO))}static avc1(e){let t,i,r,s=[],a=[];for(t=0;t<e.sps.length;t++)r=(i=e.sps[t]).byteLength,s.push(r>>>8&255),s.push(255&r),s=s.concat(Array.prototype.slice.call(i));for(t=0;t<e.pps.length;t++)r=(i=e.pps[t]).byteLength,a.push(r>>>8&255),a.push(255&r),a=a.concat(Array.prototype.slice.call(i));let n=iB.box(iB.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|e.sps.length].concat(s).concat([e.pps.length]).concat(a))),l=e.width,o=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return iB.box(iB.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,l>>8&255,255&l,o>>8&255,255&o,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),n,iB.box(iB.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),iB.box(iB.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(e){let t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static mp4a(e){let t=e.samplerate;return iB.box(iB.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0]),iB.box(iB.types.esds,iB.esds(e)))}static mp3(e){let t=e.samplerate;return iB.box(iB.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,255&t,0,0]))}static stsd(e){return"audio"!==e.type?iB.box(iB.types.stsd,iB.STSD,iB.avc1(e)):"mp3"===e.segmentCodec&&"mp3"===e.codec?iB.box(iB.types.stsd,iB.STSD,iB.mp3(e)):iB.box(iB.types.stsd,iB.STSD,iB.mp4a(e))}static tkhd(e){let t=e.id,i=e.duration*e.timescale,r=e.width,s=e.height,a=Math.floor(i/0x100000000),n=Math.floor(i%0x100000000);return iB.box(iB.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,n>>24,n>>16&255,n>>8&255,255&n,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,s>>8&255,255&s,0,0]))}static traf(e,t){let i=iB.sdtp(e),r=e.id,s=Math.floor(t/0x100000000),a=Math.floor(t%0x100000000);return iB.box(iB.types.traf,iB.box(iB.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),iB.box(iB.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,a>>24,a>>16&255,a>>8&255,255&a])),iB.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||0xffffffff,iB.box(iB.types.trak,iB.tkhd(e),iB.mdia(e))}static trex(e){let t=e.id;return iB.box(iB.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let i,r,s,a,n,l,o=e.samples||[],h=o.length,d=12+16*h,u=new Uint8Array(d);for(t+=8+d,u.set([+("video"===e.type),0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),i=0;i<h;i++)s=(r=o[i]).duration,a=r.size,n=r.flags,l=r.cts,u.set([s>>>24&255,s>>>16&255,s>>>8&255,255&s,a>>>24&255,a>>>16&255,a>>>8&255,255&a,n.isLeading<<2|n.dependsOn,n.isDependedOn<<6|n.hasRedundancy<<4|n.paddingValue<<1|n.isNonSync,61440&n.degradPrio,15&n.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return iB.box(iB.types.trun,u)}static initSegment(e){iB.types||iB.init();let t=iB.moov(e),i=new Uint8Array(iB.FTYP.byteLength+t.byteLength);return i.set(iB.FTYP),i.set(t,iB.FTYP.byteLength),i}}function i$(e,t,i=1,r=!1){let s=e*t*i;return r?Math.round(s):s}function iG(e,t=!1){return i$(e,1e3,11111111111111112e-21,t)}iB.types=void 0,iB.HDLR_TYPES=void 0,iB.STTS=void 0,iB.STSC=void 0,iB.STCO=void 0,iB.STSZ=void 0,iB.VMHD=void 0,iB.SMHD=void 0,iB.STSD=void 0,iB.FTYP=void 0,iB.DINF=void 0;let iK=null,iH=null;class iV{constructor(e,t,i,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupp
1orted=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=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,null===iK){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);iK=e?parseInt(e[1]):0}if(null===iH){const e=navigator.userAgent.match(/Safari\/(\d+)/i);iH=e?parseInt(e[1]):0}}destroy(){}resetTimeStamp(e){k.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){k.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){k.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1}getVideoStartPts(e){let t=!1,i=e.reduce((e,i)=>{let r=i.pts-e;return r<-0x100000000?(t=!0,iW(e,i.pts)):r>0?e:i.pts},e[0].pts);return t&&k.debug("PTS rollover detected"),i}remux(e,t,i,r,s,a,n,l){let o,h,d,u,c,f,g=s,m=s,p=e.pid>-1,y=t.pid>-1,T=t.samples.length,E=e.samples.length>0,v=n&&T>0||T>1;if((!p||E)&&(!y||v)||this.ISGenerated||n){let i;this.ISGenerated||(d=this.generateIS(e,t,s,a));let r=this.isVideoContiguous,n=-1;if(v&&(n=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return -1}(t.samples),!r&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,n>0){k.warn(`[mp4-remuxer]: Dropped ${n} out of ${T} video samples due to a missing keyframe`);let e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(n),t.dropped+=n,m+=(t.samples[0].pts-e)/t.inputTimeScale,i=m}else -1===n&&(k.warn(`[mp4-remuxer]: No keyframe found out of ${T} video samples`),f=!1);if(this.ISGenerated){if(E&&v){let i=this.getVideoStartPts(t.samples),r=(iW(e.samples[0].pts,i)-i)/t.inputTimeScale;g+=Math.max(0,r),m+=Math.max(0,-r)}if(E){if(e.samplerate||(k.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s,a)),h=this.remuxAudio(e,g,this.isAudioContiguous,a,y||v||l===e3?m:void 0),v){let i=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(k.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,t,s,a)),o=this.remuxVideo(t,m,r,i)}}else v&&(o=this.remuxVideo(t,m,r,0));o&&(o.firstKeyFrame=n,o.independent=-1!==n,o.firstKeyFramePTS=i)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(c=iY(i,s,this._initPTS,this._initDTS)),r.samples.length&&(u=iq(r,s,this._initPTS))),{audio:h,video:o,initSegment:d,independent:f,text:u,id3:c}}generateIS(e,t,i,r){let s,a,n,l=e.samples,o=t.samples,h=this.typeSupported,d={},u=this._initPTS,c=!u||r,f="audio/mp4";if(c&&(s=a=1/0),e.config&&l.length&&(e.timescale=e.samplerate,"mp3"===e.segmentCodec&&(h.mpeg?(f="audio/mpeg",e.codec=""):h.mp3&&(e.codec="mp3")),d.audio={id:"audio",container:f,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&h.mpeg?new Uint8Array(0):iB.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(n=e.inputTimeScale,u&&n===u.timescale?c=!1:s=a=l[0].pts-Math.round(n*i))),t.sps&&t.pps&&o.length&&(t.timescale=t.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:iB.initSegment([t]),metadata:{width:t.width,height:t.height}},c))if(n=t.inputTimeScale,u&&n===u.timescale)c=!1;else{let e=this.getVideoStartPts(o),t=Math.round(n*i);a=Math.min(a,iW(o[0].dts,e)-t),s=Math.min(s,e-t)}if(Object.keys(d).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:s,timescale:n},this._initDTS={baseTime:a,timescale:n}):s=n=void 0,{tracks:d,initPTS:s,timescale:n}}remuxVideo(e,t,i,r){let s,a,n,l=e.inputTimeScale,o=e.samples,h=[],d=o.length,u=this._initPTS,c=this.nextAvcDts,f=8,g=this.videoSampleDuration,m=1/0,p=-1/0,y=!1;i&&null!==c||(c=t*l-(o[0].pts-iW(o[0].dts,o[0].pts)));let T=u.baseTime*l/u.timescale;for(let e=0;e<d;e++){let t=o[e];t.pts=iW(t.pts-T,c),t.dts=iW(t.dts-T,c),t.dts<o[e>0?e-1:e].dts&&(y=!0)}y&&o.sort(function(e,t){let i=e.dts-t.dts,r=e.pts-t.pts;return i||r}),s=o[0].dts;let v=(a=o[o.length-1].dts)-s,A=v?Math.round(v/(d-1)):g||e.inputTimeScale/30;if(i){let e=s-c,t=e>A,i=e<-1;if((t||i)&&(t?k.warn(`AVC: ${iG(e,!0)} ms (${e}dts) hole between fragments detected, filling it`):k.warn(`AVC: ${iG(-e,!0)} ms (${e}dts) overlapping between fragments detected`),!i||c>=o[0].pts)){s=c;
1let t=o[0].pts-e;o[0].dts=s,o[0].pts=t,k.log(`Video: First PTS/DTS adjusted: ${iG(t,!0)}/${iG(s,!0)}, delta: ${iG(e,!0)} ms`)}}s=Math.max(0,s);let b=0,D=0;for(let e=0;e<d;e++){let t=o[e],i=t.units,r=i.length,a=0;for(let e=0;e<r;e++)a+=i[e].data.length;D+=a,b+=r,t.length=a,t.dts=Math.max(t.dts,s),m=Math.min(t.pts,m),p=Math.max(t.pts,p)}a=o[d-1].dts;let I=D+4*b+8;try{n=new Uint8Array(I)}catch(e){this.observer.emit(S.ERROR,S.ERROR,{type:L.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:I,reason:`fail allocating video mdat ${I}`});return}let C=new DataView(n.buffer);C.setUint32(0,I),n.set(iB.types.mdat,4);let _=!1,w=1/0,x=1/0,P=-1/0,F=-1/0;for(let e=0;e<d;e++){let t,i=o[e],s=i.units,a=0;for(let e=0,t=s.length;e<t;e++){let t=s[e],i=t.data,r=t.data.byteLength;C.setUint32(f,r),f+=4,n.set(i,f),f+=r,a+=4+r}if(e<d-1)g=o[e+1].dts-i.dts,t=o[e+1].pts-i.pts;else{let s=this.config,a=e>0?i.dts-o[e-1].dts:A;if(t=e>0?i.pts-o[e-1].pts:A,s.stretchShortVideoTrack&&null!==this.nextAudioPts){let e=Math.floor(s.maxBufferHole*l),t=(r?m+r*l:this.nextAudioPts)-i.pts;t>e?((g=t-a)<0?g=a:_=!0,k.log(`[mp4-remuxer]: It is approximately ${t/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=a}else g=a}let u=Math.round(i.pts-i.dts);w=Math.min(w,g),P=Math.max(P,g),x=Math.min(x,t),F=Math.max(F,t),h.push(new ij(i.key,g,a,u))}if(h.length){if(iK){if(iK<70){let e=h[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(iH&&F-x<P-w&&A/P<.025&&0===h[0].cts){k.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=s;for(let t=0,i=h.length;t<i;t++){let r=e+h[t].duration,s=e+h[t].cts;if(t<i-1){let e=r+h[t+1].cts;h[t].duration=e-s}else h[t].duration=t?h[t-1].duration:A;h[t].cts=0,e=r}}}g=_||!g?A:g,this.nextAvcDts=c=a+g,this.videoSampleDuration=g,this.isVideoContiguous=!0;let M={data1:iB.moof(e.sequenceNumber++,s,E({},e,{samples:h})),data2:n,startPTS:m/l,endPTS:(p+g)/l,startDTS:s/l,endDTS:c/l,type:"video",hasAudio:!1,hasVideo:!0,nb:h.length,dropped:e.dropped};return e.samples=[],e.dropped=0,M}remuxAudio(e,t,i,r,s){let a,n=e.inputTimeScale,l=e.samplerate?e.samplerate:n,o=n/l,h="aac"===e.segmentCodec?1024:1152,d=h*o,u=this._initPTS,c="mp3"===e.segmentCodec&&this.typeSupported.mpeg,f=[],g=void 0!==s,m=e.samples,p=8*!c,y=this.nextAudioPts||-1,T=t*n,v=u.baseTime*n/u.timescale;if(this.isAudioContiguous=i=i||m.length&&y>0&&(r&&9e3>Math.abs(T-y)||Math.abs(iW(m[0].pts-v,T)-y)<20*d),m.forEach(function(e){e.pts=iW(e.pts-v,T)}),!i||y<0){if(!(m=m.filter(e=>e.pts>=0)).length)return;y=0===s?0:r&&!g?Math.max(0,T):m[0].pts}if("aac"===e.segmentCodec){let t=this.config.maxAudioFramesDrift;for(let i=0,r=y;i<m.length;i++){let s=m[i],a=s.pts,l=a-r,o=Math.abs(1e3*l/n);
1if(l<=-t*d&&g)0===i&&(k.warn(`Audio frame @ ${(a/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*l/n)} ms.`),this.nextAudioPts=y=r=a);else if(l>=t*d&&o<1e4&&g){let t=Math.round(l/d);(r=a-t*d)<0&&(t--,r+=d),0===i&&(this.nextAudioPts=y=r),k.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(r/n).toFixed(3)}s due to ${Math.round(1e3*l/n)} ms gap.`);for(let a=0;a<t;a++){let t=Math.max(r,0),a=iU.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);a||(k.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),a=s.unit.subarray()),m.splice(i,0,{unit:a,pts:t}),r+=d,i++}}s.pts=r,r+=d}}let A=null,b=null,D=0,I=m.length;for(;I--;)D+=m[I].unit.byteLength;for(let t=0,r=m.length;t<r;t++){let r=m[t],s=r.unit,n=r.pts;if(null!==b)f[t-1].duration=Math.round((n-b)/o);else{if(i&&"aac"===e.segmentCodec&&(n=y),A=n,!(D>0))return;D+=p;try{a=new Uint8Array(D)}catch(e){this.observer.emit(S.ERROR,S.ERROR,{type:L.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:D,reason:`fail allocating audio mdat ${D}`});return}c||(new DataView(a.buffer).setUint32(0,D),a.set(iB.types.mdat,4))}a.set(s,p);let l=s.byteLength;p+=l,f.push(new ij(!0,h,l,0)),b=n}let C=f.length;if(!C)return;let _=f[f.length-1];this.nextAudioPts=y=b+o*_.duration;let w=c?new Uint8Array(0):iB.moof(e.sequenceNumber++,A/o,E({},e,{samples:f}));e.samples=[];let x=A/n,P=y/n,F={data1:w,data2:a,startPTS:x,endPTS:P,startDTS:x,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:C};return this.isAudioContiguous=!0,F}remuxEmptyAudio(e,t,i,r){let s=e.inputTimeScale,a=e.samplerate?e.samplerate:s,n=this.nextAudioPts,l=this._initDTS,o=9e4*l.baseTime/l.timescale,h=(null!==n?n:r.startDTS*s)+o,d=r.endDTS*s+o,u=s/a*1024,c=Math.ceil((d-h)/u),f=iU.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(k.warn("[mp4-remuxer]: remux empty Audio"),!f)return void k.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");let g=[];for(let e=0;e<c;e++){let t=h+e*u;g.push({unit:f,pts:t,dts:t})}return e.samples=g,this.remuxAudio(e,t,i,!1)}}function iW(e,t){let i;if(null===t)return e;for(i=t<e?-0x200000000:0x200000000;Math.abs(e-t)>0x100000000;)e+=i;return e}function iY(e,t,i,r){let s=e.samples.length;if(!s)return;let a=e.inputTimeScale;for(let n=0;n<s;n++){let s=e.samples[n];s.pts=iW(s.pts-i.baseTime*a/i.timescale,t*a)/a,s.dts=iW(s.dts-r.baseTime*a/r.timescale,t*a)/a}let n=e.samples;return e.samples=[],{samples:n}}function iq(e,t,i){let r=e.samples.length;if(!r)return;let s=e.inputTimeScale;for(let a=0;a<r;a++){let r=e.samples[a];r.pts=iW(r.pts-i.baseTime*s/i.timescale,t*s)/s}e.samples.sort((e,t)=>e.pts-t.pts);let a=e.samples;return e.samples=[],{samples:a}}class ij{constructor(e,t,i,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=r,this.flags=new iX(e)}}class iX{constructor(e){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=e?2:1,this.isNonSync=+!e}}class iz{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(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(function(e,t){if(!e||!t)return e;let i=t.keyId;return i&&t.isCommonEncryption&&eA(e,["moov","trak"]).forEach(e=>{let t=eA(e,["mdia","minf","stbl","stsd"])[0].subarray(8),r=eA(t,["enca"]),s=r.length>0;s||(r=eA(t,["encv"])),r.forEach(e=>{eA(s?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{let t=eD(e);if(t){let e=t.subarray(8,24);e.some(e=>0!==e)||(k.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${ep(e)} -> ${ep(i)}`),t.set(i,8))}})})}),e}(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(null!=e&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let r=this.initData=eb(e);t||(t=iQ(r.audio,P)),i||(i=iQ(r.video,F));let s={};r.audio&&r.video?s.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:r.audio?s.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:r.video?s.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:k.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,t,i,r,s,a){var n,l,o,h,d;let{initPTS:u,lastEndTime:c}=this,f={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};v(c)||(c=this.lastEndTime=s||0);let g=t.samples;if(!(null!=g&&g.length))return f;let m={initPTS:void 0,timescale:1},p=this.initData;if(null!=(n=p)&&n.length||(this.generateInitSegment(g),p=this.initData),!(null!=(l=p)&&l.length))return k.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),f;this.emitInitSegment&&(m.tracks=this.initTracks,this.emitInitSegment=!1);let y=function(e,t){let i=0,r=0,s=0,a=eA(e,["moof","traf"]);for(let e=0;e<a.length;e++){let n=a[e],l=eA(n,["tfhd"])[0],o=t[eS(l,4)];if(!o)continue;let h=o.default,d=eS(l,0)|(null==h?void 0:h.flags),u=null==h?void 0:h.duration;8&d&&(u=2&d?eS(l,12):eS(l,8));let c=o.timescale||9e4,f=eA(n,["trun"]);for(let e=0;e<f.length;e++)(i=function(e){let t=eS(e,0),i=8;1&t&&(i+=4),4&t&&(i+=4);let r=0,s=eS(e,4);for(let a=0;a<s;a++)256&t&&(r+=eS(e,i),i+=4),512&t&&(i+=4),1024&t&&(i+=4),2048&t&&(i+=4);return r}(f[e]))||!u||(i=u*eS(f[e],4)),o.type===F?r+=i/c:o.type===P&&(s+=i/c)}if(0===r&&0===s){let t=0,i=eA(e,["sidx"]);for(let e=0;e<i.length;e++){let r=function(e){let t=[],i=e[0],r=8,s=eS(e,8);r+=4,0===i?r+=8:r+=16,r+=2;let a=e.length+0,n=ev(e,r);r+=2;
1for(let i=0;i<n;i++){let i=r,n=eS(e,i);i+=4;let l=0x7fffffff&n;if(1==(0x80000000&n)>>>31)return k.warn("SIDX has hierarchical references (not supported)"),null;let o=eS(e,i);i+=4,t.push({referenceSize:l,subsegmentDuration:o,info:{duration:o/s,start:a,end:a+l-1}}),a+=l,i+=4,r=i}return{earliestPresentationTime:0,timescale:s,version:i,referencesCount:n,references:t}}(i[e]);null!=r&&r.references&&(t+=r.references.reduce((e,t)=>e+t.info.duration||0,0))}return t}return r||s}(g,p),T=(o=p,eA(g,["moof","traf"]).reduce((e,t)=>{let i=eA(t,["tfdt"])[0],r=i[0],s=eA(t,["tfhd"]).reduce((e,t)=>{let s=o[eS(t,4)];if(s){let t=eS(i,4);if(1===r){if(0xffffffff===t)return k.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=0x100000000,t+=eS(i,8)}let a=t/(s.timescale||9e4);if(isFinite(a)&&(null===e||a<e))return a}return e},null);return null!==s&&isFinite(s)&&(null===e||s<e)?s:e},null)),E=null===T?s:T;((function(e,t,i,r){if(null===e)return!0;let s=Math.max(r,1);return Math.abs(t-e.baseTime/e.timescale-i)>s}
1)(u,E,s,y)||m.timescale!==u.timescale&&a)&&(m.initPTS=E-s,u&&1===u.timescale&&k.warn(`Adjusting initPTS by ${m.initPTS-u.baseTime}`),this.initPTS=u={baseTime:m.initPTS,timescale:1});let S=e?E-u.baseTime/u.timescale:c,L=S+y;h=p,d=u.baseTime/u.timescale,eA(g,["moof","traf"]).forEach(e=>{eA(e,["tfhd"]).forEach(t=>{let i=h[eS(t,4)];if(!i)return;let r=i.timescale||9e4;eA(e,["tfdt"]).forEach(e=>{let t=e[0],i=eS(e,4);if(0===t)i-=d*r,eR(e,4,i=Math.max(i,0));else{i*=0x100000000,i+=eS(e,8),i-=d*r;let t=Math.floor((i=Math.max(i,0))/0x100000000),s=Math.floor(i%0x100000000);eR(e,4,t),eR(e,8,s)}})})}),y>0?this.lastEndTime=L:(k.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let R=!!p.audio,A=!!p.video,b="";R&&(b+="audio"),A&&(b+="video");let D={data1:g,startPTS:S,startDTS:S,endPTS:L,endDTS:L,type:b,hasAudio:R,hasVideo:A,nb:1,dropped:0};return f.audio="audio"===D.type?D:void 0,f.video="audio"!==D.type?D:void 0,f.initSegment=m,f.id3=iY(i,s,u,u),r.samples.length&&(f.text=iq(r,s,u)),f}}function iQ(e,t){let i=null==e?void 0:e.codec;return i&&i.length>4?i:"hvc1"===i||"hev1"===i?"hvc1.1.6.L120.90":"av01"===i?"av01.0.04M.08":"avc1"===i||t===F?"avc1.42e01e":"mp4a.40.5"}try{a=self.performance.now.bind(self.performance)}catch(e){k.debug("Unable to use Performance API on this environment"),a="u">typeof self&&self.Date.now}let iJ=[{demux:iv,remux:iz},{demux:ix,remux:iV},{demux:iT,remux:iV},{demux:iN,remux:iV}];class iZ{constructor(e,t,i,r,s){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=e,this.typeSupported=t,this.config=i,this.vendor=r,this.id=s}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,r){var s,n;let l,o=i.transmuxing;o.executeStart=a();let h=new Uint8Array(e),{currentTransmuxState:d,transmuxConfig:u}=this;r&&(this.currentTransmuxState=r);let{contiguous:c,discontinuity:f,trackSwitch:g,accurateTimeOffset:m,timeOffset:p,initSegmentChange:y}=r||d,{audioCodec:T,videoCodec:E,defaultInitPts:v,duration:A,initSegmentData:b}=u,D=(s=h,n=t,l=null,s.byteLength>0&&null!=n&&null!=n.key&&null!==n.iv&&null!=n.method&&(l=n),l);if(D&&"AES-128"===D.method){let e=this.getDecrypter();if(!e.isSync())return this.decryptionPromise=e.webCryptoDecrypt(h,D.key.buffer,D.iv.buffer).then(e=>{let t=this.push(e,null,i);return this.decryptionPromise=null,t}),this.decryptionPromise;{let t=e.softwareDecrypt(h,D.key.buffer,D.iv.buffer);if(i.part>-1&&(t=e.flush()),!t)return o.executeEnd=a(),i0(i);h=new Uint8Array(t)}}let I=this.needsProbing(f,g);if(I){let e=this.configureTransmuxer(h);if(e)return k.warn(`[transmuxer] ${e.message}`),this.observer.emit(S.ERROR,S.ERROR,{type:L.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),o.executeEnd=a(),i0(i)}(f||g||y||I)&&this.resetInitSegment(b,T,E,A,t),(f||y||I)&&this.resetInitialTimestamp(v),c||this.resetContiguity();let C=this.transmux(h,D,p,m,i),_=this.currentTransmuxState;return _.contiguous=!0,_.discontinuity=!1,_.trackSwitch=!1,o.executeEnd=a(),C}flush(e){let t=e.transmuxing;t.executeStart=a();let{decrypter:i,currentTransmuxState:r,decryptionPromise:s}=this;if(s)return s.then(()=>this.flush(e));let n=[],{timeOffset:l}=r;if(i){let t=i.flush();t&&n.push(this.push(t,null,e))}let{demuxer:o,remuxer:h}=this;if(!o||!h)return t.executeEnd=a(),[i0(e)];let d=o.flush(l);return i1(d)?d.then(t=>(this.flushRemux(n,t,e),n)):(this.flushRemux(n,d,e),n)}flushRemux(e,t,i){let{audioTrack:r,videoTrack:s,id3Track:n,textTrack:l}=t,{accurateTimeOffset:o,timeOffset:h}=this.currentTransmuxState;k.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);let d=this.remuxer.remux(r,s,n,l,h,o,!0,this.id);e.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=a()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,s){let{demuxer:a,remuxer:n}=this;a&&n&&(a.resetInitSegment(e,t,i,r),n.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,r,s){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,s):this.transmuxUnencrypted(e,i,r,s)}transmuxUnencrypted(e,t,i,r){let{audioTrack:s,videoTrack:a,id3Track:n,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,a,n,l,t,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,s){return this.demuxer.demuxSampleAes(e,t,i).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,this.id),chunkMeta:s}))}
1configureTransmuxer(e){let t,{config:i,observer:r,typeSupported:s,vendor:a}=this;for(let i=0,r=iJ.length;i<r;i++)if(iJ[i].demux.probe(e)){t=iJ[i];break}if(!t)return Error("Failed to find demuxer by probing fragment data");let n=this.demuxer,l=this.remuxer,o=t.remux,h=t.demux;l&&l instanceof o||(this.remuxer=new o(r,i,s,a)),n&&n instanceof h||(this.demuxer=new h(r,i,s),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new t1(this.config)),e}}let i0=e=>({remuxResult:{},chunkMeta:e});function i1(e){return"then"in e&&e.then instanceof Function}class i2{constructor(e,t,i,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null}}class i4{constructor(e,t,i,r,s,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=a}}var i3={exports:{}};!function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function s(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,r,a,n){if("function"!=typeof r)throw TypeError("The listener must be a function");
1var l=new s(r,a||e,n),o=i?i+t:t;return e._events[o]?e._events[o].fn?e._events[o]=[e._events[o],l]:e._events[o].push(l):(e._events[o]=l,e._eventsCount++),e}function n(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function l(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(i=!1)),l.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},l.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,a=r.length,n=Array(a);s<a;s++)n[s]=r[s].fn;return n},l.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},l.prototype.emit=function(e,t,r,s,a,n){var l=i?i+e:e;if(!this._events[l])return!1;var o,h,d=this._events[l],u=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),u){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,s),!0;case 5:return d.fn.call(d.context,t,r,s,a),!0;case 6:return d.fn.call(d.context,t,r,s,a,n),!0}for(h=1,o=Array(u-1);h<u;h++)o[h-1]=arguments[h];d.fn.apply(d.context,o)}else{var c,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),u){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,t);break;case 3:d[h].fn.call(d[h].context,t,r);break;case 4:d[h].fn.call(d[h].context,t,r,s);break;default:if(!o)for(c=1,o=Array(u-1);c<u;c++)o[c-1]=arguments[c];d[h].fn.apply(d[h].context,o)}}return!0},l.prototype.on=function(e,t,i){return a(this,e,t,i,!1)},l.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},l.prototype.removeListener=function(e,t,r,s){var a=i?i+e:e;if(!this._events[a])return this;if(!t)return n(this,a),this;var l=this._events[a];if(l.fn)l.fn!==t||s&&!l.once||r&&l.context!==r||n(this,a);else{for(var o=0,h=[],d=l.length;o<d;o++)(l[o].fn!==t||s&&!l[o].once||r&&l[o].context!==r)&&h.push(l[o]);h.length?this._events[a]=1===h.length?h[0]:h:n(this,a)}return this},l.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&n(this,t)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=i,l.EventEmitter=l,e.exports=l}(i3);var i5=(g=i3.exports)&&g.__esModule&&Object.prototype.hasOwnProperty.call(g,"default")?g.default:g;let i8=eN()||{isTypeSupported:()=>!1};class i6{constructor(e,t,i,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 s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;const a=(e,t)=>{(t=t||{}).frag=this.frag,t.id=this.id,e===S.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new i5,this.observer.on(S.FRAG_DECRYPTED,a),this.observer.on(S.ERROR,a);const n={mp4:i8.isTypeSupported("video/mp4"),mpeg:i8.isTypeSupported("audio/mpeg"),mp3:i8.isTypeSupported('audio/mp4; codecs="mp3"')},l=navigator.vendor;if(this.useWorker&&"u">typeof Worker&&(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__)){try{s.workerPath?(k.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){let t=new self.URL(e,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}(s.workerPath)):(k.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){let e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e);return{worker:new self.Worker(t),objectURL:t}}()),this.onwmsg=e=>this.onWorkerMessage(e);const{worker:e}=this.workerContext;e.addEventListener("message",this.onwmsg),e.onerror=e=>{let i=Error(`${e.message} (${e.filename}:${e.lineno})`);s.enableWorker=!1,k.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(S.ERROR,{type:L.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:i})}
1,e.postMessage({cmd:"init",typeSupported:n,vendor:l,id:t,config:JSON.stringify(s)})}catch(e){k.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new iZ(this.observer,n,s,l,t)}return}this.transmuxer=new iZ(this.observer,n,s,l,t)}resetWorker(){if(this.workerContext){let{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{let e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,i,r,s,a,n,l,o,h){var d,u;o.transmuxing.start=self.performance.now();let{transmuxer:c}=this,f=a?a.start:s.start,g=s.decryptdata,m=this.frag,p=!(m&&s.cc===m.cc),y=!(m&&o.level===m.level),T=m?o.sn-m.sn:-1,E=this.part?o.part-this.part.index:-1,v=0===T&&o.id>1&&o.id===(null==m?void 0:m.stats.chunkCount),S=!y&&(1===T||0===T&&(1===E||v&&E<=0)),L=self.performance.now();(y||T||0===s.stats.parsing.start)&&(s.stats.parsing.start=L),a&&(E||!S)&&(a.stats.parsing.start=L);let R=!(m&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=m.initSegment)?void 0:u.url)),A=new i4(p,S,l,y,f,R);if(!S||p||R){k.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${o.sn} p: ${o.part} level: ${o.level} id: ${o.id} 2 discontinuity: ${p} 3 trackSwitch: ${y} 4 contiguous: ${S} 5 accurateTimeOffset: ${l} 6 timeOffset: ${f} 7 initSegmentChange: ${R}`);let e=new i2(i,r,t,n,h);this.configureTransmuxer(e)}if(this.frag=s,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:g,chunkMeta:o,state:A},e instanceof ArrayBuffer?[e]:[]);else if(c){let t=c.push(e,g,o,A);i1(t)?(c.async=!0,t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,o,"transmuxer-interface push error")})):(c.async=!1,this.handleTransmuxComplete(t))}}flush(e){e.transmuxing.start=self.performance.now();let{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let i=t.flush(e);i1(i)||t.async?(i1(i)||(i=Promise.resolve(i)),i.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")})):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}onWorkerMessage(e){let t=e.data,i=this.hls;switch(t.event){case"init":{var r;let e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":k[t.data.logType]&&k[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data)}}configureTransmuxer(e){let{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class i9{constructor(e,t,i,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=e,this.media=t,this.fragmentTracker=i,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){let{config:i,media:r,stalled:s}=this;if(null===r)return;let{currentTime:a,seeking:n}=r,l=this.seeking&&!n,o=!this.seeking&&n;if(this.seeking=n,a!==e){if(this.moved=!0,null!==s){if(this.stallReported){let e=self.performance.now()-s;k.warn(`playback not stuck anymore @${a}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(o||l){this.stalled=null;return}if(r.paused&&!n||r.ended||0===r.playbackRate||!tW.getBuffered(r).length)return;let h=tW.bufferInfo(r,a,0),d=h.len>0,u=h.nextStart||0;if(!d&&!u)return;if(n){let e=h.len>2,i=!u||t&&t.start<=a||u-a>2&&!this.fragmentTracker.getPartialFragment(a);if(e||i)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var c;
7let e=Math.max(u,h.start||0)-a,t=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,i=(null==t||null==(c=t.details)?void 0:c.live)?2*t.details.targetduration:2,r=this.fragmentTracker.getPartialFragment(a);if(e>0&&(e<=i||r))return void this._trySkipBufferHole(r)}let f=self.performance.now();if(null===s){this.stalled=f;return}let g=f-s;if(!n&&g>=250&&(this._reportStall(h),!this.media))return;let m=tW.bufferInfo(r,a,i.maxBufferHole);this._tryFixBufferStall(m,g)}_tryFixBufferStall(e,t){let{config:i,fragmentTracker:r,media:s}=this;if(null===s)return;let a=s.currentTime,n=r.getPartialFragment(a);!(n&&(this._trySkipBufferHole(n)||!this.media))&&(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-a<i.maxBufferHole)&&t>1e3*i.highBufferWatchdogPeriod&&(k.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){let{hls:t,media:i,stallReported:r}=this;if(!r&&i){this.stallReported=!0;let r=Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);k.warn(r.message),t.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}
7_trySkipBufferHole(e){let{config:t,hls:i,media:r}=this;if(null===r)return 0;let s=r.currentTime,a=tW.bufferInfo(r,s,0),n=s<a.start?a.start:a.nextStart;if(n){let l=a.len<=t.maxBufferHole,o=a.len>0&&a.len<1&&r.readyState<3,h=n-s;if(h>0&&(l||o)){if(h>t.maxBufferHole){let{fragmentTracker:t}=this,i=!1;if(0===s){let e=t.getAppendedFrag(0,e4);e&&n<e.end&&(i=!0)}if(!i){let i=e||t.getAppendedFrag(s,e4);if(i){let e=!1,r=i.end;for(;r<n;){let i=t.getPartialFragment(r);if(i)r+=i.duration;else{e=!0;break}}if(e)return 0}}}let a=Math.max(n+.05,s+.1);if(k.warn(`skipping hole, adjusting currentTime from ${s} to ${a}`),this.moved=!0,this.stalled=null,r.currentTime=a,e&&!e.gap){let t=Error(`fragment loaded with buffer holes, seeking from ${s} to ${a}`);i.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:t,reason:t.message,frag:e})}return a}}return 0}_tryNudgeBuffer(){let{config:e,hls:t,media:i,nudgeRetry:r}=this;if(null===i)return;let s=i.currentTime;if(this.nudgeRetry++,r<e.nudgeMaxRetry){let a=s+(r+1)*e.nudgeOffset,n=Error(`Nudging 'currentTime' from ${s} to ${a}`);k.warn(n.message),i.currentTime=a,t.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.BUFFER_NUDGE_ON_STALL,error:n,fatal:!1})}else{let i=Error(`Playhead still not moving while enough data buffered @${s} after ${e.nudgeMaxRetry} nudges`);k.error(i.message),t.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:i,fatal:!0})}}}class i7 extends ia{constructor(e,t,i){super(e,t,i,"[stream-controller]",e4),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(){let{hls:e}=this;e.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_PARSED,this.onManifestParsed,this),e.on(S.LEVEL_LOADING,this.onLevelLoading,this),e.on(S.LEVEL_LOADED,this.onLevelLoaded,this),e.on(S.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(S.ERROR,this.onError,this),e.on(S.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(S.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(S.BUFFER_CREATED,this.onBufferCreated,this),e.on(S.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(S.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(S.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_PARSED,this.onManifestParsed,this),e.off(S.LEVEL_LOADED,this.onLevelLoaded,this),e.off(S.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(S.ERROR,this.onError,this),e.off(S.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(S.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(S.BUFFER_CREATED,this.onBufferCreated,this),e.off(S.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(S.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(S.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}startLoad(e){if(this.levels){let{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=i.startLevel;-1===e&&(i.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=i.nextAutoLevel),this.level=i.nextLoadLevel=e,this.loadedmetadata=!1}t>0&&-1===e&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=t3,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=t4}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){var e,t;switch(this.state){case is:{let{levels:t,level:i}=this,r=null==t||null==(e=t[i])?void 0:e.details;if(r&&(!r.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(r))break;this.state=t3}else this.hls.nextLoadLevel!==this.level&&(this.state=t3);break}case t6:{let e=self.performance.now(),i=this.retryDate;(!i||e>=i||null!=(t=this.media)&&t.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=t3)}}this.state===t3&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this,{config:s,nextLoadLevel:a}=e;if(null===t||!r&&(this.startFragRequested||!s.startFragPrefetch)||this.altAudio&&this.audioOnly||!(null!=i&&i[a]))return;let n=i[a],l=this.getMainFwdBufferInfo();if(null===l)return;let o=this.getLevelDetails();if(o&&this._streamEnded(l,o)){let e={};this.altAudio&&(e.type="video"),this.hls.trigger(S.BUFFER_EOS,e),this.state=it;return}e.loadLevel!==a&&-1===e.manualLevel&&this.log(`Adapting to level ${a} from level ${this.level}`),this.level=e.nextLoadLevel=a;let h=n.details;if(!h||this.state===is||h.live&&this.levelLastLoaded!==a){this.level=a,this.state=is;return}let d=l.len,u=this.getMaxBufferLength(n.maxBitrate);
7if(d>=u)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);let c=this.backtrackFragment?this.backtrackFragment.start:l.end,f=this.getNextFragment(c,h);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&"OK"!==this.fragmentTracker.getState(f)){var g;let e=(null!=(g=this.backtrackFragment)?g:f).sn-h.startSN,t=h.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){let e=this.audioOnly&&!this.altAudio?P:F,t=(e===F?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,e4)}f=this.getNextFragmentLoopLoading(f,h,l,e4,u)}f&&(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,n,c))}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===tx||r===tF?"initSegment"===e.sn?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,e4)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,1/0)}nextLevelSwitch(){let{levels:e,media:t}=this;if(null!=t&&t.readyState){let i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let s=this.getLevelDetails();if(null!=s&&s.live){let e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){let t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else i=0;let a=this.getBufferedFrag(t.currentTime+i);if(a){let e=this.followingBufferedFrag(a);if(e){this.abortCurrentFrag();let t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,r=Math.max(a.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,.5*i),.75*i));this.flushMainBuffer(r,1/0)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case t5:case t8:case t6:case t7:case ie:this.state=t3}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new i9(this.config,i,this.fragmentTracker,this.hls)}onMediaDetaching(){let{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.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(){let e=this.media,t=e?e.currentTime:null;v(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);let i=this.getMainFwdBufferInfo();null===i||0===i.len?this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`):this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(S.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}onManifestParsed(e,t){var i;let r,s,a=!1,n=!1;t.levels.forEach(e=>{(s=e.audioCodec)&&(-1!==s.indexOf("mp4a.40.2")&&(a=!0),-1!==s.indexOf("mp4a.40.5")&&(n=!0))}),this.audioCodecSwitch=a&&n&&"function"!=typeof(null==(r=il())||null==(i=r.prototype)?void 0:i.changeType),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==t3)return;let r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(r.details))&&(this.state=is)}onLevelLoaded(e,t){var i;let{levels:r}=this,s=t.level,a=t.details,n=a.totalduration;if(!r)return void this.warn(`Levels were reset while loading level ${s}`);this.log(`Level ${s} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${n}`);let l=r[s],o=this.fragCurrent;o&&(this.state===t8||this.state===t6)&&(o.level!==t.level||o.urlId!==l.urlId)&&o.loader&&this.abortCurrentFrag();let h=0;if(a.live||null!=(i=l.details)&&i.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details)}if(l.details=a,this.levelLastLoaded=s,this.hls.trigger(S.LEVEL_UPDATED,{details:a,level:s}
7),this.state===is){if(this.waitForCdnTuneIn(a))return;this.state=t3}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,h),this.tick()}_handleFragmentLoadProgress(e){var t;let{frag:i,part:r,payload:s}=e,{levels:a}=this;if(!a)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);let n=a[i.level],l=n.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let o=n.videoCodec,h=l.PTSKnown||!l.live,d=null==(t=i.initSegment)?void 0:t.data,u=this._getAudioCodec(n),c=this.transmuxer=this.transmuxer||new i6(this.hls,e4,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=new tY(i.level,i.sn,i.stats.chunkCount,s.byteLength,f,-1!==f),m=this.initPTS[i.cc];c.push(s,d,u,o,i,r,l.totalduration,h,g,m)}onAudioTrackSwitching(e,t){let i=this.altAudio;if(!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();let e=this.hls;i&&(e.trigger(S.BUFFER_FLUSHING,{startOffset:0,endOffset:1/0,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(S.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=t.id,r=!!this.hls.audioTracks[i].url;if(r){let e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=r,this.tick()}onBufferCreated(e,t){let i,r,s=t.tracks,a=!1;for(let e in s){let t=s[e];if("main"===t.id){if(r=e,i=t,"video"===e){let t=s[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i&&i.type!==e4)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===ie&&(this.state=t3);return}let s=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),"initSegment"!==i.sn&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal){this.state=ii;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(e4,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==is||(null==(i=t.context)?void 0:i.type)!==e0||(this.state=t3);break;case R.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,1/0);break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}
7checkBuffer(){let{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!tW.getBuffered(e).length){let e=this.state!==t3?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=t3,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==P||this.audioOnly&&!this.altAudio){let e=(t===F?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,e4)}}onLevelsUpdated(e,t){this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log(`could not seek to ${i}, already seeking at ${t}`);let r=tW.getBuffered(e),s=(r.length?r.start(0):0)-i;s>0&&(s<this.config.maxBufferHole||s<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${s} to match buffer start`),i+=s,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{let{hls:r}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=t3,this.startFragRequested=!1,this.bitrateTest=!1;let s=e.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),r.trigger(S.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;let i="main",{hls:r}=this,{remuxResult:s,chunkMeta:a}=e,n=this.getCurrentContext(a);if(!n)return void this.resetWhenMissingContext(a);let{frag:l,part:o,level:h}=n,{video:d,text:u,id3:c,initSegment:f}=s,{details:g}=h,m=this.altAudio?void 0:s.audio;if(this.fragContextChanged(l))return void this.fragmentTracker.removeFragment(l);if(this.state=t7,f){if(null!=f&&f.tracks){let e=l.initSegment||l;this._bufferInitSegment(h,f.tracks,e,a),r.trigger(S.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:f.tracks})}let e=f.initPTS,t=f.timescale;v(e)&&(this.initPTS[l.cc]={baseTime:e,timescale:t},r.trigger(S.INIT_PTS_FOUND,{frag:l,id:i,initPTS:e,timescale:t}))}if(d&&g&&"initSegment"!==l.sn){let e=g.fragments[l.sn-1-g.startSN],t=l.sn===g.startSN,i=!e||l.cc>e.cc;if(!1!==s.independent){let{startPTS:e,endPTS:r,startDTS:s,endDTS:n}=d;if(o)o.elementaryStreams[d.type]={startPTS:e,endPTS:r,startDTS:s,endDTS:n};else if(d.firstKeyFrame&&d.independent&&1===a.id&&!i&&(this.couldBacktrack=!0),d.dropped&&d.independent){let s=this.getMainFwdBufferInfo(),a=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,o=d.firstKeyFramePTS?d.firstKeyFramePTS:e;if(!t&&a<o-this.config.maxBufferHole&&!i)return void this.backtrack(l);i&&(l.gap=!0),l.setElementaryStreamInfo(d.type,l.start,r,l.start,n,!0)}l.setElementaryStreamInfo(d.type,e,r,s,n),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(d,l,o,a,t||i)}else{if(!t&&!i)return void this.backtrack(l);l.gap=!0}}if(m){let{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=m;o&&(o.elementaryStreams[P]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),l.setElementaryStreamInfo(P,e,t,i,r),this.bufferFragmentData(m,l,o,a)}if(g&&null!=c&&null!=(t=c.samples)&&t.length){let e={id:i,frag:l,details:g,samples:c.samples};r.trigger(S.FRAG_PARSING_METADATA,e)}if(g&&u){let e={id:i,frag:l,details:g,samples:u.samples};r.trigger(S.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,i,r){if(this.state!==t7)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;let{audio:s,video:a,audiovideo:n}=t;if(s){let t=e.audioCodec,i=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(t&&(t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),1!==s.metadata.channelCount&&-1===i.indexOf("firefox")&&(t="mp4a.40.5")),-1!==i.indexOf("android")&&"audio/mpeg"!==s.container&&(t="mp4a.40.2",this.log(`Android: force audio codec to ${t}`)),e.audioCodec&&e.audioCodec!==t&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${t}"`),s.levelCodec=t,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${t||""}/${e.audioCodec||""}/${s.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),n&&this.log(`Init audiovideo buffer, container:${n.container}, codecs[level/parsed]=[${e.attrs.CODECS||""}/${n.codec}]`),this.hls.trigger(S.BUFFER_CODECS,t),Object.keys(t).forEach(e
7=>{let s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(S.BUFFER_APPENDING,{type:e,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,e4)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=t3}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){let i=e.currentTime;if(tW.isBuffered(e,i)?t=this.getAppendedFrag(i):tW.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let e=this.fragPlaying,i=t.level;(!e||t.sn!==e.sn||e.level!==i||t.urlId!==e.urlId)&&(this.fragPlaying=t,this.hls.trigger(S.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(S.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){let e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){let e=this.media;if(e){let t=e.currentTime,i=this.currentFrag;if(i&&v(t)&&v(i.programDateTime))return new Date(i.programDateTime+(t-i.start)*1e3)}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class re{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class rt{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_
7=new re(e),this.fast_=new re(t),this.defaultTTFB_=r,this.ttfb_=new re(e)}update(e,t){let{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==e&&(this.slow_=new re(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new re(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new re(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){let i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){let t=Math.sqrt(2)*Math.exp(-Math.pow(e/1e3,2)/2);this.ttfb_.sample(t,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}class ri{constructor(e){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=e;const t=e.config;this.bwEstimator=new rt(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(S.FRAG_LOADING,this.onFragLoading,this),e.on(S.FRAG_LOADED,this.onFragLoaded,this),e.on(S.FRAG_BUFFERED,this.onFragBuffered,this),e.on(S.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(S.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){let{hls:e}=this;e.off(S.FRAG_LOADING,this.onFragLoading,this),e.off(S.FRAG_LOADED,this.onFragLoaded,this),e.off(S.FRAG_BUFFERED,this.onFragBuffered,this),e.off(S.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(S.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(e,t){var i;let r=t.frag;this.ignoreFragment(r)||(this.fragCurrent=r,this.partCurrent=null!=(i=t.part)?i:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(e,t){this.clearTimer()}getTimeToLoadFrag(e,t,i,r){return e+i/t+(r?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){let i=this.hls.config,{total:r,bwEstimate:s}=t.stats;v(r)&&v(s)&&(this.lastLevelLoadSec=8*r/s),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}_abandonRulesCheck(){let e,{fragCurrent:t,partCurrent:i,hls:r}=this,{autoLevelEnabled:s,media:a}=r;if(!t||!a)return;let n=performance.now(),l=i?i.stats:t.stats,o=i?i.duration:t.duration,h=n-l.loading.start;if(l.aborted||l.loaded&&l.loaded===l.total||0===t.level){this.clearTimer(),this._nextAutoLevel=-1;return}if(!s||a.paused||!a.playbackRate||!a.readyState)return;let d=r.mainForwardBufferInfo;if(null===d)return;let u=this.bwEstimator.getEstimateTTFB(),c=Math.abs(a.playbackRate);if(h<=Math.max(u,o/(2*c)*1e3))return;let f=d.len/c;if(f>=2*o/c)return;let g=l.loading.first?l.loading.first-l.loading.start:-1,m=l.loaded&&g>-1,p=this.bwEstimator.getEstimate(),{levels:y,minAutoLevel:T}=r,E=y[t.level],L=l.total||Math.max(l.loaded,Math.round(o*E.maxBitrate/8)),R=h-g;R<1&&m&&(R=Math.min(h,8*l.loaded/p));let A=m?1e3*l.loaded/R:0,b=A?(L-l.loaded)/A:8*L/p+u/1e3;if(b<=f)return;let D=A?8*A:p,I=1/0;for(e=t.level-1;e>T;e--){let t=y[e].maxBitrate;if((I=this.getTimeToLoadFrag(u/1e3,D,o*t,!y[e].details))<f)break}I>=b||I>10*o||(r.nextLoadLevel=e,m?this.bwEstimator.sample(h-Math.min(u,g),l.loaded):this.bwEstimator.sampleTTFB(h),this.clearTimer(),k.warn(`[abr] Fragment ${t.sn}${i?" part "+i.index:""} of level ${t.level} is loading too slowly; 8 Time to underbuffer: ${f.toFixed(3)} s 9 Estimated load time for current fragment: ${b.toFixed(3)} s 10 Estimated load time for down switch fragment: ${I.toFixed(3)} s 11 TTFB estimate: ${g} 12 Current BW estimate: ${v(p)?(p/1024).toFixed(3):"Unknown"} Kb/s 13 New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s 14 Aborting and switching to level ${e}`),t.loader&&(this.fragCurrent=this.partCurrent=null,t.abortRequests()),r.trigger(S.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:i,stats:l}))}onFragLoaded(e,{frag:t,part:i}
14){let r=i?i.stats:t.stats;if(t.type===e4&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),this.lastLoadedFragLevel=t.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){let e=i?i.duration:t.duration,s=this.hls.levels[t.level],a=(s.loaded?s.loaded.bytes:0)+r.loaded,n=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:a,duration:n},s.realBitrate=Math.round(8*a/n)}if(t.bitrateTest){let e={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(S.FRAG_BUFFERED,e),t.bitrateTest=!1}}}onFragBuffered(e,t){let{frag:i,part:r}=t,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(s.aborted||this.ignoreFragment(i))return;let a=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,s.loaded),s.bwEstimate=this.bwEstimator.getEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==e4||"initSegment"===e.sn}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){let e=this._nextAutoLevel,t=this.bwEstimator;if(-1!==e&&!t.canEstimate())return e;let i=this.getNextABRAutoLevel();if(-1!==e){let t=this.hls.levels;if(t.length>Math.max(e,i)&&t[e].loadError<=t[i].loadError)return e}return -1!==e&&(i=Math.min(e,i)),i}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this,{maxAutoLevel:r,config:s,minAutoLevel:a,media:n}=i,l=t?t.duration:e?e.duration:0,o=n&&0!==n.playbackRate?Math.abs(n.playbackRate):1,h=this.bwEstimator?this.bwEstimator.getEstimate():s.abrEwmaDefaultEstimate,d=i.mainForwardBufferInfo,u=(d?d.len:0)/o,c=this.findBestLevel(h,a,r,u,s.abrBandWidthFactor,s.abrBandWidthUpFactor);if(c>=0)return c;k.trace(`[abr] ${u?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let f=l?Math.min(l,s.maxStarvationDelay):s.maxStarvationDelay,g=s.abrBandWidthFactor,m=s.abrBandWidthUpFactor;if(!u){let e=this.bitrateTestDelay;e&&(f=(l?Math.min(l,s.maxLoadingDelay):s.maxLoadingDelay)-e,k.trace(`[abr] bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*f)} ms`),g=m=1)}return Math.max(c=this.findBestLevel(h,a,r,u+f,g,m),0)}findBestLevel(e,t,i,r,s,a){var n;let{fragCurrent:l,partCurrent:o,lastLoadedFragLevel:h}=this,{levels:d}=this.hls,u=d[h],c=!!(null!=u&&null!=(n=u.details)&&n.live),f=null==u?void 0:u.codecSet,g=o?o.duration:l?l.duration:0,m=this.bwEstimator.getEstimateTTFB()/1e3,p=t,y=-1;for(let n=i;n>=t;n--){let t,i=d[n];if(!i||f&&i.codecSet!==f){i&&(p=Math.min(n,p),y=Math.max(n,y));continue}-1!==y&&k.trace(`[abr] Skipped level(s) ${p}-${y} with CODECS:"${d[y].attrs.CODECS}"; not compatible with "${u.attrs.CODECS}"`);let l=i.details,T=(o?null==l?void 0:l.partTarget:null==l?void 0:l.averagetargetduration)||g;t=n<=h?s*e:a*e;let E=d[n].maxBitrate,S=this.getTimeToLoadFrag(m,t,E*T,void 0===l);if(k.trace(`[abr] level:${n} adjustedbw-bitrate:${Math.round(t-E)} avgDuration:${T.toFixed(1)} maxFetchDuration:${r.toFixed(1)} fetchDuration:${S.toFixed(1)}`),t>E&&(0===S||!v(S)||c&&!this.bitrateTestDelay||S<r))return n}return -1}set nextAutoLevel(e){this._nextAutoLevel=e}}class rr{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let e,{chunks:t,dataLength:i}=this;return t.length?(e=1===t.length?t[0]:function(e,t){let i=new Uint8Array(t),r=0;for(let t=0;t<e.length;t++){let s=e[t];i.set(s,r),r+=s.length}return i}(t,i),this.reset(),e):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}class rs extends ia{constructor(e,t,i){super(e,t,i,"[audio-stream-controller]",e3),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(){let{hls:e}=this;e.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.LEVEL_LOADED,this.onLevelLoaded,this),e.on(S.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(S.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(S.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(S.ERROR,this.onError,this),e.on(S.BUFFER_RESET,this.onBufferReset,this),e.on(S.BUFFER_CREATED,this.onBufferCreated,this),e.on(S.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(S.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(S.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;
14e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.LEVEL_LOADED,this.onLevelLoaded,this),e.off(S.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(S.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(S.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(S.ERROR,this.onError,this),e.off(S.BUFFER_RESET,this.onBufferReset,this),e.off(S.BUFFER_CREATED,this.onBufferCreated,this),e.off(S.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(S.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(S.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s}){if("main"===i){let e=t.cc;this.initPTS[t.cc]={baseTime:r,timescale:s},this.log(`InitPTS for cc: ${e} found from main: ${r}`),this.videoTrackCC=e,this.state===ir&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=t4;return}let t=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),t>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=t3):(this.loadedmetadata=!1,this.state=t9),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){var e,t;switch(this.state){case t3:this.doTickIdle();break;case t9:{let{levels:t,trackId:i}=this,r=null==t||null==(e=t[i])?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=ir}break}case t6:{let e=performance.now(),i=this.retryDate;(!i||e>=i||null!=(t=this.media)&&t.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=t3);break}case ir:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:r,complete:s}=e;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=t8;let e={frag:t,part:i,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{let e=this.getLoadPosition(),i=tW.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);0>tD(i.end,this.config.maxFragLookUpTolerance,t)&&(this.log(`Waiting fragment cc (${t.cc}) @ ${t.start} cancelled because another fragment at ${i.end} is needed`),this.clearWaitingFragment())}}else this.state=t3}}this.onTickEnd()}clearWaitingFragment(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=t3)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){let{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){let{hls:e,levels:t,media:i,trackId:r}=this,s=e.config;if(!(null!=t&&t[r])||!i&&(this.startFragRequested||!s.startFragPrefetch))return;let a=t[r],n=a.details;if(!n||n.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(n)){this.state=t9;return}let l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,P,e3));let o=this.getFwdBufferInfo(l,e3);if(null===o)return;let{bufferedTrack:h,switchingTrack:d}=this;if(!d&&this._streamEnded(o,n)){e.trigger(S.BUFFER_EOS,{type:"audio"}),this.state=it;return}let u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,e4),c=o.len,f=this.getMaxBufferLength(null==u?void 0:u.len);if(c>=f&&!d)return;let g=n.fragments[0].start,m=o.end;if(d&&i){let e=this.getLoadPosition();h&&d.attrs!==h.attrs&&(m=e),n.PTSKnown&&e<g&&(o.end>g||o.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=g+.05)}let p=this.getNextFragment(m,n),y=!1;if(p&&this.isLoopLoading(p,m)&&(y=!!p.gap,p=this.getNextFragmentLoopLoading(p,n,o,e4,f)),!p){this.bufferFlushed=!0;return}let T=u&&p.start>u.end+n.targetduration;if(T||!(null!=u&&u.len)&&o.len){let e=this.getAppendedFrag(p.start,e4);if(null===e||(y||(y=!!e.gap||!!T&&0===u.len),T&&!y||y&&o.nextStart&&o.nextStart<e.end))return}this.loadFragment(p,a,m)}getMaxBufferLength(e){let t=super.getMaxBufferLength();
14return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new tc(e))}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?this.setInterval(100):this.resetTransmuxer(),i?(this.switchingTrack=t,this.state=t3):(this.switchingTrack=null,this.bufferedTrack=t,this.state=t4),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(S.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var i;if(null==this.mainDetails){this.cachedTrackLoadedData=t;return}let{levels:r}=this,{details:s,id:a}=t;if(!r)return void this.warn(`Audio tracks were reset while loading level ${a}`);this.log(`Track ${a} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);let n=r[a],l=0;if(s.live||null!=(i=n.details)&&i.live){this.checkLiveUpdate(s);let e=this.mainDetails;if(s.deltaUpdateFailed||!e)return;!n.details&&s.hasProgramDateTime&&e.hasProgramDateTime?(tQ(s,e),l=s.fragments[0].start):l=this.alignPlaylists(s,n.details)}n.details=s,this.levelLastLoaded=a,this.startFragRequested||!this.mainDetails&&s.live||this.setStartPosition(n.details,l),this.state!==t9||this.waitForCdnTuneIn(s)||(this.state=t3),this.tick()}_handleFragmentLoadProgress(e){var t;let{frag:i,part:r,payload:s}=e,{config:a,trackId:n,levels:l}=this;if(!l)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);let o=l[n];if(!o)return void this.warn("Audio track is undefined on fragment load progress");let h=o.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let d=a.defaultAudioCodec||o.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new i6(this.hls,e3,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let c=this.initPTS[i.cc],f=null==(t=i.initSegment)?void 0:t.data;if(void 0!==c){let e=r?r.index:-1,t=new tY(i.level,i.sn,i.stats.chunkCount,s.byteLength,e,-1!==e);u.push(s,f,d,"",i,r,h.totalduration,!1,t,c)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${n}`);let{cache:e}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new rr,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=ir}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i.type!==e3){if(!this.loadedmetadata&&i.type===e4){let e=this.videoBuffer||this.media;e&&tW.getBuffered(e).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(i))return void this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);if("initSegment"!==i.sn){this.fragPrevious=i;let e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(S.AUDIO_TRACK_SWITCHED,T({},e)))}this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal){this.state=ii;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(e3,t);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==t9||(null==(i=t.context)?void 0:i.type)!==e1||(this.state=t3);break;case R.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,1/0,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushed(e,{type:t}){t===P&&(this.bufferFlushed=!0,this.state===it&&(this.state=t3))}_handleTransmuxComplete(e){var t;let i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:a}=e,n=this.getCurrentContext(a);if(!n)return void this.resetWhenMissingContext(a);let{frag:l,part:o,level:h}=n,{details:d}=h,{audio:u,text:c,id3:f,initSegment:g}=s;if(this.fragContextChanged(l)||!d)return void this.fragmentTracker.removeFragment(l);
14if(this.state=t7,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){let e=l.initSegment||l;this._bufferInitSegment(g.tracks,e,a),r.trigger(S.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:g.tracks})}if(u){let{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=u;o&&(o.elementaryStreams[P]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),l.setElementaryStreamInfo(P,e,t,i,r),this.bufferFragmentData(u,l,o,a)}if(null!=f&&null!=(t=f.samples)&&t.length){let e=E({id:i,frag:l,details:d},f);r.trigger(S.FRAG_PARSING_METADATA,e)}if(c){let e=E({id:i,frag:l,details:d},c);r.trigger(S.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,i){if(this.state!==t7)return;e.video&&delete e.video;let r=e.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(S.BUFFER_CODECS,e);let s=r.initSegment;if(null!=s&&s.byteLength){let e={type:"audio",frag:t,part:null,chunkMeta:i,parent:t.type,data:s};this.hls.trigger(S.BUFFER_APPENDING,e)}this.tick()}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||r===tx||r===tF){var s;"initSegment"===e.sn?this._loadInitSegment(e,t):null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]?(this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=ir):(this.startFragRequested=!0,super.loadFragment(e,t,i))}else this.clearTrackerIfNeeded(e)}completeAudioSwitch(e){let{hls:t,media:i,bufferedTrack:r}=this,s=null==r?void 0:r.attrs,a=e.attrs;i&&s&&(s.CHANNELS!==a.CHANNELS||s.NAME!==a.NAME||s.LANGUAGE!==a.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,1/0,"audio")),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(S.AUDIO_TRACK_SWITCHED,T({},e))}}class ra extends tI{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_PARSED,this.onManifestParsed,this),e.on(S.LEVEL_LOADING,this.onLevelLoading,this),e.on(S.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(S.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(S.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_PARSED,this.onManifestParsed,this),e.off(S.LEVEL_LOADING,this.onLevelLoading,this),e.off(S.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(S.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(S.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(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:i,groupId:r,details:s}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r)return void this.warn(`Track with id:${i} and group:${r} not found in active group ${a.groupId}`);let n=a.details;a.details=t.details,this.log(`audio-track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,n)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!(null!=t&&t.audioGroupIds))return;let i=t.audioGroupIds[t.urlId];if(this.groupId!==i){this.groupId=i||null;let e=this.tracks.filter(e=>!i||e.groupId===i);this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=e,this.log(`Updating audio tracks, ${e.length} track(s) found in group:${i}`),this.hls.trigger(S.AUDIO_TRACKS_UPDATED,{audioTracks:e}),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(e,t){!t.fatal&&t.context&&t.context.type===e1&&t.context.
14id===this.trackId&&t.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(t))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn("Invalid id passed to audio-track controller");this.clearTimer();let i=this.currentTrack;t[this.trackId];let r=t[e],{groupId:s,name:a}=r;if(this.log(`Switching to audio-track ${e} "${a}" lang:${r.lang} group:${s}`),this.trackId=e,this.currentTrack=r,this.selectDefaultTrack=!1,this.hls.trigger(S.AUDIO_TRACK_SWITCHING,T({},r)),r.details&&!r.details.live)return;let n=this.switchParams(r.url,null==i?void 0:i.details);this.loadPlaylist(n)}selectInitialTrack(){let e=this.tracksInGroup,t=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(-1!==t)this.setAudioTrack(t);else{let t=Error(`No track found for running audio group-ID: ${this.groupId} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if((!this.selectDefaultTrack||r.default)&&(!e||void 0!==e.attrs["STABLE-RENDITION-ID"]&&e.attrs["STABLE-RENDITION-ID"]===r.attrs["STABLE-RENDITION-ID"]||e.name===r.name&&e.lang===r.lang))return r.id}return -1}loadPlaylist(e){super.loadPlaylist();let t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){let i=t.id,r=t.groupId,s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`loading audio-track playlist ${i} "${t.name}" lang:${t.lang} group:${r}`),this.clearTimer(),this.hls.trigger(S.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null})}}}function rn(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!function(e,t){let i=e["STABLE-RENDITION-ID"];return i?i===t["STABLE-RENDITION-ID"]:!["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED"].some(i=>e[i]!==t[i])}(e[i].attrs,t[i].attrs))return!1;return!0}class rl extends ia{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",e5),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){let{hls:e}=this;e.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.LEVEL_LOADED,this.onLevelLoaded,this),e.on(S.ERROR,this.onError,this),e.on(S.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(S.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(S.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(S.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(S.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(S.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.LEVEL_LOADED,this.onLevelLoaded,this),e.off(S.ERROR,this.onError,this),e.off(S.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(S.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(S.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(S.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(S.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(S.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=t3,this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let i,{frag:r,success:s}=t;if(this.fragPrevious=r,this.state=t3,!s)return;let a=this.tracksBuffered[this.currentTrackId];if(!a)return;let n=r.start;for(let e=0;e<a.length;e++)if(n>=a[e].start&&n<=a[e].end){i=a[e];break}let l=r.start+r.duration;i?i.end=l:(i={start:n,end:l},a.push(i)),this.fragmentTracker.fragBuffered(r)}onBufferFlushing(e,t){let{startOffset:i,endOffset:r}=t;if(0===i&&r!==1/0){let e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let i=0;i<t.length;){if(t[i].end<=e){t.shift();continue}if(t[i].start<e)t[i].start=e;else break;i++}}),this.fragmentTracker.removeFragmentsInRange(i,e,e5)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===e4){var i;null!=(i=this.media)&&i.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){let i=t.frag;(null==i?void 0:i.type)===e5&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==t4&&(this.state=t3))}
14onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(rn(this.levels,t)){this.levels=t.map(e=>new tc(e));return}this.tracksBuffered=[],this.levels=t.map(e=>{let t=new tc(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,1/0,e5),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){if(this.currentTrackId=t.id,!this.levels.length||-1===this.currentTrackId)return void this.clearInterval();let i=this.levels[this.currentTrackId];null!=i&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i;let{details:r,id:s}=t,{currentTrackId:a,levels:n}=this;if(!n.length)return;let l=n[a];if(s>=n.length||s!==a||!l)return;this.mediaBuffer=this.mediaBufferTimeRanges;let o=0;if(r.live||null!=(i=l.details)&&i.live){let e=this.mainDetails;if(r.deltaUpdateFailed||!e)return;let t=e.fragments[0];l.details?0===(o=this.alignPlaylists(r,l.details))&&t&&tp(r,o=t.start):r.hasProgramDateTime&&e.hasProgramDateTime?(tQ(r,e),o=r.fragments[0].start):t&&tp(r,o=t.start)}l.details=r,this.levelLastLoaded=s,this.startFragRequested||!this.mainDetails&&r.live||this.setStartPosition(l.details,o),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===t3&&(tb(null,r.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0))}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e,r=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>0&&r&&r.key&&r.iv&&"AES-128"===r.method){let e=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer).catch(e=>{throw s.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(i=>{let r=performance.now();s.trigger(S.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:r}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=t3})}}doTick(){if(!this.media){this.state=t3;return}if(this.state===t3){let{currentTrackId:e,levels:t}=this,i=t[e];if(!t.length||!i||!i.details)return;let{config:r}=this,s=this.getLoadPosition(),{end:a,len:n}=tW.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),l=this.getFwdBufferInfo(this.media,e4),o=i.details;if(n>this.getMaxBufferLength(null==l?void 0:l.len)+o.levelTargetDuration)return;let h=o.fragments,d=h.length,u=o.edge,c=null,f=this.fragPrevious;if(a<u){let e=r.maxFragLookUpTolerance;(c=tb(f,h,Math.max(h[0].start,a),a>u-e?0:e))||!f||!(f.start<h[0].start)||(c=h[0])}else c=h[d-1];if(!c)return;if("initSegment"!==(c=this.mapToInitFragWhenRequired(c)).sn){let e=h[c.sn-o.startSN-1];e&&e.cc===c.cc&&this.fragmentTracker.getState(e)===tx&&(c=e)}this.fragmentTracker.getState(c)===tx&&this.loadFragment(c,i,a)}}getMaxBufferLength(e){let t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,i){this.fragCurrent=e,"initSegment"===e.sn?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,i))}get mediaBufferTimeRanges(){return new ro(this.tracksBuffered[this.currentTrackId]||[])}}class ro{constructor(e){this.buffered=void 0;const t=(t,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}class rh extends tI{constructor(e){super(e,"[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(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){let{hls:e}=this;
vendor: 1,619 bytes, line 14
14e.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_PARSED,this.onManifestParsed,this),e.on(S.LEVEL_LOADING,this.onLevelLoading,this),e.on(S.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(S.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(S.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_PARSED,this.onManifestParsed,this),e.off(S.LEVEL_LOADING,this.onLevelLoading,this),e.off(S.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(S.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(S.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.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(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,e)}onMediaDetaching(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),rd(this.media.textTracks).forEac
14h(e=>{tt(e)}),this.subtitleTrack=-1,this.media=null)}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:i,details:r}=t,{trackId:s}=this,a=this.tracksInGroup[s];if(!a)return void this.warn(`Invalid subtitle track id ${i}`);let n=a.details;a.details=t.details,this.log(`subtitle track ${i} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,n)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!(null!=t&&t.textGroupIds))return;let i=t.textGroupIds[t.urlId],r=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==i){let e=this.tracks.filter(e=>!i||e.groupId===i);this.tracksInGroup=e;let t=this.findTrackId(null==r?void 0:r.name)||this.findTrackId();this.groupId=i||null,this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${i}" group-id`),this.hls.trigger(S.SUBTITLE_TRACKS_UPDATED,{subtitleTracks:e}),-1!==t&&this.setSubtitleTrack(t,r)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId,r)}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if((!this.selectDefaultTrack||r.default)&&(!e||e===r.name))return r.id}return -1}onError(e,t){!t.fatal&&t.context&&t.context.type===e2&&t.context.id===this.trackId&&t.context.groupId===this.groupId&&this.checkRetry(t)}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1;let t=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(e,t)}loadPlaylist(e){super.loadPlaylist();let t=this.tracksInGroup[this.trackId];if(this.shouldLoadPlaylist(t)){let i=t.id,r=t.groupId,s=t.url;if(e)try{s=e.addDirectives(s)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`Loading subtitle playlist for id ${i}`),this.hls.trigger(S.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null})}}toggleTrackModes(e){let{media:t,trackId:i}=this;if(!t)return;let r=rd(t.textTracks),s=r.filter(e=>e.groupId===this.groupId);if(-1===e)[].slice.call(r).forEach(e=>{e.mode="disabled"});else{let e=s[i];e&&(e.mode="disabled")}let a=s[e];a&&(a.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(e,t){var i;let r=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(this.trackId!==e&&this.toggleTrackModes(e),this.trackId===e&&(-1===e||null!=(i=r[e])&&i.details)||e<-1||e>=r.length)return;this.clearTimer();let s=r[e];if(this.log(`Switching to subtitle-track ${e}`+(s?` "${s.name}" lang:${s.lang} group:${s.groupId}`:"")),this.trackId=e,s){let{id:e,groupId:i="",name:r,type:a,url:n}=s;this.hls.trigger(S.SUBTITLE_TRACK_SWITCH,{id:e,groupId:i,name:r,type:a,url:n});let l=this.switchParams(s.url,null==t?void 0:t.details);this.loadPlaylist(l)}else this.hls.trigger(S.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1,t=rd(this.media.textTracks);for(let i=0;i<t.length;i++)if("hidden"===t[i].mode)e=i;else if("showing"===t[i].mode){e=i;break}this.subtitleTrack!==e&&(this.subtitleTrack=e)}}function rd(e){let t=[];for(let i=0;i<e.length;i++){let r=e[i];("subtitles"===r.kind||"captions"===r.kind)&&r.label&&t.push(e[i])}return t}class ru{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t){let i=this.queues[t];i.push(e),1===i.length&&this.buffers[t]&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t,i=new Promise(e=>{t=e}),r={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,e),i}executeNext(e){let{buffers:t,queues:i}=this,r=t[e],s=i[e];if(s.length){let t=s[0];try{t.execute()}catch(i){k.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),t.onError(i),null!=r&&r.updating||(s.shift(),this.executeNext(e))}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}let rc=eN(),rf=/([ha]vc.)(?:\.[^.,]+)+/;class rg{constructor(e){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=()=>{let{media:e,mediaSource:t}=this;k.log("[buffer-controller]: Media source opened"),e&&(e.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(S.MEDIA_ATTA
14CHED,{media:e})),t&&t.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{k.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{k.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{let{media:e,_objectUrl:t}=this;e&&e.src!==t&&k.error(`Media element src was set while attaching MediaSource (${t} > ${e.src})`)},this.hls=e,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){let{hls:e}=this;e.on(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_PARSED,this.onManifestParsed,this),e.on(S.BUFFER_RESET,this.onBufferReset,this),e.on(S.BUFFER_APPENDING,this.onBufferAppending,this),e.on(S.BUFFER_CODECS,this.onBufferCodecs,this),e.on(S.BUFFER_EOS,this.onBufferEos,this),e.on(S.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(S.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(S.FRAG_PARSED,this.onFragParsed,this),e.on(S.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){let{hls:e}=this;e.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_PARSED,this.onManifestParsed,this),e.off(S.BUFFER_RESET,this.onBufferReset,this),e.off(S.BUFFER_APPENDING,this.onBufferAppending,this),e.off(S.BUFFER_CODECS,this.onBufferCodecs,this),e.off(S.BUFFER_EOS,this.onBufferEos,this),e.off(S.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(S.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(S.FRAG_PARSED,this.onFragParsed,this),e.off(S.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new ru(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let i=2;(!t.audio||t.video)&&t.altAudio||(i=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,k.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){let i=this.media=t.media;if(i&&rc){let e=this.mediaSource=new rc;e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),i.src=self.URL.createObjectURL(e),this._objectUrl=i.src,i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){let{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(k.log("[buffer-controller]: media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(e){k.warn(`[buffer-controller]: onMediaDetaching: ${e.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(e.removeEventListener("emptied",this._onMediaEmptied),i&&self.URL.revokeObjectURL(i),e.src===i?(e.removeAttribute("src"),e.load()):k.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(S.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{let t=this.sourceBuffer[e];try{t&&(this.removeBufferListeners(e),this.mediaSource&&this.mediaSource.removeSourceBuffer(t),this.sourceBuffer[e]=void 0)}catch(t){k.warn(`[buffer-controller]: Failed to reset the ${e} buffer`,t)}}),this._initSourceBuffer()}onBufferCodecs(e,t){let i=this.getSourceBufferTypes().length;Object.keys(t).forEach(e=>{if(i){let i=this.tracks[e];if(i&&"function"==typeof i.buffer.changeType){let{id:r,codec:s,levelCodec:a,container:n,metadata:l}=t[e],o=(i.levelCodec||i.codec).replace(rf,"$1"),h=(a||s).replace(rf,"$1");if(o!==h){let t=`${n};codecs=${a||s}`;this.appendChangeType(e,t),k.log(`[buffer-controller]: switching codec ${o} to ${h}`),this.tracks[e]={buffer:i.buffer,codec:s,container:n,levelCodec:a,metadata:l,id:r}}}}else this.pendingTracks[e]=t[e]}),!i&&(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())}appendChangeType(e,t){let{operationQueue:i}=this;i.append({execute:()=>{let r=this.sourceBuffer[e];r&&(k.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{k.warn(`[buffer-controller]: Failed to change ${e} SourceBuffer type`,t)}},e)}onBufferAppending(e,t){let{hls:i,operationQueue:r,tracks:s}=this,{data:a,type:n,frag:l,part:o,chunkMeta:h}=t,d=h.buffering[n],u=self.performance.now();d.start=u;let c=l.stats.buffering,f=o?o.stats.buffering:null;0===c.start&&(c.start=u),f&&0===f.start&&(f.start=u);let g=s.audio,m=!1;"audio"===n&&(null==g?void 0:g.container)==="audio/mpeg"&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);let p=l.start;r.append({execute:()=>{if(d.executeStart=self.performance.now(),m){let e=this.sourceBuffer[n];if(e){let t=p-e.timestampOffset;Math.abs(t)>=.1&&(k.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${p} (delta: ${t}) sn: ${l.sn}
14)`),e.timestampOffset=p)}}this.appendExecutor(a,n)},onStart:()=>{},onComplete:()=>{let e=self.performance.now();d.executeEnd=d.end=e,0===c.first&&(c.first=e),f&&0===f.first&&(f.first=e);let{sourceBuffer:t}=this,i={};for(let e in t)i[e]=tW.getBuffered(t[e]);this.appendError=0,this.hls.trigger(S.BUFFER_APPENDED,{type:n,frag:l,part:o,chunkMeta:h,parent:l.type,timeRanges:i})},onError:e=>{k.error(`[buffer-controller]: Error encountered while trying to append to the ${n} SourceBuffer`,e);let t={type:L.MEDIA_ERROR,parent:l.type,details:R.BUFFER_APPEND_ERROR,frag:l,part:o,chunkMeta:h,error:e,err:e,fatal:!1};e.code===DOMException.QUOTA_EXCEEDED_ERR?t.details=R.BUFFER_FULL_ERROR:(this.appendError++,t.details=R.BUFFER_APPEND_ERROR,this.appendError>i.config.appendErrorMaxRetry&&(k.error(`[buffer-controller]: Failed ${i.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),t.fatal=!0)),i.trigger(S.ERROR,t)}},n)}onBufferFlushing(e,t){let{operationQueue:i}=this,r=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(S.BUFFER_FLUSHED,{type:e})},onError:t=>{k.warn(`[buffer-controller]: Failed to remove from ${e} SourceBuffer`,t)}});t.type?i.append(r(t.type),t.type):this.getSourceBufferTypes().forEach(e=>{i.append(r(e),e)})}onFragParsed(e,t){let{frag:i,part:r}=t,s=[],a=r?r.elementaryStreams:i.elementaryStreams;a[M]?s.push("audiovideo"):(a[P]&&s.push("audio"),a[F]&&s.push("video"));let n=()=>{let e=self.performance.now();i.stats.buffering.end=e,r&&(r.stats.buffering.end=e);let t=r?r.stats:i.stats;this.hls.trigger(S.FRAG_BUFFERED,{frag:i,part:r,stats:t,id:i.type})};0===s.length&&k.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(n,s)}onFragChanged(e,t){this.flushBackBuffer()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((e,i)=>{let r=this.sourceBuffer[i];return r&&(!t.type||t.type===i)&&(r.ending=!0,r.ended||(r.ended=!0,k.log(`[buffer-controller]: ${i} sourceBuffer now EOS`))),e&&!!(!r||r.ended)},!0)&&(k.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(e=>{let t=this.sourceBuffer[e];t&&(t.ending=!1)});let{mediaSource:e}=this;if(!e||"open"!==e.readyState){e&&k.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`);return}k.log("[buffer-controller]: Calling mediaSource.endOfStream()"),e.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){let{hls:e,details:t,media:i,sourceBuffer:r}=this;if(!i||null===t)return;let s=this.getSourceBufferTypes();if(!s.length)return;let a=t.live&&null!==e.config.liveBackBufferLength?e.config.liveBackBufferLength:e.config.backBufferLength;if(!v(a)||a<0)return;let n=i.currentTime,l=t.levelTargetDuration,o=Math.max(a,l),h=Math.floor(n/l)*l-o;s.forEach(i=>{let s=r[i];if(s){let r=tW.getBuffered(s);if(r.length>0&&h>r.start(0)){if(e.trigger(S.BACK_BUFFER_REACHED,{bufferEnd:h}),t.live)e.trigger(S.LIVE_BACK_BUFFER_REACHED,{bufferEnd:h});else if(s.ended&&r.end(r.length-1)-n<2*l)return void k.info(`[buffer-controller]: Cannot flush ${i} back buffer while SourceBuffer is in ended state`);e.trigger(S.BUFFER_FLUSHING,{startOffset:0,endOffset:h,type:i})}}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;let{details:e,hls:t,media:i,mediaSource:r}=this,s=e.fragments[0].start+e.totalduration,a=i.duration,n=v(r.duration)?r.duration:0;e.live&&t.config.liveDurationInfinity?(k.log("[buffer-controller]: Media Source duration is set to Infinity"),r.duration=1/0,this.updateSeekableRange(e)):(s>n&&s>a||!v(a))&&(k.log(`[buffer-controller]: Updating Media Source duration to ${s.toFixed(3)}`),r.duration=s)}updateSeekableRange(e){let t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&null!=t&&t.setLiveSeekableRange){let r=Math.max(0,i[0].start),s=Math.max(r,r+e.totalduration);t.setLiveSeekableRange(r,s)}}checkPendingTracks(){let{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,r=Object.keys(i).length;if(r&&!e||2===r){this.createSourceBuffers(i),this.pendingTracks={};let e=this.getSourceBufferTypes();if(e.length)this.hls.trigger(S.BUFFER_CREATED,{tracks:this.tracks}
14),e.forEach(e=>{t.executeNext(e)});else{let e=Error("could not create source buffer for media codec(s)");this.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}}createSourceBuffers(e){let{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(let r in e)if(!t[r]){let s=e[r];if(!s)throw Error(`source buffer exists for track ${r}, however track does not`);let a=s.levelCodec||s.codec,n=`${s.container};codecs=${a}`;k.log(`[buffer-controller]: creating sourceBuffer(${n})`);try{let e=t[r]=i.addSourceBuffer(n);this.addBufferListener(r,"updatestart",this._onSBUpdateStart),this.addBufferListener(r,"updateend",this._onSBUpdateEnd),this.addBufferListener(r,"error",this._onSBUpdateError),this.tracks[r]={buffer:e,codec:a,container:s.container,levelCodec:s.levelCodec,metadata:s.metadata,id:s.id}}catch(e){k.error(`[buffer-controller]: error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:n})}}}_onSBUpdateStart(e){let{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){let{operationQueue:t}=this;t.current(e).onComplete(),t.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){let i=Error(`${e} SourceBuffer error`);k.error(`[buffer-controller]: ${i}`,t),this.hls.trigger(S.ERROR,{type:L.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,error:i,fatal:!1});let r=this.operationQueue.current(e);r&&r.onError(t)}removeExecutor(e,t,i){let{media:r,mediaSource:s,operationQueue:a,sourceBuffer:n}=this,l=n[e];if(!r||!s||!l){k.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(e);return}let o=v(r.duration)?r.duration:1/0,h=v(s.duration)?s.duration:1/0,d=Math.max(0,t),u=Math.min(i,o,h);u>d&&!l.ending?(l.ended=!1,k.log(`[buffer-controller]: Removing [${d},${u}] from the ${e} SourceBuffer`),l.remove(d,u)):a.shiftAndExecuteNext(e)}appendExecutor(e,t){let{operationQueue:i,sourceBuffer:r}=this,s=r[t];if(!s){k.warn(`[buffer-controller]: Attempting to append to the ${t} SourceBuffer, but it does not exist`),i.shiftAndExecuteNext(t);return}s.ended=!1,s.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){k.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}let{operationQueue:i}=this;Promise.all(t.map(e=>i.appendBlocker(e))).then(()=>{e(),t.forEach(e=>{let t=this.sourceBuffer[e];null!=t&&t.updating||i.shiftAndExecuteNext(e)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){let r=this.sourceBuffer[e];if(!r)return;let s=i.bind(this,e);this.listeners[e].push({event:t,listener:s}),r.addEventListener(t,s)}removeBufferListeners(e){let t=this.sourceBuffer[e];t&&this.listeners[e].forEach(e=>{t.removeEventListener(e.event,e.listener)})}}let rm={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},rp=function(e){let t=e;return rm.hasOwnProperty(e)&&(t=rm[e]),String.fromCharCode(t)},ry={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rT={17:2,18:4,21:6,22:8,23:10,19:13,20:15},rE={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},rv={25:2,26:4,29:6,30:8,31:10,27:13,28:15},rS=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class rL{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let i="function"==typeof t?t():t;k.log(`${this.time} [${e}] ${i}`)}}}let rR=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class rA{constructor(e,t,i,r,s){this.foreground=void 0,this.underline=void 0,this.italics=void 0,this.background=void 0,this.flash=void 0,this.foreground=e||"white",this.underline=t||!1,this.italics=i||!1,this.background=r||"black",this.flash=s||!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){let t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){let r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class rb{constructor(e,t,i,r,s,a){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new rA(t,i,r,s,a)}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class rD{constructor(e){this.chars=void 0,this.pos=void 0,this.currPenState=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chars=[];for(let e=0;e<100;e++)this.chars.push(new rb);this.logger=e,this.pos=0,this.currPenState=new rA}equals(e){let t=!0;for(let i=0;i<100;i++)if(!this.chars[i].equals(e.chars[i])){t=!1;break}return t}copy(e){for(let t=0;t<100;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<100;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}
14setCursor(e){this.pos!==e&&(this.pos=e),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(e){let t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=rp(e);this.pos>=100?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<100;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let i=0;i<100;i++){let r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class rk{constructor(e){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(let t=0;t<15;t++)this.rows.push(new rD(e));this.logger=e,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<15;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let i=0;i<15;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<15;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<15;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+JSON.stringify(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<15;e++)this.rows[e].clear();let e=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){let r=i.rows[e].cueStartTime,s=this.logger.time;if(r&&null!==s&&r<s)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(i.rows[e+r])}}this.currRow=t;let i=this.rows[this.currRow];if(null!==e.indent){let t=Math.max(e.indent-1,0);i.setCursor(e.indent),e.color=i.chars[t].penState.foreground}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;let t=[],i="",r=-1;for(let i=0;i<15;i++){let s=this.rows[i].getTextString();s&&(r=i+1,e?t.push("Row "+r+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class rI{constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new rk(i),this.nonDisplayedMemory=new rk(i),this.lastOutputScreen=new rk(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),("MODE_PAINT-ON"===this.mode||"MODE_ROLL-UP"===this.mode)&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}
14ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};(t.underline=e%2==1,t.italics=e>=46,t.italics)?t.foreground="white":t.foreground=["white","green","blue","cyan","red","yellow","magenta"][Math.floor(e/2)-16],this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&!this.displayedMemory.isEmpty()&&(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e)}}class rC{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const r=new rL;this.channels=[null,new rI(e,t,r),new rI(e+1,i,r)],this.cmdHistory=rx(),this.logger=r}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let i,r,s,a=!1;this.logger.time=e;for(let e=0;e<t.length;e+=2)if(r=127&t[e],s=127&t[e+1],0!==r||0!==s){if(this.logger.log(3,"["+rR([t[e],t[e+1]])+"] -> ("+rR([r,s])+")"),(i=this.parseCmd(r,s))||(i=this.parseMidrow(r,s)),i||(i=this.parsePAC(r,s)),i||(i=this.parseBackgroundAttributes(r,s)),!i&&(a=this.parseChars(r,s))){let e=this.currentChannel;e&&e>0?this.channels[e].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}i||a||this.logger.log(2,"Couldn't parse cleaned data "+rR([r,s])+" orig: "+rR([t[e],t[e+1]]))}}parseCmd(e,t){let{cmdHistory:i}=this,r=(20===e||28===e||21===e||29===e)&&t>=32&&t<=47,s=(23===e||31===e)&&t>=33&&t<=35;if(!(r||s))return!1;if(rw(e,t,i))return r_(null,null,i),this.logger.log(3,"Repeated command ("+rR([e,t])+") is dropped"),!0;let a=20===e||21===e||23===e?1:2,n=this.channels[a];return 20===e||21===e||28===e||29===e?32===t?n.ccRCL():33===t?n.ccBS():34===t?n.ccAOF():35===t?n.ccAON():36===t?n.ccDER():37===t?n.ccRU(2):38===t?n.ccRU(3):39===t?n.ccRU(4):40===t?n.ccFON():41===t?n.ccRDC():42===t?n.ccTR():43===t?n.ccRTD():44===t?n.ccEDM():45===t?n.ccCR():46===t?n.ccENM():47===t&&n.ccEOC():n.ccTO(t-32),r_(e,t,i),this.currentChannel=a,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if((i=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,"MIDROW ("+rR([e,t])+")"),!0)}return!1}parsePAC(e,t){let i,r=this.cmdHistory,s=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,a=(16===e||24===e)&&t>=64&&t<=95;if(!(s||a))return!1;if(rw(e,t,r))return r_(null,null,r),!0;let n=e<=23?1:2;i=t>=64&&t<=95?1===n?ry[e]:rE[e]:1===n?rT[e]:rv[e];let l=this.channels[n];return!!l&&(l.setPAC(this.interpretPAC(i,t)),r_(e,t,r),this.currentChannel=n,!0)}interpretPAC(e,t){let i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return r.underline=(1&(i=t>95?t-96:t-64))==1,i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(e,t){let i,r=null,s=null;if(e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,"Special char '"+rp(e)+"' in channel "+i),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);if(r){let i=rR(r);this.logger.log(3,"Char codes = "+i.join(",")),r_(e,t,this.cmdHistory)}return r}
14parseBackgroundAttributes(e,t){let i=(16===e||24===e)&&t>=32&&t<=47,r=(23===e||31===e)&&t>=45&&t<=47;if(!(i||r))return!1;let s={};16===e||24===e?(s.background=rS[Math.floor((t-32)/2)],t%2==1&&(s.background=s.background+"_semi")):45===t?s.background="transparent":(s.foreground="black",47===t&&(s.underline=!0));let a=e<=23?1:2;return this.channels[a].setBkgData(s),r_(e,t,this.cmdHistory),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}this.cmdHistory=rx()}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function r_(e,t,i){i.a=e,i.b=t}function rw(e,t,i){return i.a===e&&i.b===t}function rx(){return{a:null,b:null}}class rP{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var rF=function(){if("u">typeof self&&self.VTTCue)return self.VTTCue;let e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t||!Array.isArray(e))return!1;let i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){let t=1;for(;t<arguments.length;t++){let i=arguments[t];for(let t in i)e[t]=i[t]}return e}function s(s,a,n){let l={enumerable:!0};this.hasBeenReset=!1;let o="",h=!1,d=s,u=a,c=n,f=null,g="",m=!0,p="auto",y="start",T=50,E="middle",v=50,S="middle";Object.defineProperty(this,"id",r({},l,{get:function(){return o},set:function(e){o=""+e}})),Object.defineProperty(this,"pauseOnExit",r({},l,{get:function(){return h},set:function(e){h=!!e}})),Object.defineProperty(this,"startTime",r({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"endTime",r({},l,{get:function(){return u},set:function(e){if("number"!=typeof e)throw TypeError("End time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"text",r({},l,{get:function(){return c},set:function(e){c=""+e,this.hasBeenReset=!0}})),Object.defineProperty(this,"region",r({},l,{get:function(){return f},set:function(e){f=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"vertical",r({},l,{get:function(){return g},set:function(t){let r=i(e,t);if(!1===r)throw SyntaxError("An invalid or illegal string was specified.");g=r,this.hasBeenReset=!0}})),Object.defineProperty(this,"snapToLines",r({},l,{get:function(){return m},set:function(e){m=!!e,this.hasBeenReset=!0}})),Object.defineProperty(this,"line",r({},l,{get:function(){return p},set:function(e){if("number"!=typeof e&&"auto"!==e)throw SyntaxError("An invalid number or illegal string was specified.");p=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"lineAlign",r({},l,{get:function(){return y},set:function(e){let r=i(t,e);if(!r)throw SyntaxError("An invalid or illegal string was specified.");y=r,this.hasBeenReset=!0}})),Object.defineProperty(this,"position",r({},l,{get:function(){return T},set:function(e){if(e<0||e>100)throw Error("Position must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"positionAlign",r({},l,{get:function(){return E},set:function(e){let r=i(t,e);if(!r)throw SyntaxError("An invalid or illegal string was specified.");E=r,this.hasBeenReset=!0}})),Object.defineProperty(this,"size",r({},l,{get:function(){return v},set:function(e){if(e<0||e>100)throw Error("Size must be between 0 and 100.");v=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"align",r({},l,{get:function(){return S},set:function(e){let r=i(t,e);if(!r)throw SyntaxError("An invalid or illegal string was specified.");S=r,this.hasBeenReset=!0}})),this.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}();class rM{decode(e,t){if(!e)return"";if("string"!=typeof e)throw Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function rO(e){function t(e,t,i,r){return(0|e)*3600+(0|t)*60+(0|i)+parseFloat(r||0)}let i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class rN{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r<i.length;++r)if(t===i[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function rU(e,t,i,r){let s=r?e.split(r):[e];for(let e in s){if("string"!=typeof s[e])continue;let r=s[e].split(i);if(2===r.length)t(r[0],r[1])}}let rB=new rF(0,0,""),r$="middle"===rB.align?"middle":"center";function rG(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class rK{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new rM,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;function i(){let e=t.buffer,i=0;for(e=rG(e);i<e.length&&"\r"!==e[i]&&"\n"!==e[i];)++i;let r=e.slice(0,i);return"\r"===e[i]&&++i,"\n"===e[i]&&++i,t.buffer=e.slice(i),r}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;let r=(e=i()).match(/^()?WEBVTT([ \t].*)?$/);if(!(null!=r&&r[0]))throw Error("Malformed WebVTT signature.");t.state="HEADER"}let s=!1;for(;t.buffer&&/\r\n|\n/.test(t.buffer);)switch(s?s=!1:e=i(),t.state){case"HEADER":if(/:/.test(e)){var r;r=e,rU(r,function(e,t){},/:/)}else e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new rF(0,0,""),t.state="CUE",-1===e.indexOf("--\x3e")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{!function(e,t,i){var r;let s,a,n,l=e;function o(){let t=rO(e);if(null===t)throw Error("Malformed timestamp: "+l);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function h(){e=e.replace(/^\s+/,"")}if(h(),t.startTime=o(),h(),"--\x3e"!==e.slice(0,3))throw Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+l);e=e.slice(3),h(),t.endTime=o(),h(),r=e,s=new rN,rU(r,function(e,t){let r;switch(e){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===t){s.set(e,i[r].region);break}break;case"vertical":s.alt(e,t,["rl","lr"]);break;case"line":r=t.split(","),s.integer(e,r[0]),s.percent(e,r[0])&&s.set("snapToLines",!1),s.alt(e,r[0],["auto"]),2===r.length&&s.alt("lineAlign",r[1],["start",r$,"end"]);break;case"position":r=t.split(","),s.percent(e,r[0]),2===r.length&&s.alt("positionAlign",r[1],["start",r$,"end","line-left","line-right","auto"]);break;case"size":s.percent(e,t);break;case"align":s.alt(e,t,["start",r$,"end","left","right"])}},/:/,/\s/),t.region=s.get("region",null),t.vertical=s.get("vertical",""),"auto"===(a=s.get("line","auto"))&&-1===rB.line&&(a=-1),t.line=a,t.lineAlign=s.get("lineAlign","start"),t.snapToLines=s.get("snapToLines",!0),t.size=s.get("size",100),t.align=s.get("align",r$),"auto"===(n=s.get("position","auto"))&&50===rB.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let i=-1!==e.indexOf("--\x3e");
14if(!e||i&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){try{if((this.cue||"HEADER"===this.state)&&(this.buffer+="\n\n",this.parse()),"INITIAL"===this.state||"BADWEBVTT"===this.state)throw Error("Malformed WebVTT signature.")}catch(e){this.onparsingerror&&this.onparsingerror(e)}return this.onflush&&this.onflush(),this}}let rH=/\r\n|\n\r|\n|\r/g,rV=function(e,t,i=0){return e.slice(i,i+t.length)===t},rW=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!v(t)||!v(i)||!v(r)||!v(s))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*r,t+=36e5*s},rY=function(e){let t=5381,i=e.length;for(;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()};function rq(e,t,i){return rY(e.toString())+rY(t.toString())+rY(i)}let rj=function(e,t,i){let r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=!1;return}for(;null!=(a=s)&&a.new;){var a;e.ccOffset+=r.start-s.start,r.new=!1,s=e[(r=s).prevCC]}e.presentationOffset=i},rX="stpp.ttml.im1t",rz=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,rQ=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,rJ={left:"start",center:"center",right:"end",start:"start",end:"end"};function rZ(e,t,i,r){let s=eA(new Uint8Array(e),["mdat"]);if(0===s.length)return void r(Error("Could not parse IMSC1 mdat"));let a=s.map(e=>em(e)),n=function(e,t=1,i=!1){return i$(e,1,1/t,i)}(t.baseTime,t.timescale);try{a.forEach(e=>i(function(e,t){let i=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw Error("Invalid ttml");let r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(r).reduce((e,t)=>(e[t]=i.getAttribute(`ttp:${t}`)||r[t],e),{}),a="preserve"!==i.getAttribute("xml:space"),n=r1(r0(i,"styling","style")),l=r1(r0(i,"layout","region")),o=r0(i,"body","[begin]");return[].map.call(o,e=>{var i,r,o;let h,d,u,c=function e(t,i){return[].slice.call(t.childNodes).reduce((t,r,s)=>{var a;return"br"===r.nodeName&&s?t+"\n":null!=(a=r.childNodes)&&a.length?e(r,i):i?t+r.textContent.trim().replace(/\s+/g," "):t+r.textContent},"")}(e,a);if(!c||!e.hasAttribute("begin"))return null;let f=r3(e.getAttribute("begin"),s),g=r3(e.getAttribute("dur"),s),m=r3(e.getAttribute("end"),s);if(null===f)throw r4(e);if(null===m){if(null===g)throw r4(e);m=f+g}let p=new rF(f-t,m-t,c);p.id=rq(p.startTime,p.endTime,p.text);let y=(i=l[e.getAttribute("region")],r=n[e.getAttribute("style")],o=n,h="http://www.w3.org/ns/ttml#styling",d=null,(u=null!=i&&i.hasAttribute("style")?i.getAttribute("style"):null)&&o.hasOwnProperty(u)&&(d=o[u]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((e,t)=>{let s=r2(r,h,t)||r2(i,h,t)||r2(d,h,t);return s&&(e[t]=s),e},{})),{textAlign:T}=y;if(T){let e=rJ[T];e&&(p.lineAlign=e),p.align=T}return E(p,y),p}).filter(e=>null!==e)}(e,n)))}catch(e){r(e)}}function r0(e,t,i){let r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function r1(e){return e.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function r2(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function r4(e){return Error(`Could not parse ttml timestamp ${e}`)}function r3(e,t){var i,r;let s,a;if(!e)return null;let n=rO(e);return null===n&&(rz.test(e)?(i=e,r=t,a=(0|(s=rz.exec(i))[4])+(0|s[5])/r.subFrameRate,n=(0|s[1])*3600+(0|s[2])*60+(0|s[3])+a/r.frameRate):rQ.test(e)&&(n=function(e,t){let i=rQ.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),n}class r5{constructor(e){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=r8(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.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 e=new rP(this,"textTrack1"),t=new rP(this,"textTrack2"),i=new rP(this,"textTrack3"),r=new rP(this,"textTrack4");this.cea608Parser1=new rC(1,e,t),this.cea608Parser2=new rC(3,i,r)}
14e.on(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(S.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(S.FRAG_LOADING,this.onFragLoading,this),e.on(S.FRAG_LOADED,this.onFragLoaded,this),e.on(S.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(S.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(S.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(S.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(S.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(S.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(S.FRAG_LOADING,this.onFragLoading,this),e.off(S.FRAG_LOADED,this.onFragLoaded,this),e.off(S.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(S.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(S.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(S.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(S.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(e,t,i,r,s){let a=!1;for(let e=s.length;e--;){var n,l;let r=s[e],o=(n=r[0],l=r[1],Math.min(l,i)-Math.max(n,t));if(o>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],i),a=!0,o/(i-t)>.5))return}if(a||s.push([t,i]),this.config.renderTextTracksNatively){let s=this.captionsTracks[e];this.Cues.newCue(s,t,i,r)}else{let s=this.Cues.newCue(null,t,i,r);this.hls.trigger(S.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s}){let{unparsedVttFrags:a}=this;"main"===i&&(this.initPTS[t.cc]={baseTime:r,timescale:s}),a.length&&(this.unparsedVttFrags=[],a.forEach(e=>{this.onFragLoaded(S.FRAG_LOADED,e)}))}getExistingTrack(e){let{media:t}=this;if(t)for(let i=0;i<t.textTracks.length;i++){let r=t.textTracks[i];if(r[e])return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,media:r}=this,{label:s,languageCode:a}=t[e],n=this.getExistingTrack(e);if(n)i[e]=n,tt(i[e]),e7(i[e],r);else{let t=this.createTextTrack("captions",s,a);t&&(t[e]=!0,i[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(S.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,i){let r=this.media;if(r)return r.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){let{captionsTracks:e}=this;Object.keys(e).forEach(t=>{tt(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=r8(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let e=0;e<t.length;e++)tt(t[e])}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],r=i.some(e=>e.textCodec===rX);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(rn(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let e=this.media?this.media.textTracks:null;this.tracks.forEach((t,i)=>{let r;if(e&&i<e.length){let i=null;for(let r=0;r<e.length;r++){var s,a;if(s=e[r],a=t,s&&s.label===a.name&&!(s.textTrack1||s.textTrack2)){i=e[r];break}}i&&(r=i)}if(r)tt(r);else{let e=this._captionsOrSubtitlesFromCharacteristics(t);(r=this.createTextTrack(e,t.name,t.lang))&&(r.mode="disabled")}r&&(r.groupId=t.groupId,this.textTracks.push(r))})}else if(this.tracks.length){let e=this.tracks.map(e=>
14({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(S.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){let t=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),i=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(t&&i)return"captions"}return"subtitles"}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let i=`textTrack${t[1]}`,r=this.captionsProperties[i];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){let{cea608Parser1:i,cea608Parser2:r,lastSn:s,lastPartIndex:a}=this;if(this.enabled&&i&&r&&t.frag.type===e4){var n,l;let e=t.frag.sn,o=null!=(n=null==t||null==(l=t.part)?void 0:l.index)?n:-1;e!==s+1&&(e!==s||o!==a+1)&&(i.reset(),r.reset()),this.lastSn=e,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.type===e5)if(r.byteLength){let e=i.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){let e=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===rX?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(S.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:Error("Empty subtitle payload")})}_parseIMSC1(e,t){let i=this.hls;rZ(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),i.trigger(S.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{k.log(`Failed to parse IMSC1: ${t}`),i.trigger(S.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t,i,r,s,a,n,l,o;let h,d,u,c,f,g,m,p,y,{frag:T,payload:E}=e,{initPTS:v,unparsedVttFrags:L}=this,R=v.length-1;if(!v[T.cc]&&-1===R)return void L.push(e);let A=this.hls;i=null!=(t=T.initSegment)&&t.data?ek(T.initSegment.data,new Uint8Array(E)):E,r=this.initPTS[T.cc],s=this.vttCCs,a=T.cc,n=T.start,l=e=>{this._appendCues(e,T.level),A.trigger(S.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:T})},o=t=>{let i="Missing initPTS for VTT MPEGTS"===t.message;i?L.push(e):this._fallbackToIMSC1(T,E),k.log(`Failed to parse VTT cue: ${t}`),i&&R>T.cc||A.trigger(S.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:T,error:t})},d=new rK,u=em(new Uint8Array(i)).trim().replace(rH,"\n").split("\n"),c=[],f=r?function(e,t=1){return i$(e,9e4,1/t)}(r.baseTime,r.timescale):0,g="00:00.000",m=0,p=0,y=!0,d.oncue=function(e){let t=s[a],i=s.ccOffset,l=(m-f)/9e4;if(null!=t&&t.new&&(void 0!==p?i=s.ccOffset=t.start:rj(s,a,l)),l){if(!r){h=Error("Missing initPTS for VTT MPEGTS");return}i=l-s.presentationOffset}let o=e.endTime-e.startTime,d=iW((e.startTime+i-p)*9e4,9e4*n)/9e4;e.startTime=Math.max(d,0),e.endTime=Math.max(d+o,0);let u=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(u)),e.id||(e.id=rq(e.startTime,e.endTime,u)),e.endTime>0&&c.push(e)},d.onparsingerror=function(e){h=e},d.onflush=function(){h?o(h):l(c)},u.forEach(e=>{if(y)if(rV(e,"X-TIMESTAMP-MAP=")){y=!1,e.slice(16).split(",").forEach(e=>{rV(e,"LOCAL:")?g=e.slice(6):rV(e,"MPEGTS:")&&(m=parseInt(e.slice(7)))});try{p=rW(g)/1e3}catch(e){h=e}return}else""===e&&(y=!1);d.parse(e+"\n")}),d.flush()}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||rZ(t,this.initPTS[e.cc],()=>{i.textCodec=rX,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach(e=>te(i,e))}else{let r=this.tracks[t];if(!r)return;let s=r.default?"default":"subtitles"+t;i.trigger(S.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===e5&&this.onFragLoaded(S.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){let{cea608Parser1:i,cea608Parser2:r}=this;if(!this.enabled||!(i&&r))return;let{frag:s,samples:a}=t;if(s.type!==e4||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;e<a.length;e++){let t=a[e].bytes;if(t){let s=this.extractCea608Data(t);
14i.addData(a[e].pts,s[0]),r.addData(a[e].pts,s[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:r,type:s}){let{media:a}=this;if(a&&!(a.currentTime<i)){if(!s||"video"===s){let{captionsTracks:e}=this;Object.keys(e).forEach(r=>ti(e[r],t,i))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){let{textTracks:e}=this;Object.keys(e).forEach(i=>ti(e[i],t,r))}}}extractCea608Data(e){let t=[[],[]],i=31&e[0],r=2;for(let s=0;s<i;s++){let i=e[r++],s=127&e[r++],a=127&e[r++];if((0!==s||0!==a)&&(4&i)!=0){let e=3&i;(0===e||1===e)&&(t[e].push(s),t[e].push(a))}}return t}}function r8(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class r6{constructor(e){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=e,this.autoLevelCapping=1/0,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){let{hls:e}=this;e.on(S.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(S.MANIFEST_PARSED,this.onManifestParsed,this),e.on(S.BUFFER_CODECS,this.onBufferCodecs,this),e.on(S.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(S.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(S.MANIFEST_PARSED,this.onManifestParsed,this),e.off(S.BUFFER_CODECS,this.onBufferCodecs,this),e.off(S.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null}onManifestParsed(e,t){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){let e=this.hls.levels;if(e.length){let t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return -1;let i=t.filter((t,i)=>this.isLevelAllowed(t)&&i<=e);return this.clientRect=null,r6.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=1/0,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=1/0,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch(e){}return e}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,i){if(!(null!=e&&e.length))return -1;let r=(e,t)=>!t||e.width!==t.width||e.height!==t.height,s=e.length-1;for(let a=0;a<e.length;a+=1){let n=e[a];if((n.width>=t||n.height>=i)&&r(n,e[a+1])){s=a;break}}return s}}class r9{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}
14registerListeners(){this.hls.on(S.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(S.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let e=r-this.lastTime,s=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,n=1e3*s/e,l=this.hls;if(l.trigger(S.FPS_DROP,{currentDropped:s,currentDecoded:a,totalDroppedFrames:i}),n>0&&s>l.config.fpsDroppedMonitoringThreshold*a){let e=l.currentLevel;k.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=e)&&(e-=1,l.trigger(S.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:l.currentLevel}),l.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}let r7="[eme]";class se{constructor(e){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=se.CDMCleanupPromise?[se.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=k.debug.bind(k,r7),this.log=k.log.bind(k,r7),this.warn=k.warn.bind(k,r7),this.error=k.error.bind(k,r7),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(S.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(S.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(S.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(S.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(S.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(S.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===W&&i)return i;throw Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=t[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,r=t.map(e=>e.audioCodec).filter(i),s=t.map(e=>e.videoCodec).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise((t,i)=>{let a=e=>{let n=e.shift();this.getMediaKeysPromise(n,r,s).then(e=>t({keySystem:n,mediaKeys:e})).catch(t=>{e.length?a(e):t instanceof st?i(t):i(new st({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};a(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===ee&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){let r=function(e,t,i,r){var s,a,n,l;let o;switch(e){case H:o=["cenc","sinf"];break;case W:case V:o=["cenc"];break;case K:o=["cenc","keyids"];break;default:throw Error(`Unknown key-system: ${e}`)}
14return s=o,a=t,n=i,[{initDataTypes:s,persistentState:(l=r).persistentState||"not-allowed",distinctiveIdentifier:l.distinctiveIdentifier||"not-allowed",sessionTypes:l.sessionTypes||[l.sessionType||"temporary"],audioCapabilities:a.map(e=>({contentType:`audio/mp4; codecs="${e}"`,robustness:l.audioRobustness||"",encryptionScheme:l.audioEncryptionScheme||null})),videoCapabilities:n.map(e=>({contentType:`video/mp4; codecs="${e}"`,robustness:l.videoRobustness||"",encryptionScheme:l.videoEncryptionScheme||null}))}]}(e,t,i,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e],a=null==s?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(r)}`),a=this.requestMediaKeySystemAccess(e,r);let t=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);let r=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=i.createMediaKeys().then(t=>(this.log(`Media-keys created for "${e}"`),r.then(i=>i?this.setMediaKeysServerCertificate(t,e,i):t))),t.mediaKeys.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),t.mediaKeys})}return a.then(()=>s.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${ep(e.keyId||[])}`);let r=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,"cenc",t.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw Error("keyId is null");return ep(e.keyId)}updateKeySession(e,t){var i;let r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${ep((null==(i=e.decryptdata)?void 0:i.keyId)||[])} 15 } (data length: ${t?t.byteLength:t})`),r.update(t)}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,i)=>{let r=Z(this.config),s=e.map(z).filter(e=>!!e&&-1!==r.indexOf(e));return this.getKeySystemSelectionPromise(s).then(({keySystem:e})=>{let r=J(e);r?t(r):i(Error(`Unable to find format for key-system "${e}"`))}).catch(i)})}loadKey(e){let t=e.keyInfo.decryptdata,i=this.getKeyIdString(t),r=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let s=this.keyIdToKeySessionPromise[i];return s||(s=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(t).then(({keySystem:i,mediaKeys:s})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(i,s).then(()=>{this.throwIfDestroyed();let e=this.createMediaKeySessionContext({keySystem:i,mediaKeys:s,decryptdata:t});return this.generateRequestWithPreferredKeySession(e,"cenc",t.pssh,"playlist-key")})))).catch(e=>this.handleError(e)),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof st?this.hls.trigger(S.ERROR,e.data):this.hls.trigger(S.ERROR,{type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){let t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){let t=z(e.keyFormat),i=t?[t]:Z(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=Z(this.config)),0===e.length)throw new st({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){let t,i,{initDataType:r,initData:s}=e;if(this.debug(`"${e.type}" event: init data type: "${r}"`),null===s)return;if("sinf"===r&&this.config.drmSystems[H]){let e=eE(new Uint8Array(s));try{let r=$(JSON.parse(e).sinf),s=eD(new Uint8Array(r));if(!s)return;t=s.subarray(8,24),i=H}catch(e){this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{let e=function(e){if(!(e instanceof ArrayBuffer)||e.byteLength<32)return null;let t={version:0,systemId:"",kids:null,data:null},i=new DataView(e),r=i.getUint32(0);if(e.byteLength!==r&&r>44||0x70737368!==i.getUint32(4)||(t.version=i.getUint32(8)>>>24,t.version>1))return null;t.systemId=ep(new Uint8Array(e,12,16));let s=i.getUint32(28);if(0===t.version){if(r-32<s)return null;t.data=new Uint8Array(e,32,s)}else if(1===t.version){t.kids=[];for(let i=0;i<s;i++)t.kids.push(new Uint8Array(e,32+16*i,16))}return t}(s);if(null===e)return;0===e.version&&e.systemId===Q&&e.data&&(t=e.data.subarray(8,24)),i=function(e){if(e===Q)return W}(e.systemId)}if(!i||!t)return;let a=ep(t),{keyIdToKeySessionPromise:n,mediaKeySessions:l}=this,o=n[a];for(let e=0;e<l.length;e++){let i=l[e],h=i.decryptdata;if(h.pssh||!h.keyId)continue;let d=ep(h.keyId);if(a===d||-1!==h.uri.replace(/-/g,"").indexOf(a)){o=n[d],delete n[d],h.pss
15h=new Uint8Array(s),h.keyId=t,o=n[a]=o.then(()=>this.generateRequestWithPreferredKeySession(i,r,s,"encrypted-event-key-match"));break}}o||(o=n[a]=this.getKeySystemSelectionPromise([i]).then(({keySystem:e,mediaKeys:i})=>{var n;this.throwIfDestroyed();let l=new ex("ISO-23001-7",a,null!=(n=J(e))?n:"");return l.pssh=new Uint8Array(s),l.keyId=t,this.attemptSetMediaKeys(e,i).then(()=>{this.throwIfDestroyed();let t=this.createMediaKeySessionContext({decryptdata:l,keySystem:e,mediaKeys:i});return this.generateRequestWithPreferredKeySession(t,r,s,"encrypted-event-no-match")})})),o.catch(e=>this.handleError(e))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>{if(!this.media)throw Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>-1===i.indexOf(e))})}generateRequestWithPreferredKeySession(e,t,i,r){var s,a,n;let l=null==(s=this.config.drmSystems)||null==(a=s[e.keySystem])?void 0:a.generateRequest;if(l)try{let r=l.call(this.hls,t,i,e);if(!r)throw Error("Invalid response from configured generateRequest filter");t=r.initDataType,i=e.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(e){if(this.warn(e.message),null!=(n=this.hls)&&n.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let o=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${r}": ${o} (init data type: ${t} length: ${i?i.byteLength:null})`);let h=new i5;e.mediaKeysSession.onmessage=t=>{let i=e.mediaKeysSession;if(!i)return void h.emit("error",Error("invalid state"));let{messageType:r,message:s}=t;this.log(`"${r}" message event for session "${i.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,s).catch(e=>{this.handleError(e),h.emit("error",e)}):"license-release"===r?e.keySystem===H&&(this.updateKeySession(e,G("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${r}"`)},e.mediaKeysSession.onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void h.emit("error",Error("invalid state"));this.onKeyStatusChange(e);let i=e.keyStatus;h.emit("keyStatus",i),"expired"===i&&(this.warn(`${e.keySystem} expired for key ${o}`),this.renewKeySession(e))};let d=new Promise((e,t)=>{h.on("error",t),h.on("keyStatus",i=>{i.startsWith("usable")?e():"output-restricted"===i?t(new st({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?t(new st({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${i}"`)):"expired"===i?t(Error("key expired while generating request")):this.warn(`unhandled key status change "${i}"`)})});return e.mediaKeysSession.generateRequest(t,i).then(()=>{var t;this.log(`Request generated for key-session "${null==(t=e.mediaKeysSession)?void 0:t.sessionId}" keyId: ${o}`)}).catch(e=>{throw new st({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>d).catch(t=>{throw h.removeAllListeners(),this.removeSession(e),t}).then(()=>(h.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,i)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${ep("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${ep(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){let t=this.config,i=new t.loader(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching serverCertificate for "${e}"`),new Promise((s,a)=>{let n={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,o={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};i.load(n,o,{onSuccess:(e,t,i,r)=>{s(e.data)},onError:(t,i,s,l)=>{a(new st({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:T({url:n.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,s)=>{a(new st({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:n.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,i)=>{a(Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,s)=>{e.setServerCertificate(i).then(s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${null==i?void 0:i.byteLength}) on "${t}"`),r(e)}).catch(e=>{s(new st({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(e=>{throw new st({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))}setupLicenseXHR(e,t,i,r){let s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>
15{if(!i.decryptdata)throw Error("Key removed");return s.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),s.call(this.hls,e,t,i,r)}).then(i=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((r,s)=>{let a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);let n=new XMLHttpRequest;n.responseType="arraybuffer",n.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(Error("invalid state"));if(4===n.readyState)if(200===n.status){this._requestLicenseFailureCount=0;let t=n.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);let i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,n,a,e)}catch(e){this.error(e)}r(t)}else{let l=i.errorRetry,o=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>o||n.status>=400&&n.status<500)s(new st({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:n,response:{url:a,data:void 0,code:n.status,text:n.statusText}},`License Request XHR failed (${a}). Status: ${n.status} (${n.statusText})`));else{let i=o-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=n,this.setupLicenseXHR(n,a,e,t).then(({xhr:e,licenseChallenge:t})=>{e.send(t)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){let e=this.media,t=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},ex.clearKeyUriToKeyIdMap();let i=t.length;se.CDMCleanupPromise=Promise.all(t.map(e=>this.removeSession(e)).concat(null==e?void 0:e.setMediaKeys(null).catch(t=>{this.log(`Could not clear media keys: ${t}. media.src: ${null==e?void 0:e.src}`)}))).then(()=>
15{i&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}. media.src: ${null==e?void 0:e.src}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){let e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),t.onmessage=null,t.onkeystatuseschange=null,i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let r=this.mediaKeySessions.indexOf(e);return r>-1&&this.mediaKeySessions.splice(r,1),t.remove().catch(e=>{this.log(`Could not remove session: ${e}`)}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`)})}}}se.CDMCleanupPromise=void 0;class st extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=Error(t)),this.data=e,e.err=e.error}}class si{constructor(e){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=e=>{try{this.apply(e,{ot:"m",su:!this.initialized})}catch(e){k.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{let t=e.frag,i=this.hls.levels[t.level],r=this.getObjectType(t),s={d:1e3*t.duration,ot:r};("v"===r||"a"===r||"av"==r)&&(s.br=i.bitrate/1e3,s.tb=this.getTopBandwidth(r)/1e3,s.bl=this.getBufferLength(r)),this.apply(e,s)}catch(e){k.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||si.uuid(),this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.registerListeners())}registerListeners(){let e=this.hls;e.on(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(S.MEDIA_DETACHED,this.onMediaDetached,this),e.on(S.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(S.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(S.MEDIA_DETACHED,this.onMediaDetached,this),e.off(S.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(e,t){this.media=t.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(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}createData(){var e;return{v:1,sf:"h",sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){E(t,this.createData());let i="i"===t.ot||"v"===t.ot||"av"===t.ot;if(this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering),this.useHeaders){let i=si.toHeaders(t);if(!Object.keys(i).length)return;e.headers||(e.headers={}),E(e.headers,i)}else{let i=si.toQuery(t);if(!i)return;e.url=si.appendQueryToUri(e.url,i)}}getObjectType(e){let{type:t}=e;return"subtitle"===t?"tt":"initSegment"===e.sn?"i":"audio"===t?"a":"main"===t?this.hls.audioTracks.length?"v":"av":void 0}getTopBandwidth(e){let t,i=0,r=this.hls;if("a"===e)t=r.audioTracks;else{let e=r.maxAutoLevel,i=e>-1?e+1:r.levels.length;t=r.levels.slice(0,i)}for(let e of t)e.bitrate>i&&(i=e.bitrate);return i>0?i:NaN}getBufferLength(e){let t=this.hls.media,i="a"===e?this.audioBuffer:this.videoBuffer;return i&&t?1e3*tW.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}static uuid(){let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}static serialize(e){let t=[],i=e=>!Number.isNaN(e)&&null!=e&&""!==e&&!1!==e,r=e=>Math.round(e),s=e=>100*r(e/100),a={br:r,d:r,bl:s,dl:s,mtp:s,nor:e=>encodeURIComponent(e),rtp:s,tb:r};for(let r of Object.keys(e||{}).sort()){let s,n=e[r];if(!i(n)||"v"===r&&1===n||"pr"==r&&1===n)continue;let l=a[r];l&&(n=l(n));let o=typeof n;s="ot"===r||"sf"===r||"st"===r?`${r}=${n}`:"boolean"===o?r:"number"===o?`${r}=${n}`:`${r}=${JSON.stringify(n)}`,t.push(s)}return t.join(",")}static toHeaders(e){let t=Object.keys(e),i={},r=["Object","Request","Session","Status"],s=[{},{},{},{}],a={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(let i of t)s[null!=a[i]?a[i]:1][i]=e[i];for(let e=0;e<s.length;e++){let t=si.serialize(s[e]);t&&(i[`CMCD-${r[e]}`]=t)}return i}static toQuery(e){return`CMCD=${encodeURIComponent(si.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;let i=e.includes("?")?"&":"?";return`${e}${i}${t}`}}class sr{constructor(e){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=e,this.log=k.log.bind(k,"[content-steering]:"),this.registerListeners()}registerListeners(){let e=this.hls;e.on(S.MANIFEST_LOADING,this.onManifestLoading,this),e.on(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(S.MANIFEST_PARSED,this.onManifestParsed,this),e.on(S.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(S.MANIFEST_LOADING,this.onManifestLoading,this),e.off(S.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(S.MANIFEST_PARSED,this.onManifestParsed,this),e.off(S.ERROR,this.onError,this))}
15startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri)if(this.updated){let e=Math.max(1e3*this.timeToLoad-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,e)}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(e){let t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:i}=t;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if((null==i?void 0:i.action)===2&&1===i.flags){let e=this.pathwayPriority,t=this.pathwayId;this.penalizedPathways[t]||(this.penalizedPathways[t]=performance.now()),!e&&this.levels&&(e=this.levels.reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e),[])),e&&e.length>1&&(this.updatePathwayPriority(e),i.resolved=this.pathwayId!==t)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this.pathwayPriority=e;let i=this.penalizedPathways,r=performance.now();
15Object.keys(i).forEach(e=>{r-i[e]>3e5&&delete i[e]});for(let r=0;r<e.length;r++){let s=e[r];if(i[s])continue;if(s===this.pathwayId)return;let a=this.hls.nextLoadLevel,n=this.hls.levels[a];if((t=this.getLevelsForPathway(s)).length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,this.hls.trigger(S.LEVELS_UPDATED,{levels:t});let e=this.hls.levels[a];n&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==n.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==n.bitrate&&this.log(`Unstable Pathways change from bitrate ${n.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=a);break}}}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach(e=>{let{ID:s,"BASE-ID":a,"URI-REPLACEMENT":n}=e;if(t.some(e=>e.pathwayId===s))return;let l=this.getLevelsForPathway(a).map(e=>{let t=E({},e);t.details=void 0,t.url=sa(e.uri,e.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",n);let a=new _(e.attrs);a["PATHWAY-ID"]=s;let l=a.AUDIO&&`${a.AUDIO}_clone_${s}`,o=a.SUBTITLES&&`${a.SUBTITLES}_clone_${s}`;l&&(i[a.AUDIO]=l,a.AUDIO=l),o&&(r[a.SUBTITLES]=o,a.SUBTITLES=o),t.attrs=a;let h=new tc(t);return t_(h,"audio",l),t_(h,"text",o),h});t.push(...l),ss(this.audioTracks,i,n,s),ss(this.subtitleTracks,r,n,s)})}loadSteeringManifest(e){let t,i=this.hls.config,r=i.loader;this.loader&&this.loader.destroy(),this.loader=new r(i);try{t=new self.URL(e)}catch(t){this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if("data:"!==t.protocol){let e=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+e)}let s={responseType:"json",url:t.href},a=i.steeringManifestLoadPolicy.default,n=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0};this.log(`Requesting steering manifest: ${t}`),this.loader.load(s,l,{onSuccess:(e,i,r,s)=>{this.log(`Loaded steering manifest: "${t}"`);let a=e.data;if(1!==a.VERSION)return void this.log(`Steering VERSION ${a.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=a.TTL;let{"RELOAD-URI":n,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":o}=a;if(n)try{this.uri=new self.URL(n,t).href}catch(e){this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${n}`);return}this.scheduleRefresh(this.uri||r.url),l&&this.clonePathways(l),o&&this.updatePathwayPriority(o)},onError:(e,t,i,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code){this.enabled=!1,this.log(`Steering manifest ${t.url} no longer available`);return}let s=1e3*this.timeToLoad;if(429===e.code){let e=this.loader;if("function"==typeof(null==e?void 0:e.getResponseHeader)){let t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`);return}this.scheduleRefresh(this.uri||t.url,s)},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}})}scheduleRefresh(e,t=1e3*this.timeToLoad){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(e)},t)}}function ss(e,t,i,r){e&&Object.keys(t).forEach(s=>{let a=e.filter(e=>e.groupId===s).map(e=>{let a=E({},e);return a.details=void 0,a.attrs=new _(a.attrs),a.url=a.attrs.URI=sa(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),a.groupId=a.attrs["GROUP-ID"]=t[s],a.attrs["PATHWAY-ID"]=r,a});e.push(...a)})}function sa(e,t,i,r){let s,{HOST:a,PARAMS:n,[i]:l}=r;t&&(s=null==l?void 0:l[t])&&(e=s);let o=new self.URL(e);return a&&!s&&(o.host=a),n&&Object.keys(n).sort().forEach(e=>{e&&o.searchParams.set(e,n[e])}),o.href}let sn=/^age:\s*[\d.]+\s*$/im;class sl{constructor(e){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=e&&e.xhrSetup||null,this.stats=new x,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let s=this.xhrSetup;s?Promise.resolve().then(()=>
15{if(!this.stats.aborted)return s(i,t.url)}).catch(e=>(i.open("GET",t.url,!0),s(i,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(e=>{this.callbacks.onError({code:i.status,text:e.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let r=this.context.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(let t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&v(s)?s:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let r=t.status,a="text"!==t.responseType;if(r>=200&&r<300&&(a&&t.response||null!==t.responseText)){i.loading.end=Math.max(self.performance.now(),i.loading.first);let s=a?t.response:t.responseText;if(i.loaded=i.total="arraybuffer"===t.responseType?s.byteLength:s.length,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;let n=this.callbacks.onProgress;if(n&&n(i,e,s,t),!this.callbacks)return;let l={url:t.responseURL,data:s,code:r};this.callbacks.onSuccess(l,i,e,t)}else{let a=s.loadPolicy.errorRetry;tR(a,i.retry,!1,r)?this.retry(a):(k.error(`${r} while loading ${e.url}`),this.callbacks.onError({code:r,text:t.statusText},e,t,i))}}}loadtimeout(){var e;let t=null==(e=this.config)?void 0:e.loadPolicy.timeoutRetry;if(tR(t,this.stats.retry,!0))this.retry(t);else{k.warn(`timeout while loading ${this.context.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:i}=this;this.retryDelay=tS(e,i.retry),i.retry++,k.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t.url}, retrying ${i.retry}/${e.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(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&sn.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}let so=/(\d+)-(\d+)\/(\d+)/;class sh{constructor(e){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=e.fetchSetup||sd,this.controller=new self.AbortController,this.stats=new x}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){let e=this.response;null!=e&&e.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){var r;let s,a=this.stats;if(a.loading.start)throw Error("Loader can only be used once.");a.loading.start=self.performance.now();let n=(r=e,s={method:"GET",mode:"cors",credentials:"same-origin",signal:this.controller.signal,headers:new self.Headers(E({},r.headers))},r.rangeEnd&&s.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),s),l=i.onProgress,o="arraybuffer"===e.responseType,h=o?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=
15d&&v(d)?d:u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(a,e,this.response)},t.timeout),self.fetch(this.request).then(r=>{this.response=this.loader=r;let s=Math.max(self.performance.now(),a.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(a,e,this.response)},u-(s-a.loading.start)),!r.ok){let{status:e,statusText:t}=r;throw new su(t||"fetch, bad network response",e,r)}return(a.loading.first=s,a.total=function(e){let t=e.get("Content-Range");if(t){let e=function(e){let t=so.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(v(e))return e}let i=e.get("Content-Length");if(i)return parseInt(i)}(r.headers)||a.total,l&&v(t.highWaterMark))?this.loadProgressively(r,a,e,t.highWaterMark,l):o?r.arrayBuffer():"json"===e.responseType?r.json():r.text()}).then(r=>{let{response:s}=this;self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);let n=r[h];n&&(a.loaded=a.total=n);let o={url:s.url,data:r,code:s.status};l&&!v(t.highWaterMark)&&l(a,e,r,s),i.onSuccess(o,a,e,s)}).catch(t=>{if(self.clearTimeout(this.requestTimeout),a.aborted)return;let r=t&&t.code||0,s=t?t.message:null;i.onError({code:r,text:s},e,t?t.details:null,a)})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,s){let a=new rr,n=e.body.getReader(),l=()=>n.read().then(n=>{if(n.done)return a.dataLength&&s(t,i,a.flush(),e),Promise.resolve(new ArrayBuffer(0));let o=n.value,h=o.length;return t.loaded+=h,h<r||a.dataLength?(a.push(o),a.dataLength>=r&&s(t,i,a.flush(),e)):s(t,i,o,e),l()}).catch(()=>Promise.reject());return l()}}function sd(e,t){return new self.Request(e.url,t)}class su extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}let sc=/\s/,sf={newCue(e,t,i,r){let s,a,n,l,o,h=[],d=self.VTTCue||self.TextTrackCue;for(let c=0;c<r.rows.length;c++)if(s=r.rows[c],n=!0,l=0,o="",!s.isEmpty()){var u;for(let e=0;e<s.chars.length;e++)sc.test(s.chars[e].uchar)&&n?l++:(o+=s.chars[e].uchar,n=!1);s.cueStartTime=t,t===i&&(i+=1e-4),l>=16?l--:l++;let r=rG(o.trim()),f=rq(t,i,r);null!=e&&null!=(u=e.cues)&&u.getCueById(f)||((a=new d(t,i,r)).id=f,a.line=c+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),h.push(a))}return e&&h.length&&(h.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),h.forEach(t=>te(e,t))),h}},sg=T(T({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:sl,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:ri,bufferController:rg,capLevelController:r6,errorController:tk,fpsController:r9,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:ee,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,cert
15LoadPolicy:{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:sf,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:rl,subtitleTrackController:rh,timelineController:r5,audioStreamController:rs,audioTrackController:ra,emeController:se,cmcdController:si,contentSteeringController:sr});class sm{static get version(){return"1.4.12"}static isSupported(){let e=eN();if(!e)return!1;let t=il(),i=e&&"function"==typeof e.isTypeSupported&&e.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),r=!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove;return!!i&&!!r}static get Events(){return S}static get ErrorTypes(){return L}static get ErrorDetails(){return R}static get DefaultConfig(){return sm.defaultConfig?sm.defaultConfig:sg}static set DefaultConfig(e){sm.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new i5,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(e,t){if(self.console&&!0===e||"object"==typeof e){!function(e,...t){t.forEach(function(t){let i;D[t]=e[t]?e[t].bind(e):(i=self.console[t])?i.bind(self.console,`[${t}] >`):A})}(e,"debug","log","info","warn","error");try{D.log(`Debug logs enabled for "${t}" in hls.js version 1.4.12`)}catch(e){D=b}}else D=b}(e.debug||!1,"Hls instance");const t=this.config=function(e,t){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let i=function e(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(e):Object.keys(t).reduce((i,r)=>(i[r]=e(t[r]),i),{}):t}(e),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];
15return["manifest","level","frag"].forEach(e=>{let s=`${"level"===e?"playlist":e}LoadPolicy`,a=void 0===t[s],n=[];r.forEach(r=>{let l=`${e}Loading${r}`,o=t[l];if(void 0!==o&&a){n.push(l);let e=i[s].default;switch(t[s]={default:e},r){case"TimeOut":e.maxLoadTimeMs=o,e.maxTimeToFirstByteMs=o;break;case"MaxRetry":e.errorRetry.maxNumRetry=o,e.timeoutRetry.maxNumRetry=o;break;case"RetryDelay":e.errorRetry.retryDelayMs=o,e.timeoutRetry.retryDelayMs=o;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=o,e.timeoutRetry.maxRetryDelayMs=o}}}),n.length&&k.warn(`hls.js config: "${n.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(t[s])}`)}),T(T({},i),t)}(sm.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&function(e){let t=e.loader;t!==sh&&t!==sl?(k.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=sh,e.progressive=!0,e.enableSoftwareAES=!0,k.log("[config]: Progressive streaming enabled, using FetchLoader"))}(t);const{abrController:i,bufferController:r,capLevelController:s,errorController:a,fpsController:n}=t,l=new a(this),o=this.abrController=new i(this),h=this.bufferController=new r(this),d=this.capLevelController=new s(this),u=new n(this),c=new e9(this),f=new to(this),g=t.contentSteeringController,m=g?new g(this):null,p=this.levelController=new tC(this,m),y=new tM(this),E=new tK(this.config),v=this.streamController=new i7(this,y,E);d.setStreamController(v),u.setStreamController(v);const L=[c,p,v];m&&L.splice(1,0,m),this.networkControllers=L;const R=[o,h,d,u,f,y];this.audioTrackController=this.createController(t.audioTrackController,L);const I=t.audioStreamController;I&&L.push(new I(this,y,E)),this.subtitleTrackController=this.createController(t.subtitleTrackController,L);const C=t.subtitleStreamController;C&&L.push(new C(this,y,E)),this.createController(t.timelineController,R),E.emeController=this.emeController=this.createController(t.emeController,R),this.cmcdController=this.createController(t.cmcdController,R),this.latencyController=this.createController(th,R),this.coreComponents=R,L.push(l);const _=l.onErrorOut;"function"==typeof _&&this.on(S.ERROR,_,l)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){k.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),this.trigger(S.ERROR,{type:L.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:e,error:t})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){k.log("destroy"),this.trigger(S.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){k.log("attachMedia"),this._media=e,this.trigger(S.MEDIA_ATTACHING,{media:e})}detachMedia(){k.log("detachMedia"),this.trigger(S.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();let t=this.media,i=this.url,r=this.url=p.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});k.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(S.MANIFEST_LOADING,{url:e})}startLoad(e=-1){k.log(`startLoad(${e})`),this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){k.log("stopLoad"),this.networkControllers.forEach(e=>{e.stopLoad()})}swapAudioCodec(){k.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){k.log("recoverMediaError");let e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,t=0){this.levelController.removeLevel(e,t)}get levels(){return this.levelController.levels||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){k.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){k.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){k.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){k.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){k.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(k.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){td.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return -1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let e,{levels:t,autoLevelCapping:i,maxHdcpLevel:r}=this;if(e=-1===i&&t&&t.length?t.length-1:i,r)for(let i=e;i--;){let e=t[i].attrs["HDCP-LEVEL"];if(e&&e<=r)return i}return e}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){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}}sm.defaultConfig=void 0}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.