PageSourceSearch

https://cityfoods.com.br/_next/static/chunks/0b4b6ee1-70550c1d604dc530.js

js cityfoods.com.br collected 2026-10-10 00:19:23 UTC 354,868 bytes, 15 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[595],{3398:function(e,t,i){let r,s,a;i.d(t,{Z:function(){return rH}});var n,l,o,h,d,u,c,f,g,m,p={exports:{}};n=p,l=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,o=/^(?=([^\/?#]*))\1([^]*)$/,h=/(?:\/|^)\.(?=\/)/g,d=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,u={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var r=u.parseURL(e);if(!r)throw Error("Error trying to parse base URL.");return r.path=u.normalizePath(r.path),u.buildURLFromParts(r)}var s=u.parseURL(t);if(!s)throw Error("Error trying to parse relative URL.");if(s.scheme)return i.alwaysNormalize?(s.path=u.normalizePath(s.path),u.buildURLFromParts(s)):t;var a=u.parseURL(e);if(!a)throw Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var n=o.exec(a.path);a.netLoc=n[1],a.path=n[2]}a.netLoc&&!a.path&&(a.path="/");var l={scheme:a.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(l.netLoc=a.netLoc,"/"!==s.path[0])){if(s.path){var h=a.path,d=h.substring(0,h.lastIndexOf("/")+1)+s.path;l.path=u.normalizePath(d)}else l.path=a.path,s.params||(l.params=a.params,s.query||(l.query=a.query))}return null===l.path&&(l.path=i.alwaysNormalize?u.normalizePath(s.path):s.path),u.buildURLFromParts(l)},parseURL:function(e){var t=l.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(h,"");e.length!==(e=e.replace(d,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},n.exports=u;var E=p.exports;function T(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 y(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?T(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)):T(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function v(){return(v=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 S=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},A=((c={}).MEDIA_ATTACHING="hlsMediaAttaching",c.MEDIA_ATTACHED="hlsMediaAttached",c.MEDIA_DETACHING="hlsMediaDetaching",c.MEDIA_DETACHED="hlsMediaDetached",c.BUFFER_RESET="hlsBufferReset",c.BUFFER_CODECS="hlsBufferCodecs",c.BUFFER_CREATED="hlsBufferCreated",c.BUFFER_APPENDING="hlsBufferAppending",c.BUFFER_APPENDED="hlsBufferAppended",c.BUFFER_EOS="hlsBufferEos",c.BUFFER_FLUSHING="hlsBufferFlushing",c.BUFFER_FLUSHED="hlsBufferFlushed",c.MANIFEST_LOADING="hlsManifestLoading",c.MANIFEST_LOADED="hlsManifestLoaded",c.MANIFEST_PARSED="hlsManifestParsed",c.LEVEL_SWITCHING="hlsLevelSwitching",c.LEVEL_SWITCHED="hlsLevelSwitched",c.LEVEL_LOADING="hlsLevelLoading",c.LEVEL_LOADED="hlsLevelLoaded",c.LEVEL_UPDATED="hlsLevelUpdated",c.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",c.LEVELS_UPDATED="hlsLevelsUpdated",c.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",c.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",c.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",c.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",c.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",c.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUp
1dated",c.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",c.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",c.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",c.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",c.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",c.CUES_PARSED="hlsCuesParsed",c.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",c.INIT_PTS_FOUND="hlsInitPtsFound",c.FRAG_LOADING="hlsFragLoading",c.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",c.FRAG_LOADED="hlsFragLoaded",c.FRAG_DECRYPTED="hlsFragDecrypted",c.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",c.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",c.FRAG_PARSING_METADATA="hlsFragParsingMetadata",c.FRAG_PARSED="hlsFragParsed",c.FRAG_BUFFERED="hlsFragBuffered",c.FRAG_CHANGED="hlsFragChanged",c.FPS_DROP="hlsFpsDrop",c.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",c.ERROR="hlsError",c.DESTROYING="hlsDestroying",c.KEY_LOADING="hlsKeyLoading",c.KEY_LOADED="hlsKeyLoaded",c.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",c.BACK_BUFFER_REACHED="hlsBackBufferReached",c),L=((f={}).NETWORK_ERROR="networkError",f.MEDIA_ERROR="mediaError",f.KEY_SYSTEM_ERROR="keySystemError",f.MUX_ERROR="muxError",f.OTHER_ERROR="otherError",f),R=((g={}).KEY_SYSTEM_NO_KEYS="keySystemNoKeys",g.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",g.KEY_SYSTEM_NO_SESSION="keySystemNoSession",g.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",g.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",g.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",g.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",g.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",g.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",g.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",g.MANIFEST_LOAD_ERROR="manifestLoadError",g.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",g.MANIFEST_PARSING_ERROR="manifestParsingError",g.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",g.LEVEL_EMPTY_ERROR="levelEmptyError",g.LEVEL_LOAD_ERROR="levelLoadError",g.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",g.LEVEL_PARSING_ERROR="levelParsingError",g.LEVEL_SWITCH_ERROR="levelSwitchError",g.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",g.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",g.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",g.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",g.FRAG_LOAD_ERROR="fragLoadError",g.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",g.FRAG_DECRYPT_ERROR="fragDecryptError",g.FRAG_PARSING_ERROR="fragParsingError",g.FRAG_GAP="fragGap",g.REMUX_ALLOC_ERROR="remuxAllocError",g.KEY_LOAD_ERROR="keyLoadError",g.KEY_LOAD_TIMEOUT="keyLoadTimeOut",g.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",g.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",g.BUFFER_APPEND_ERROR="bufferAppendError",g.BUFFER_APPENDING_ERROR="bufferAppendingError",g.BUFFER_STALLED_ERROR="bufferStalledError",g.BUFFER_FULL_ERROR="bufferFullError",g.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",g.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",g.INTERNAL_EXCEPTION="internalException",g.INTERNAL_ABORTED="aborted",g.UNKNOWN="unknown",g),I=function(){},D={trace:I,debug:I,log:I,warn:I,info:I,error:I},b=D,k=b,_=/^(\d+)x(\d+)$/,C=/(.+?)=(".*?"|.*?)(?:,|$)/g;class w{constructor(e){for(let t in"string"==typeof e&&(e=w.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);t=(1&t.length?"0":"")+t;let i=new Uint8Array(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=_.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;let 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));let r=t[1].trim();i[r]=e}return i}}class P{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){let i=t.attr;for(let 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}
1e=v(new w({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){let e=new Date(this.attr["END-DATE"]);S(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(S(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&&S(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 O={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class F{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[O.AUDIO]:null,[O.VIDEO]:null,[O.AUDIOVIDEO]: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=E.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class M extends F{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||!S(this.programDateTime))return null;let e=S(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(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[O.AUDIO]=null,e[O.VIDEO]=null,e[O.AUDIOVIDEO]=null}}class N extends F{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;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}class U{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.drift
1StartTime=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&&S(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){let e=this.driftEndTime-this.driftStartTime;if(e>0){let t=this.driftEnd-this.driftStart;return 1e3*t/e}return 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 B(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function $(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}var G={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},K={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function H(e){switch(e){case K.FAIRPLAY:return G.FAIRPLAY;case K.PLAYREADY:return G.PLAYREADY;case K.WIDEVINE:return G.WIDEVINE;case K.CLEARKEY:return G.CLEARKEY}}var V={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Y(e){switch(e){case G.FAIRPLAY:return K.FAIRPLAY;case G.PLAYREADY:return K.PLAYREADY;case G.WIDEVINE:return K.WIDEVINE;case G.CLEARKEY:return K.CLEARKEY}}function W(e){let{drmSystems:t,widevineLicenseUrl:i}=e,r=t?[G.FAIRPLAY,G.WIDEVINE,G.PLAYREADY,G.CLEARKEY].filter(e=>!!t[e]):[];return!r[G.WIDEVINE]&&i&&r.push(G.WIDEVINE),r}let q="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function j(e,t,i){return Uint8Array.prototype.slice?e.slice(t,i):new Uint8Array(Array.prototype.slice.call(e,t,i))}let X=(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,z=(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,Q=(e,t)=>{let i=t,r=0;for(;X(e,t);){r+=10;let i=J(e,t+6);r+=i,z(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(i,i+r)},J=(e,t)=>(127&e[t])<<21|(127&e[t+1])<<14|(127&e[t+2])<<7|127&e[t+3],Z=(e,t)=>X(e,t)&&J(e,t+6)+10<=e.length-t,ee=e=>{let t=er(e);for(let e=0;e<t.length;e++){let i=t[e];if(et(i))return eo(i)}},et=e=>e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info,ei=e=>{let t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=J(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}},er=e=>{let t=0,i=[];for(;X(e,t);){let r=J(e,t+6);t+=10;let s=t+r;for(;t+8<s;){let r=ei(e.subarray(t)),s=es(r);s&&i.push(s),t+=r.size+10}z(e,t)&&(t+=10)}return i},es=e=>"PRIV"===e.type?ea(e):"W"===e.type[0]?el(e):en(e),ea=e=>{if(e.size<2)return;let t=eh(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}},en=e=>{if(e.size<2)return;if("TXXX"===e.type){let t=1,i=eh(e.data.subarray(t),!0);t+=i.length+1;let r=eh(e.data.subarray(t));return{key:e.type,info:i,data:r}}let t=eh(e.data.subarray(1));return{key:e.type,data:t}},el=e=>{if("WXXX"===e.type){if(e.size<2)return;let t=1,i=eh(e.data.subarray(t),!0);t+=i.length+1;let r=eh(e.data.subarray(t));return{key:e.type,info:i,data:r}}let t=eh(e.data);return{key:e.type,data:t}},eo=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)}},eh=(e,t=!1)=>{let i,s;let 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("\x00");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>>
14){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&e[o++]);break;case 14:l+=String.fromCharCode((15&i)<<12|(63&e[o++])<<6|(63&e[o++])<<0)}return l},ed={hexDump: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}},eu=[].push,ec={video:1,audio:2,id3:3,text:4};function ef(e){return String.fromCharCode.apply(null,e)}function eg(e,t){let i=e[t]<<8|e[t+1];return i<0?65536+i:i}function em(e,t){let i=ep(e,t);return i<0?4294967296+i:i}function ep(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function eE(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 eT(e,t){let i=[];if(!t.length)return i;let r=e.byteLength;for(let s=0;s<r;){let a=em(e,s),n=ef(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=eT(e.subarray(s+8,l),t.slice(1));r.length&&eu.apply(i,r)}}s=l}return i}function ey(e){let t=[],i=eT(e,["moov","trak"]);for(let e=0;e<i.length;e++){let r=i[e],s=eT(r,["tkhd"])[0];if(s){let e=s[0],i=0===e?12:20,a=em(s,i),n=eT(r,["mdia","mdhd"])[0];if(n){i=0===(e=n[0])?12:20;let s=em(n,i),l=eT(r,["mdia","hdlr"])[0];if(l){let e=ef(l.subarray(8,12)),i={soun:O.AUDIO,vide:O.VIDEO}[e];if(i){let e;let n=eT(r,["mdia","minf","stbl","stsd"])[0];n&&(e=ef(n.subarray(12,16))),t[a]={timescale:s,type:i},t[i]={timescale:s,id:a,codec:e}}}}}}let r=eT(e,["moov","mvex","trex"]);return r.forEach(e=>{let i=em(e,4),r=t[i];r&&(r.default={duration:em(e,12),flags:em(e,20)})}),t}function ev(e){let t=eT(e,["schm"])[0];if(t){let i=ef(t.subarray(4,8));if("cbcs"===i||"cenc"===i)return eT(e,["schi","tenc"])[0]}return k.error("[eme] missing 'schm' box"),null}function eS(e,t){let i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function eA(e,t){let i=[],r=t.samples,s=t.timescale,a=t.id,n=!1,l=eT(r,["moof"]);return l.map(l=>{let o=l.byteOffset-8,h=eT(l,["traf"]);h.map(l=>{let h=eT(l,["tfdt"]).map(e=>{let t=e[0],i=em(e,4);return 1===t&&(i*=4294967296,i+=em(e,8)),i/s})[0];return void 0!==h&&(e=h),eT(l,["tfhd"]).map(h=>{let d=em(h,4),u=16777215&em(h,0),c=0,f=0,g=8;d===a&&((1&u)!=0&&(g+=8),(2&u)!=0&&(g+=4),(8&u)!=0&&(c=em(h,g),g+=4),(16&u)!=0&&(f=em(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)),eT(l,["trun"]).map(a=>{let l=a[0],h=16777215&em(a,0),d=0,u=(256&h)!=0,g=0,m=(512&h)!=0,p=0,E=(1024&h)!=0,T=(2048&h)!=0,y=0,v=em(a,4),S=8;(1&h)!=0&&(d=em(a,S),S+=4),(4&h)!=0&&(S+=4);let A=d+o;for(let o=0;o<v;o++){if(u?(g=em(a,S),S+=4):g=c,m?(p=em(a,S),S+=4):p=f,E&&(S+=4),T&&(y=0===l?em(a,S):ep(a,S),S+=4),t.type===O.VIDEO){let t=0;for(;t<p;){let a=em(r,A);if(function(e,t){if(!e)return 6==(31&t);{let e=t>>1&63;return 39===e||40===e}}(n,r[A+=4])){let t=r.subarray(A,A+a);eL(t,n?2:1,e+y/s,i)}A+=a,t+=a+4}}e+=g/s}}))})})}),i}function eL(e,t,i,r){let s;let a=eR(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){o=!0;let e=a[s++];if(181===e){let e=eg(a,s);if(s+=2,49===e){let e=em(a,s);if(s+=4,1195456820===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:eh(o),userDataBytes:o})}}else if(l<e)s+=l;else if(l>e)break}}function eR(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 eI={};class eD{static clearKeyUriToKeyIdMap(){eI={}}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.pss
1h=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 K.FAIRPLAY:case K.WIDEVINE:case K.PLAYREADY:case K.CLEARKEY: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),i=new eD(this.method,this.uri,"identity",this.keyFormatVersions,t);return i}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];t?(e.splice(-1,1),i=B(s)):i=function(e){let t=$(e).subarray(0,16),i=new Uint8Array(16);return i.set(t,16-t.length),i}(s)}}return i}(this.uri);if(t)switch(this.keyFormat){case K.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case K.PLAYREADY:{let e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(e,t,i){let r,s,a;if(16!==e.byteLength)throw RangeError("Invalid system id");if(t){r=1,s=new Uint8Array(16*t.length);for(let e=0;e<t.length;e++){let i=t[e];if(16!==i.byteLength)throw RangeError("Invalid key");s.set(i,16*e)}}else r=0,s=new Uint8Array;r>0?(a=new Uint8Array(4),t.length>0&&new DataView(a.buffer).setUint32(0,t.length,!1)):a=new Uint8Array;let n=new Uint8Array(4);return i&&i.byteLength>0&&new DataView(n.buffer).setUint32(0,i.byteLength,!1),function(e,...t){let i=t.length,r=8,s=i;for(;s--;)r+=t[s].byteLength;let a=new Uint8Array(r);for(a[0]=r>>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=255&r,a.set(e,4),s=0,r=8;s<i;s++)a.set(t[s],r),r+=t[s].byteLength;return a}([112,115,115,104],new Uint8Array([r,0,0,0]),e,a,s,n,i||new Uint8Array)}(e,null,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,n=a.parseFromString(s,"text/xml"),l=n.getElementsByTagName("KID")[0];if(l){let e=l.childNodes[0]?l.childNodes[0].nodeValue:l.getAttribute("VALUE");if(e){let t=B(e).subarray(0,16);!function(e){let t=function(e,t,i){let r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}(t),this.keyId=t}}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=eI[this.uri];if(!e){let t=Object.keys(eI).length%Number.MAX_SAFE_INTEGER;e=new Uint8Array(16);let i=new DataView(e.buffer,12,4);i.setUint32(0,t),eI[this.uri]=e}this.keyId=e}return this}}let eb=/\{\$([a-zA-Z0-9-_]+)\}/g;function ek(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]=e_(e,a))}}function e_(e,t){if(null!==e.variableList||e.hasVariableRefs){let i=e.variableList;return t.replace(eb,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 eC(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 ew(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}let eP={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}},ex=ew();function eO(e,t){var i;
1return null!=(i=null==ex?void 0:ex.isTypeSupported(`${t||"video"}/mp4;codecs="${e}"`))&&i}let eF=/#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,eM=/#EXT-X-MEDIA:(.*)/g,eN=/^#EXT(?:INF|-X-TARGETDURATION):/m,eU=RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),eB=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 e${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(".");return t.length>2?t.shift()+"."+(parseInt(t.shift()).toString(16)+("000"+parseInt(t.shift()).toString(16)).slice(-4)):e}static resolve(e,t){return E.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return eN.test(e)}static parseMasterPlaylist(e,t){var i;let r;let s=eb.test(e),a={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},n=[];for(eF.lastIndex=0;null!=(r=eF.exec(e));)if(r[1]){let e=new w(r[1]);ek(a,e,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);let s=e_(a,r[2]),l={attrs:e,bitrate:e.decimalInteger("AVERAGE-BANDWIDTH")||e.decimalInteger("BANDWIDTH"),name:e.NAME,url:e$.resolve(s,t)},o=e.decimalResolution("RESOLUTION");o&&(l.width=o.width,l.height=o.height),function(e,t){["video","audio","text"].forEach(i=>{let r=e.filter(e=>(function(e,t){let i=eP[t];return!!i&&!0===i[e.slice(0,4)]})(e,i));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=e$.convertAVC1ToAVCOTI(l.videoCodec)),null!=(i=l.unknownCodecs)&&i.length||n.push(l),a.levels.push(l)}else if(r[3]){let e=r[3],i=r[4];switch(e){case"SESSION-DATA":{let e=new w(i);ek(a,e,["DATA-ID","LANGUAGE","VALUE","URI"]);let t=e["DATA-ID"];t&&(null===a.sessionData&&(a.sessionData={}),a.sessionData[t]=e);break}case"SESSION-KEY":{let e=eG(i,t,a);e.encrypted&&e.isSupported()?(null===a.sessionKeys&&(a.sessionKeys=[]),a.sessionKeys.push(e)):k.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":{let e=new w(i);ek(a,e,["NAME","VALUE","QUERYPARAM"]),eC(a,e,t)}break;case"CONTENT-STEERING":{let e=new w(i);ek(a,e,["SERVER-URI","PATHWAY-ID"]),a.contentSteering={uri:e$.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":a.startTimeOffset=eK(i)}}let l=n.length>0&&n.length<a.levels.length;return a.levels=l?n:a.levels,0===a.levels.length&&(a.playlistParsingError=Error("no levels found in manifest")),a}static parseMasterPlaylistMedia(e,t,i){let r;let s={},a=i.levels,n={AUDIO:a.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:a.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(eM.lastIndex=0;null!==(r=eM.exec(e));){let e=new w(r[1]),a=e.TYPE;if(a){let r=n[a],o=s[a]||[];s[a]=o,ek(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?e$.resolve(e.URI,t):""};if(null!=r&&r.length){let e=e$.findGroup(r,h.groupId)||r[0];eH(h,e,"audioCodec"),eH(h,e,"textCodec")}o.push(h)}}return s}static parseLevelPlaylist(e,t,i,r,s,a){let n,l,o;let h=new U(t),d=h.fragments,u=null,c=0,f=0,g=0,m=0,p=null,E=new M(r,t),T=-1,y=!1;for(eU.lastIndex=0,h.m3u8=e,h.hasVariableRefs=eb.test(e);null!==(n=eU.exec(e));){y&&(y=!1,(E=new M(r,t)).start=g,E.sn=c,E.cc=m,E.level=i,u&&(E.initSegment=u,E.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null));let e=n[1];if(e){E.duration=parseFloat(e);let t=(" "+n[2]).slice(1);E.title=t||null,E.tagList.push(t?["INF",e,t]:["INF",e])}else if(n[3]){if(S(E.duration)){E.start=g,o&&eW(E,o,h),E.sn=c,E.level=i,E.cc=m,E.urlId=s,d.push(E);let e=(" "+n[3]).slice(1);E.relurl=e_(h,e),eV(E,p),p=E,g+=E.duration,c++,f=0,y=!0}}else if(n[4]){let e=(" "+n[4]).slice(1);p?E.setByteRange(e,p):E.setByteRange(e)}else if(n[5])E.rawProgramDateTime=(" "+n[5]).slice(1),E.tagList.push(["PROGRAM-DATE-TIME",E.rawProgramDateTime]),-1===T&&(T=d.length);
1else{if(!(n=n[0].match(eB))){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 w(s);ek(h,e,["RECENTLY-REMOVED-DATERANGES"]);let t=e.decimalInteger("SKIPPED-SEGMENTS");if(S(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)&&E.tagList.push(g?[s,g]:[s]);break;case"DISCONTINUITY":m++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([e]);break;case"BITRATE":E.tagList.push([e,s]);break;case"DATERANGE":{let e=new w(s);ek(h,e,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),ek(h,e,e.clientAttrs);let t=new P(e,h.dateRanges[e.ID]);t.isValid||h.skippedSegments?h.dateRanges[t.id]=t:k.warn(`Ignoring invalid DATERANGE tag: "${s}"`),E.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{let e=new w(s);ek(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):eC(h,e,t)}break;case"DISCONTINUITY-SEQUENCE":m=parseInt(s);break;case"KEY":{let e=eG(s,t,h);if(e.isSupported()){if("NONE"===e.method){o=void 0;break}o||(o={}),o[e.keyFormat]&&(o=v({},o)),o[e.keyFormat]=e}else k.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${s}"`);break}case"START":h.startTimeOffset=eK(s);break;case"MAP":{let e=new w(s);if(ek(h,e,["BYTERANGE","URI"]),E.duration){let s=new M(r,t);eY(s,e,i,o),u=s,E.initSegment=u,u.rawProgramDateTime&&!E.rawProgramDateTime&&(E.rawProgramDateTime=u.rawProgramDateTime)}else eY(E,e,i,o),u=E,y=!0;break}case"SERVER-CONTROL":{let e=new w(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":{let e=new w(s);h.partTarget=e.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 w(s);ek(h,a,["BYTERANGE","URI"]);let n=new N(a,E,t,r,i);e.push(n),E.duration+=n.duration;break}case"PRELOAD-HINT":{let e=new w(s);ek(h,e,["URI"]),h.preloadHint=e;break}case"RENDITION-REPORT":{let e=new w(s);ek(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&&(eV(E,p),E.cc=m,h.fragmentHint=E,o&&eW(E,o,h));let A=d.length,L=d[0],R=d[A-1];if((g+=h.skippedSegments*h.targetduration)>0&&A&&R){h.averagetargetduration=g/A;let e=R.sn;h.endSN="initSegment"!==e?e:0,h.live||(R.endList=!0),L&&(h.startCC=L.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 eG(e,t,i){var r,s;let a=new w(e);ek(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";l&&a.IV&&!o&&k.error(`Invalid IV: ${a.IV}`);let u=l?e$.resolve(l,t):"",c=(h||"1").split("/").map(Number).filter(Number.isFinite);return new eD(n,u,d,c,o)}function eK(e){let t=new w(e),i=t.decimalFloatingPoint("TIME-OFFSET");return S(i)?i:null}function eH(e,t,i){let r=t[i];r&&(e[i]=r)}function eV(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),S(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function eY(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 eW(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 eq={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},ej={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function eX(e){let{type:t}=e;switch(t){case eq.AUDIO_TRACK:return ej.AUDIO;case eq.SUBTITLE_TRACK:return ej.SUBTITLE;default:return ej.MAIN}}function ez(e,t){let i=e.url;return(void 0===i||0===i.indexOf("data:"))&&(i=t.url),i}class eQ{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}
1startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(A.MANIFEST_LOADING,this.onManifestLoading,this),e.on(A.LEVEL_LOADING,this.onLevelLoading,this),e.on(A.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(A.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){let{hls:e}=this;e.off(A.MANIFEST_LOADING,this.onManifestLoading,this),e.off(A.LEVEL_LOADING,this.onLevelLoading,this),e.off(A.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(A.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:eq.MANIFEST,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:eq.LEVEL,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:eq.AUDIO_TRACK,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:eq.SUBTITLE_TRACK,url:s,deliveryDirectives:a})}load(e){var t;let i;let r=this.hls.config,s=this.getInternalLoader(e);if(s){let t=s.context;if(t&&t.url===e.url){k.trace("[playlist-loader]: playlist request ongoing");return}k.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(i=e.type===eq.MANIFEST?r.manifestLoadPolicy.default:v({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),null!=(t=e.deliveryDirectives)&&t.part){let t;if(e.type===eq.LEVEL&&null!==e.level?t=this.hls.levels[e.level].details:e.type===eq.AUDIO_TRACK&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===eq.SUBTITLE_TRACK&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,r=t.targetduration;if(e&&r){let t=1e3*Math.max(3*e,.8*r);i=v({},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;if(0!==a.indexOf("#EXTM3U")){this.handleManifestParsingError(e,i,Error("no EXTM3U delimiter"),r||null,t);return}t.parsing.start=performance.now(),e$.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=ez(e,i),l=e$.parseMasterPlaylist(a,n);if(l.playlistParsingError){this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);return}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}=e$.parseMasterPlaylistMedia(a,n,l);if(g.length){let e=g.some(e=>!e.url);e||!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 w({}),bitrate:0,url:""}))}s.trigger(A.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=ez(e,i),d=S(n)?n:0,u=S(l)?l:d,c=eX(i),f=e$.parseLevelPlaylist(e.data,h,u,c,d,this.variableList);if(o===eq.MANIFEST){let e={attrs:new w({}),bitrate:0,details:f,name:"",url:h};a.trigger(A.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(A.ERROR,{type:L.NETWORK_E
1RROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===eq.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,i=!1,r,s){let a=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===eq.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===eq.AUDIO_TRACK||e.type===eq.SUBTITLE_TRACK)&&(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 eq.MANIFEST:l=i?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,o=!0;break;case eq.LEVEL:l=i?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,o=!1;break;case eq.AUDIO_TRACK:l=i?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,o=!1;break;case eq.SUBTITLE_TRACK: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};if(r){let i=(null==t?void 0:t.url)||e.url;d.response=y({url:i,data:void 0},r)}this.hls.trigger(A.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=ez(t,r),f=eX(r),g="number"==typeof r.level&&f===ej.MAIN?o:void 0;if(!e.fragments.length){let e=Error("No Segments found in Playlist");n.trigger(A.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){n.trigger(A.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});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case eq.MANIFEST:case eq.LEVEL:n.trigger(A.LEVEL_LOADED,{details:e,level:g||0,id:h||0,stats:i,networkDetails:s,deliveryDirectives:u});break;case eq.AUDIO_TRACK:n.trigger(A.AUDIO_TRACK_LOADED,{details:e,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u});break;case eq.SUBTITLE_TRACK:n.trigger(A.SUBTITLE_TRACK_LOADED,{details:e,id:h||0,groupId:d||"",stats:i,networkDetails:s,deliveryDirectives:u})}}}function eJ(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 eZ(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 e0(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 e1(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 e2={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};function e4(){if("undefined"!=typeof self)return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}let e3=(()=>{let e=e4();try{new e(0,Number.POSITIVE_INFINITY,"")}catch(e){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function e5(e,t){return e.getTime()/1e3-t}class e8{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(A.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(A.MANIFEST_LOADING,this.onManifestLoading,this),e.on(A.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(A.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){let{hls:e}=this;e.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(A.MANIFEST_LOADING,this.onManifestLoading,this),e.off(A.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(A.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(A.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(e0(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 eJ(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=e4();for(let e=0;e<s.length;e++){let t=s[e].type;if(t===e2.emsg&&!i||!r)continue;let n=er(s[e].data);if(n){let i=s[e].pts,r=i+s[e].duration;r>e3&&(r=e3);let l=r-i;l<=0&&(r=i+.25);for(let e=0;e<n.length;e++){let s=n[e];if(!et(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===e3&&(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)&&e1(s,t,i,"audio"===r?e=>e.type===e2.audioId3&&l:"video"===r?e=>e.type===e2.emsg&&n:e=>e.type===e2.audioId3&&l||e.type===e2.emsg&&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||!S(null==n?void 0:n.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));let l=n.programDateTime/1e3-n.start,o=e4();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=e5(r.startDate,l),f=e3,g=r.endDate;if(g)f=e5(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=e5(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=e2.dateRange,s.id=t,this.id3Track.addCue(s),d[i]=s}}i[t]={cues:d,dateRange:r,durationKnown:u}}}}class e6{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(1*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,a=r-i.totalduration,n=r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,s),n)}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(A.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(A.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(A.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(A.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(A.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(A.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(A.ERROR,this.onError,this)}onMediaAttached(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);if(t.live&&n<l&&n>.05&&this.forwardBufferLength>1){let t=Math.round(2/(1+Math.exp(-.75*n-this.edgeStalled))*20)/20;e.playbackRate=Math.min(Math.min(2,Math.max(1,s)),Math.max(1,t))}else 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 e9=["NONE","TYPE-0","TYPE-1",null];var e7={No:"",Yes:"YES",v2:"v2"};class te{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 tt{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 ti(e,t){let i=t.startPTS;if(S(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 if(t.sn>e.sn){let i=e.cc===t.cc;i&&e.minEndPTS?t.start=e.start+(e.minEndPTS-e.start):t.start=e.start+e.duration}else t.start=Math.max(e.start-t.duration,0)}function tr(e,t,i,r,s,a){let n;let l=r-i;l<=0&&(k.warn("Fragment should have a positive duration",t),r=i+t.duration,a=s+t.duration);let o=i,h=r,d=t.startPTS,u=t.endPTS;if(S(d)){let e=Math.abs(d-i);S(t.deltaPTS)?t.deltaPTS=Math.max(e,t.deltaPTS):t.deltaPTS=e,o=Math.max(i,d),i=Math.min(i,d),s=Math.min(s,t.startDTS),h=Math.min(r,u),r=Math.max(r,u),a=Math.max(a,t.endDTS)}let c=i-t.start;0!==t.start&&(t.start=i),t.duration=r-t.start,t.startPTS=i,t.maxStartPTS=o,t.startDTS=s,t.endPTS=r,t.minEndPTS=h,t.endDTS=a;let f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;let g=f-e.startSN,m=e.fragments;for(m[g]=t,n=g;n>0;n--)ti(m[n],m[n-1]);for(n=g;n<m.length-1;n++)ti(m[n],m[n+1]);return e.fragmentHint&&ti(m[m.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,c}function ts(e,t){let i=t.startSN+t.skippedSegments-e.startSN,r=e.fragments;i<0||i>=r.length||ta(t,r[i].start)}function ta(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 tn(e,t,i){var r;
1return null!=e&&e.details?tl(null==(r=e.details)?void 0:r.partList,t,i):null}function tl(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 to(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 th(e,t){let i=to(t);return e.default[`${i?"timeout":"error"}Retry`]}function td(e,t){let i="linear"===e.backoff?1:Math.pow(2,t);return Math.min(i*e.retryDelayMs,e.maxRetryDelayMs)}function tu(e){return y(y({},e),{errorRetry:null,timeoutRetry:null})}function tc(e,t,i,r){return!!e&&t<e.maxNumRetry&&(0===r&&!1===navigator.onLine||!!r&&(r<400||r>499)||!!i)}let tf={search:function(e,t){let i=0,r=e.length-1,s=null,a=null;for(;i<=r;){a=e[s=(i+r)/2|0];let n=t(a);if(n>0)i=s+1;else{if(!(n<0))return a;r=s-1}}return null}};function tg(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===tm(i,r,s))return s;let a=tf.search(t,tm.bind(null,i,r));return a&&(a!==e||!s)?a:s}function tm(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}var tp={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},tE={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class tT{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;let 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 te(s,a>=0?a:void 0,e7.No)}}}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?1:0)+(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),S(e.startPTS)&&S(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){let e=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;
1e.forEach(e=>{var t;e.initSegment&&e.initSegment.relurl!==(null==(t=r)?void 0:t.relurl)||(e.initSegment=r)})}if(t.skippedSegments){if(t.deltaUpdateFailed=t.fragments.some(e=>!e),t.deltaUpdateFailed){k.warn("[level-helper] Previous playlist missing segments skipped 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 t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){let r=v({},e);return i&&i.forEach(e=>{delete r[e]}),Object.keys(t).forEach(e=>{let i=new P(t[e].attr,r[e]);i.isValid?r[e]=i:k.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)}),r}(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges))}let n=t.fragments;if(a){k.warn("discontinuity sliding from playlist, take drift into account");for(let e=0;e<n.length;e++)n[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?tr(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):ts(e,t),n.length&&(t.totalduration=t.edge-n[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let l=t.advancedDateTime;if(t.advanced&&l){let e=t.edge;t.driftStart||(t.driftStartTime=l,t.driftStart=e),t.driftEndTime=l,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=u+r.ageHeader,f=Math.min(c-r.partTarget,1.5*r.targetduration);if(f>0){if(i&&f>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${f} with playlist age: ${r.age}`),f=0;else{let e=Math.floor(f/r.targetduration);if(l+=e,void 0!==o){let e=Math.round(f%r.targetduration/r.partTarget);o+=e}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${u.toFixed(2)}s goal: ${f} skip sn ${e} to part ${o}`)}r.tuneInGoal=f}if(n=this.getDeliveryDirectives(r,t.deliveryDirectives,l,o),e||!d){this.loadPlaylist(n);return}}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?e7.v2:e7.Yes:e7.No}(e,i);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=e7.No),new te(i,r,s)}checkRetry(e){let t=e.details,i=to(e),r=e.errorAction,{action:s,retryCount:a=0,retryConfig:n}=r||{},l=!!r&&!!n&&(s===tp.RetryRequest||!r.resolved&&s===tp.SendAlternateToPenaltyBox);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=td(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 ty extends tT{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(A.MANIFEST_LOADING,this.onManifestLoading,this),e.on(A.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(A.LEVEL_LOADED,this.onLevelLoaded,this),e.on(A.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(A.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(A.FRAG_LOADED,this.onFragLoaded,this),e.on(A.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(A.MANIFEST_LOADING,this.onManifestLoading,this),e.off(A.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(A.LEVEL_LOADED,this.onLevelLoaded,this),e.off(A.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(A.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(A.FRAG_LOADED,this.onFragLoaded,this),e.off(A.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}
1startLoad(){let e=this._levels;e.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;let 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 tt(e),a[g]=i,r.push(i)),tv(i,"audio",l),tv(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||eO(e,"audio"))&&(!t||eO(t,"video"))));if((s||a)&&n&&(l=l.filter(({videoCodec:e,width:t,height:i})=>!!e||!!(t&&i))),0===l.length){Promise.resolve().then(()=>{if(this.hls){let e=Error("no level with compatible codecs found in manifest");this.hls.trigger(A.ERROR,{type:L.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}});return}t.audioTracks&&tS(i=t.audioTracks.filter(e=>!e.audioCodec||eO(e.audioCodec,"audio"))),t.subtitles&&tS(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(A.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(A.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=v({},a,{level:e,maxBitrate:a.maxBitrate,attrs:a.attrs,uri:a.uri,urlId:a.urlId});delete l._attrs,delete l._urlId,this.hls.trigger(A.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===eq.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(void 0!==t&&t.type===ej.MAIN){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(A.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(A.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 tv(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 tS(e){let t={};e.forEach(e=>{let i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}var tA={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class tL{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(A.BUFFER_APPENDED,this.onBufferAppended,this),e.on(A.FRAG_BUFFERED,this.onFragBuffered,this),e.on(A.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){let{hls:e}=this;e.off(A.BUFFER_APPENDED,this.onBufferAppended,this),e.off(A.FRAG_BUFFERED,this.onFragBuffered,this),e.off(A.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=tI(i),a=this.fragments[s];if(!a||a.buffered&&i.gap)return;let n=!i.relurl;if(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;let e=a.body.endList=i.endList||a.body.endList;e&&(this.endListFragments[a.body.type]=a),tR(a)||this.removeParts(i.sn-1,i.type)}else 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=tI(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&&tR(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||tR(t))}getState(e){let t=tI(e),i=this.fragments[t];return i?i.buffered?tR(i)?tA.PARTIAL:tA.OK:tA.APPENDING:tA.NOT_LOADED}isTimeBuffered(e,t,i){let r,s;for(let a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,s=i.end(a)+this.bufferPadding,e>=r&&t<=s)return!0;if(t<=r)break}return!1}onFragLoaded(e,t){let{frag:i,part:r}=t;if("initSegment"===i.sn||i.bitrateTest)return;let s=tI(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=tI(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=tI(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 tR(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 tI(e){return`${e.type}_${e.level}_${e.urlId}_${e.sn}
1`}class tD{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 t_({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])){l(tk(e));return}e.gap=!1}let o=this.loader=e.loader=s?new s(r):new a(r),h=tb(e),d=tu(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 t_({type:L.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:y({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 t_({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 t_({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){l(tk(e,t));return}let o=this.loader=e.loader=s?new s(r):new a(r),h=tb(e,t),d=tu(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 t_({type:L.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:y({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 t_({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 t_({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(S(s)&&S(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 tk(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 t_(r)}class t_ extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class tC{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 t_({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=i.loader,s=new r(i);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((r,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};s.load(n,o,{onSuccess:(e,t,i,s)=>{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"),s));l.decryptdata.key=n.decryptdata.key=new Uint8Array(e.data),n.keyLoader=null,l.loader=null,r({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,y({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 tw{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 tP={length:0,start:()=>0,end:()=>0};class tx{static isBuffered(e,t){try{if(e){let i=tx.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;let s=tx.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),tP}}}class tO{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=tF(),this.buffering={audio:tF(),video:tF(),audiovideo:tF()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=s,this.partial=a}}function tF(){return{start:0,executeStart:0,executeEnd:0,end:0}}function tM(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 tN(e,t){if(e){let i=e.start+t;e.start=e.startPTS=i,e.endPTS=i+e.duration}}function tU(e,t){let i=t.fragments;for(let t=0,r=i.length;t<r;t++)tN(i[t],e);t.fragmentHint&&tN(t.fragmentHint,e),t.alignedSliding=!0}function tB(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=tM(i,a.cc)||i[Math.round(i.length/2)-1],l=a.programDateTime,o=n.programDateTime;if(null===l||null===o)return;let h=(o-l)/1e3-(n.start-a.start);tU(h,e)}class t${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 tG{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 tK{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],E=257*c[i]^16843008*i;r[f]=E<<24|E>>>8,s[f]=E<<16|E>>>16,a[f]=E<<8|E>>>24,n[f]=E,E=16843009*p^65537*m^257*l^16843008*f,o[i]=E<<24|E>>>8,h[i]=E<<16|E>>>16,d[i]=E<<8|E>>>24,u[i]=E,f?(f=l^c[c[c[p^l]]],g^=c[c[g]]):f=g=1}}expandKey(e){let t,i,r,s;let a=this.uint8ArrayToUint32Array_(e),n=!0,l=0;for(;l<a.length&&n;)n=a[l]===this.key[l],l++;if(n)return;this.key=a;let o=this.keySize=a.length;if(4!==o&&6!==o&&8!==o)throw Error("Invalid aes key size="+o);let h=this.ksRows=(o+6+1)*4,d=this.keySchedule=new Uint32Array(h),u=this.invKeySchedule=new Uint32Array(h),c=this.sBox,f=this.rcon,g=this.invSubMix,m=g[0],p=g[1],E=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]]^E[c[s>>>8&255]]^T[c[255&s]],u[i]=u[i]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,i){let r,s,a,n,l,o,h,d,u,c,f,g,m,p;let E=this.keySize+6,T=this.invKeySchedule,y=this.invSBox,v=this.invSubMix,S=v[0],A=v[1],L=v[2],R=v[3],I=this.uint8ArrayToUint32Array_(i),D=I[0],b=I[1],k=I[2],_=I[3],C=new Int32Array(e),w=new Int32Array(C.length),P=this.networkToHostOrderSwap;for(;t<C.length;){for(p=1,u=P(C[t]),c=P(C[t+1]),f=P(C[t+2]),g=P(C[t+3]),l=u^T[0],o=g^T[1],h=f^T[2],d=c^T[3],m=4;p<E;p++)r=S[l>>>24]^A[o>>16&255]^L[h>>8&255]^R[255&d]^T[m],s=S[o>>>24]^A[h>>16&255]^L[d>>8&255]^R[255&l]^T[m+1],a=S[h>>>24]^A[d>>16&255]^L[l>>8&255]^R[255&o]^T[m+2],n=S[d>>>24]^A[l>>16&255]^L[o>>8&255]^R[255&h]^T[m+3],l=r,o=s,h=a,d=n,m+=4;r=y[l>>>24]<<24^y[o>>16&255]<<16^y[h>>8&255]<<8^y[255&d]^T[m],s=y[o>>>24]<<24^y[h>>16&255]<<16^y[d>>8&255]<<8^y[255&l]^T[m+1],a=y[h>>>24]<<24^y[d>>16&255]<<16^y[l>>8&255]<<8^y[255&o]^T[m+2],n=y[d>>>24]<<24^y[l>>16&255]<<16^y[o>>8&255]<<8^y[255&h]^T[m+3],w[t]=P(r^D),w[t+1]=P(n^b),w[t+2]=P(a^k),w[t+3]=P(s^_),D=u,b=c,k=f,_=g,t+=4}return w.buffer}}class tH{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{let 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);return(this.reset(),this.removePKCS7Padding)?function(e){let t=e.byteLength,i=t&&new DataView(e.buffer).getUint8(t-1);return i?j(e,0,t-i):e}(i):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=eS(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 tK),l.expandKey(t),this.currentResult=l.decrypt(n.buffer,0,i),this.currentIV=j(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 tG(r,t)),this.fastAesKey.expandKey().then(t=>{if(!r)return Promise.reject(Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");let s=new t$(r,new Uint8Array(i));return s.decrypt(e.buffer,t)}).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=j(e,0,i),this.remainderData=j(e,i)),t}logOnce(e){this.logEnabled&&(k.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}let tV={toString: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}},tY={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class tW extends tw{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=tY.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=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 tD(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new tH(e.config),e.on(A.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=tY.STOPPED}_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],t=tx.isBuffered(this.media,e.start+e.duration/2);return t}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===tY.STOPPED&&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=tx.bufferInfo(r||i,a,e.maxBufferHole);if(this.log(`media seeking to ${S(a)?a.toFixed(3):a}, state: ${s}`),this.state===tY.ENDED)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=tY.STOPPED,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!==tY.FRAG_LOADING&&(this.fragCurrent||i!==tY.PARSING)||(this.fragmentTracker.removeFragment(e),this.state=tY.IDLE);return}"payload"in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(A.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t)}).catch(t=>{this.state!==tY.STOPPED&&this.state!==tY.ERROR&&(this.warn(t),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this,r=i.getState(e);if(r===tA.APPENDING){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)===tA.PARTIAL&&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(A.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(A.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(A.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=tY.IDLE,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(A.FRAG_BUFFERED,{stats:n,frag:r,part:null,id:e.type}),this.tick()}).catch(t=>{this.state!==tY.STOPPED&&this.state!==tY.ERROR&&(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===ej.MAIN?"level":"track"} ${e.level} (frag:[${(null!=(i=e.startPTS)?i:NaN).toFixed(3)}-${(null!=(r=e.endPTS)?r:NaN).toFixed(3)}] > buffer:${n?tV.toString(tx.getBuffered(n)):"(detached)"})`),this.state=tY.IDLE,n&&(!this.loadedmetadata&&e.type==ej.MAIN&&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 tO(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;let 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=tY.KEY_LOADING,this.fragCurrent=e,l=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(A.KEY_LOADED,e),this.state===tY.KEY_LOADING&&(this.state=tY.IDLE),e}),this.hls.trigger(A.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;let 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=tY.FRAG_LOADING,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(A.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))}`),S(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=tY.FRAG_LOADING;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(A.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(A.FRAG_LOADED,r);let n=tn(i,e.sn,t.index+1)||tl(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(A.ERROR,t)}else this.hls.trigger(A.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!==tY.PARSING){this.fragCurrent||this.state===tY.STOPPED||this.state===tY.ERROR||(this.state=tY.IDLE);return}let{frag:i,part:r,level:s}=t,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a),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?tn(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!==tY.PARSING)return;let{data1:n,data2:l}=e,o=n;if(n&&l&&(o=eS(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(A.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!tx.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let i=t.currentTime,r=tx.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 S(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){let{config:{maxBufferHole:r}}=this,s=tx.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 tx.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=ej.MAIN){let i=this.fragmentTracker.getAppendedFrag(e,ej.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){let i;let 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(i===tA.OK||i===tA.PARTIAL&&!!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||!S(t))return null;let r=e[0].programDateTime;if(t<(r||0))return null;let s=e[e.length-1].endProgramDateTime;if(t>=(s||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)),s=i.endProgramDateTime||0;return s-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=tf.search(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;let{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?tg(a,n,e,e>t-h?0:h):n[n.length-1]){let e=r.sn-i.startSN,t=this.fragmentTracker.getState(r);if((t===tA.OK||t===tA.PARTIAL&&r.gap)&&(a=r),a&&r.sn===a.sn&&(!u||d[0].fragment.sn>r.sn)){let t=a&&r.level===a.level;if(t){let t=n[e+1];r=r.sn<l&&this.fragmentTracker.getState(t)!==tA.OK?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=e.alignedSliding&&S(l);if(!t||!o&&!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){k.log("No fragments to align");return}let a=tM(r,s[0].cc);if(!a||a&&!a.startPTS){k.log("No frag in previous level to align on");return}return a}(i.details,t);e&&S(e.start)&&(k.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),tU(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&&S(s)&&(k.log(`Adjusting PTS using programDateTime delta ${r-i}ms, sliding:${s.toFixed(3)} ${e.url} `),tU(s,e))}(e,a.details),e.alignedSliding||!a.details||e.skippedSegments||ts(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&&S(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===tY.FRAG_LOADING_WAITING_RETRY)||(this.state=tY.IDLE)}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)){this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(i=this.fragCurrent)?void 0:i.url}`);return}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&&l===tp.RetryRequest&&h){this.resetStartWhenNotLoaded(null!=(r=this.levelLastLoaded)?r:s.level);let i=td(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=tY.FRAG_LOADING_WAITING_RETRY}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)===tp.SendAlternateToPenaltyBox?this.state=tY.WAITING_LEVEL:this.state=tY.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===tY.PARSING||this.state===tY.PARSED){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===ej.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==tY.STOPPED&&(this.state=tY.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;let r=tx.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===tY.ENDED&&this.resetLoadingState()}
1resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=tY.IDLE}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){this.warn("level.details undefined");return}let n=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:tr(a,e,n.startPTS,n.endPTS,n.startDTS,n.endDTS);return this.hls.trigger(A.LEVEL_PTS_UPDATED,{details:a,level:i,drift:
1o,type:s,frag:e,start:n.startPTS,end:n.endPTS}),!0}return t},!1);if(n)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(A.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=tY.PARSED,this.hls.trigger(A.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 tq(){return self.SourceBuffer||self.WebKitSourceBuffer}function tj(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class tX{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=eS(this.cachedData,e),this.cachedData=null);let r=Q(e,0),s=r?r.length:0,a=this._audioTrack,n=this._id3Track,l=r?ee(r):void 0,o=e.length;for((null===this.basePTS||0===this.frameIndex&&S(l))&&(this.basePTS=tz(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:e2.audioId3,duration:Number.POSITIVE_INFINITY});s<o;){if(this.canParse(e,s)){let t=this.appendFrame(a,e,s);t?(this.frameIndex++,this.lastPTS=t.sample.pts,s+=t.length,i=s):s=o}else Z(e,s)?(r=Q(e,s),n.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:e2.audioId3,duration:Number.POSITIVE_INFINITY}),s+=r.length,i=s):s++;if(s===o&&i!==o){let t=j(e,i);this.cachedData?this.cachedData=eS(this.cachedData,t):this.cachedData=t}}return{audioTrack:a,videoTrack:tj(),id3Track:n,textTrack:tj()}}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:tj(),id3Track:this._id3Track,textTrack:tj()}}destroy(){}}let tz=(e,t,i)=>{if(S(e))return 90*e;let r=i?9e4*i.baseTime/i.timescale:0;return 9e4*t+r};function tQ(e,t){return 255===e[t]&&(246&e[t+1])==240}function tJ(e,t){return 1&e[t+1]?7:9}function tZ(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function t0(e,t){return t+1<e.length&&tQ(e,t)}function t1(e,t,i,r,s){if(!e.samplerate){let a=function(e,t,i,r){let s,a,n,l;let o=navigator.userAgent.toLowerCase(),h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=((192&t[i+2])>>>6)+1;let d=(60&t[i+2])>>>2;if(d>h.length-1){e.trigger(A.ERROR,{type:L.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${d}`});return}return n=(1&t[i+2])<<2|(192&t[i+3])>>>6,k.log(`manifest codec:${r}, ADTS type:${s}, samplingIndex:${d}`),/firefox/i.test(o)?d>=6?(s=5,l=[,,,,],a=d-3):(s=2,l=[,,],a=d):-1!==o.indexOf("android")?(s=2,l=[,,],a=d):(s=5,l=[,,,,],r&&(-1!==r.indexOf("mp4a.40.29")||-1!==r.indexOf("mp4a.40.5"))||!r&&d>=6?a=d-3:((r&&-1!==r.indexOf("mp4a.40.2")&&(d>=6&&1===n||/vivaldi/i.test(o))||!r&&1===n)&&(s=2,l=[,,]),a=d)),l[0]=s<<3,l[0]|=(14&d)>>1,l[1]|=(1&d)<<7,l[1]|=n<<3,5===s&&(l[1]|=(14&a)>>1,l[2]=(1&a)<<7,l[2]|=8,l[3]=0),{config:l,samplerate:h[d],channelCount:n,codec:"mp4a.40."+s,manifestCodec:r}}(t,i,r,s);a&&(e.config=a.config,e.samplerate=a.samplerate,e.channelCount=a.channelCount,e.codec=a.codec,e.manifestCodec=a.manifestCodec,k.log(`parsed codec:${e.codec}, rate:${a.samplerate}, channels:${a.channelCount}`))}}function t2(e,t,i,r,s){let a;let n=9216e4/e.samplerate,l=r+s*n,o=function(e,t){let i=tJ(e,t);if(t+i<=e.length){let r=tZ(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);if(o){let{frameLength:r,headerLength:s}=o,n=s+r,h=Math.max(0,i+n-t.length);h?(a=new Uint8Array(n-s)).set(t.subarray(i+s,t.length),0):a=t.subarray(i+s,i+n);let d={unit:a,pts:l};return h||e.samples.push(d),{sample:d,length:n,missing:h}}let h=t.length-i;(a=new Uint8Array(h)).set(t.subarray(i,t.length),0);let d={unit:a,pts:l};return{sample:d,length:h,missing:-1}}let t4=/\/emsg[-/]ID3/i,t3=null,t5=[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],t8=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],t6=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],t9=[0,1,1,4];function t7(e,t,i,r,s){if(i+24>t.length)return;let a=ie(t,i);if(a&&i+a.frameLength<=t.length){let n=9e4*a.samplesPerFrame/a.sampleRate,l=r+s*n,o={unit:t.subarray(i,i+a.frameLength),pts:l,dts:l};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}function ie(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*t5[14*(3===i?3-r:3===r?3:4)+s-1],h=t8[3*(3===i?0:2===i?1:2)+a],d=t6[i][r],u=t9[r];if(null===t3){let e=navigator.userAgent||"",t=e.match(/Chrome\/(\d+)/i);t3=t?parseInt(t[1]):0}let c=!!t3&&t3<=87;return c&&2===r&&o>=224e3&&0===l&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:3===l?1:2,frameLength:Math.floor(d*o/h+n)*u,samplesPerFrame:8*d*u}}}
1function it(e,t){return 255===e[t]&&(224&e[t+1])==224&&(6&e[t+1])!=0}function ii(e,t){return t+1<e.length&&it(e,t)}class ir{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?(this.word<<=e,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&2147483648>>>e)!=0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}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 E=h(),T=h(),y=o(1);0===y&&u(1),u(1),d()&&(r=h(),s=h(),a=h(),n=h());let v=[1,1];if(d()&&d()){let e=l();switch(e){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((E+1)*16-2*r-2*s),height:(2-y)*(T+1)*16-(y?2:4)*(a+n),pixelRatio:v}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class is{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new tH(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){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=16*Math.floor((e.length-48)/160)+16,i=new Int8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)i.set(e.subarray(t,t+16),r);return i}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=eR(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){r();return}let s=e[t].units;for(;!(i>=s.length);i++){let a=s[i];if(!(a.data.length<=48)&&(1===a.type||5===a.type)&&(this.decryptAvcSample(e,t,i,r,a),!this.decrypter.isSync()))return}}}}class ia{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=ia.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===io(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:ec[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=ia.createTrack("video"),this._audioTrack=ia.createTrack("audio",r),this._id3Track=ia.createTrack("id3"),this._txtTrack=ia.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,E=this._pmtId,T=e.length;if(this.remainderData&&(T=(e=eS(this.remainderData,e)).length,this.remainderData=null),T<188&&!r)return this.remainderData=e,{audioTrack:n,videoTrack:a,id3Track:l,textTrack:o};let y=Math.max(0,ia.syncOffset(e));(T-=(T-y)%188)<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,T,e.buffer.byteLength-T));let v=0;for(let t=y;t<T;t+=188)if(71===e[t]){let r;let T=!!(64&e[t+1]),v=io(e,t),A=(48&e[t+3])>>4;if(A>1){if((r=t+5+e[t+4])===t+188)continue}else r=t+4;switch(v){case h:T&&(d&&(s=ih(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=ih(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=ih(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 S,I;T&&(r+=e[r]+1),E=this._pmtId=(31&(S=e)[(I=r)+10])<<8|S[I+11];break;case E:{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=io(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 @${y} to parse all TS packets.`),m=null,t=y-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(A.ERROR,A.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;let{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;let{audioTrack:i,videoTrack:r,id3Track:s,textTrack:a}=e,n=r.pesData,l=i.pesData,o=s.pesData;if(n&&(t=ih(n))?(this.parseAVCPES(r,a,t,!0),r.pesData=null):r.pesData=n,l&&(t=ih(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=ih(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 is(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;let a=this.parseAVCNALu(e,i.data),n=this.avcSample,l=!1;i.data=null,n&&a.length&&!e.audFound&&(id(n,e),n=this.avcSample=il(!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 ir(a).readSliceType();(2===e||4===e||7===e||9===e)&&(t=!0)}t&&null!=(o=n)&&o.frame&&!n.key&&(id(n,e),n=this.avcSample=null),n||(n=this.avcSample=il(!0,i.pts,i.dts,"")),n.frame=!0,n.key=t;break}case 5:s=!0,null!=(a=n)&&a.frame&&!n.key&&(id(n,e),n=this.avcSample=null),n||(n=this.avcSample=il(!0,i.pts,i.dts,"")),n.key=!0,n.frame=!0;break;case 6:s=!0,eL(r.data,1,i.pts,t.samples);break;case 7:if(s=!0,l=!0,!e.sps){let t=r.data,i=new ir(t),s=i.readSPS();e.width=s.width,e.height=s.height,e.pixelRatio=s.pixelRatio,e.sps=[t],e.duration=this._duration;let a=t.subarray(1,4),n="avc1.";for(let e=0;e<3;e++){let t=a[e].toString(16);t.length<2&&(t="0"+t),n+=t}e.codec=n}break;case 8:s=!0,e.pps||(e.pps=[r.data]);break;case 9:s=!1,e.audFound=!0,n&&id(n,e),n=this.avcSample=il(!1,i.pts,i.dts,"");break;case 12:s=!0;break;default:s=!1,n&&(n.debug+="unknown NAL "+r.type+" ")}if(n&&s){let e=n.units;e.push(r)}}),r&&n&&(id(n,e),this.avcSample=null)}getLastNalUnit(e){var t;let i;let 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;let 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?0:1;continue}if(1===n){n=i?0:2;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&&!t0(o,i);i++);if(i!==n){let e;let t=i<r-1;e=t?`AAC PES did not start with ADTS header,offset:${i}`:"No ADTS header found in AAC PES";let s=Error(e);if(k.warn(`parsing error: ${e}`),this.observer.emit(A.ERROR,A.ERROR,{type:L.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:s,reason:e}),!t)return}if(t1(e,this.observer,o,i,this.audioCodec),void 0!==t.pts)s=t.pts;else if(l){let t=9216e4/e.samplerate;s=l.sample.pts+t}else{k.warn("[tsdemuxer]: AAC PES unknown PTS");return}let h=0;for(;i<r;){if(a=t2(e,o,i,s,h),i+=a.length,a.missing){this.aacOverFlow=a;break}for(h++;i<r-1&&!t0(o,i);i++);}}parseMPEGPES(e,t){let i=t.data,r=i.length,s=0,a=0,n=t.pts;if(void 0===n){k.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<r;)if(ii(i,a)){let t=t7(e,i,a,n,s);if(t)a+=t.length,s++;else break}else a++}parseID3PES(e,t){if(void 0===t.pts){k.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let i=v({},t,{type:this._avcTrack?e2.emsg:e2.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function il(e,t,i,r){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:r,length:0}}function io(e,t){return((31&e[t+1])<<8)+e[t+2]}function ih(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)}t=l[0];let o=(t[0]<<16)+(t[1]<<8)+t[2];if(1===o){if((i=(t[4]<<8)+t[5])&&i>e.size-6)return null;let o=t[7];192&o&&(s=(14&t[9])*536870912+(255&t[10])*4194304+(254&t[11])*16384+(255&t[12])*128+(254&t[13])/2,64&o?s-(a=(14&t[14])*536870912+(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}t=t.subarray(h),i-=h,h=0}
1d.set(t,n),n+=i}return i&&(i-=r+3),{data:d,pts:s,dts:a,len:i}}return null}function id(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){let i=t.samples,r=i.length;if(r){let t=i[r-1];e.pts=t.pts,e.dts=t.dts}else{t.dropped++;return}}t.samples.push(e)}e.debug.length&&k.log(e.pts+"/"+e.dts+":"+e.debug)}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]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);else if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);else if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t||3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}class ic{static init(){let e;for(e in ic.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:[]},ic.types)ic.types.hasOwnProperty(e)&&(ic.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);let t=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]),i=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]);ic.HDLR_TYPES={video:t,audio:i};let r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);ic.STTS=ic.STSC=ic.STCO=s,ic.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),ic.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),ic.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),ic.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let a=new Uint8Array([105,115,111,109]),n=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);ic.FTYP=ic.box(ic.types.ftyp,a,l,a,n),ic.DINF=ic.box(ic.types.dinf,ic.box(ic.types.dref,r))}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 ic.box(ic.types.hdlr,ic.HDLR_TYPES[e])}static mdat(e){return ic.box(ic.types.mdat,e)}static mdhd(e,t){t*=e;let i=Math.floor(t/4294967296),r=Math.floor(t%4294967296);return ic.box(ic.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 ic.box(ic.types.mdia,ic.mdhd(e.timescale,e.duration),ic.hdlr(e.type),ic.minf(e))}static mfhd(e){return ic.box(ic.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?ic.box(ic.types.minf,ic.box(ic.types.smhd,ic.SMHD),ic.DINF,ic.stbl(e)):ic.box(ic.types.minf,ic.box(ic.types.vmhd,ic.VMHD),ic.DINF,ic.stbl(e))}static moof(e,t,i){return ic.box(ic.types.moof,ic.mfhd(e),ic.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=ic.trak(e[t]);return ic.box.apply(null,[ic.types.moov,ic.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(ic.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=ic.trex(e[t]);return ic.box.apply(null,[ic.types.mvex,...i])}static mvhd(e,t){t*=e;let i=Math.floor(t/4294967296),r=Math.floor(t%4294967296),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return ic.box(ic.types.mvhd,s)}static sdtp(e){let t,i;let r=e.samples||[],s=new Uint8Array(4+r.length);for(t=0;t<r.length;t++)i=r[t].flags,s[t+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return ic.box(ic.types.sdtp,s)}static stbl(e){return ic.box(ic.types.stbl,ic.stsd(e),ic.box(ic.types.stts,ic.STTS),ic.box(ic.types.stsc,ic.STSC),ic.box(ic.types.stsz,ic.STSZ),ic.box(ic.types.stco,ic.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=ic.box(ic.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 ic.box(ic.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,ic.box(ic.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),ic.box(ic.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 ic.box(ic.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]),ic.box(ic.types.esds,ic.esds(e)))}static mp3(e){let t=e.samplerate;return ic.box(ic.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?ic.box(ic.types.stsd,ic.STSD,ic.avc1(e)):"mp3"===e.segmentCodec&&"mp3"===e.codec?ic.box(ic.types.stsd,ic.STSD,ic.mp3(e)):ic.box(ic.types.stsd,ic.STSD,ic.mp4a(e))}static tkhd(e){let t=e.id,i=e.duration*e.timescale,r=e.width,s=e.he
1ight,a=Math.floor(i/4294967296),n=Math.floor(i%4294967296);return ic.box(ic.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=ic.sdtp(e),r=e.id,s=Math.floor(t/4294967296),a=Math.floor(t%4294967296);return ic.box(ic.types.traf,ic.box(ic.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),ic.box(ic.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])),ic.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,ic.box(ic.types.trak,ic.tkhd(e),ic.mdia(e))}static trex(e){let t=e.id;return ic.box(ic.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;let o=e.samples||[],h=o.length,d=12+16*h,u=new Uint8Array(d);for(t+=8+d,u.set(["video"===e.type?1:0,0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),i=0;i<h;i++)s=(r=o[i]).duration,a=r.size,n=r.flags,l=r.cts,u.set([s>>>24&255,s>>>16&255,s>>>8&255,255&s,a>>>24&255,a>>>16&255,a>>>8&255,255&a,n.isLeading<<2|n.dependsOn,n.isDependedOn<<6|n.hasRedundancy<<4|n.paddingValue<<1|n.isNonSync,61440&n.degradPrio,15&n.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return ic.box(ic.types.trun,u)}static initSegment(e){ic.types||ic.init();let t=ic.moov(e),i=new Uint8Array(ic.FTYP.byteLength+t.byteLength);return i.set(ic.FTYP),i.set(t,ic.FTYP.byteLength),i}}function ig(e,t,i=1,r=!1){let s=e*t*i;return r?Math.round(s):s}function im(e,t=!1){return ig(e,1e3,11111111111111112e-21,t)}ic.types=void 0,ic.HDLR_TYPES=void 0,ic.STTS=void 0,ic.STSC=void 0,ic.STCO=void 0,ic.STSZ=void 0,ic.VMHD=void 0,ic.SMHD=void 0,ic.STSD=void 0,ic.FTYP=void 0,ic.DINF=void 0;let ip=null,iE=null;class iT{constructor(e,t,i,r=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,null===ip){let e=navigator.userAgent||"",t=e.match(/Chrome\/(\d+)/i);ip=t?parseInt(t[1]):0}if(null===iE){let e=navigator.userAgent.match(/Safari\/(\d+)/i);iE=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<-4294967296?(t=!0,iy(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;let g=s,m=s,p=e.pid>-1,E=t.pid>-1,T=t.samples.length,y=e.samples.length>0,v=n&&T>0||T>1,S=(!p||y)&&(!E||v)||this.ISGenerated||n;if(S){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(y&&v){let i=this.getVideoStartPts(t.samples),r=iy(e.samples[0].pts,i)-i,s=r/t.inputTimeScale;g+=Math.max(0,s),m+=Math.max(0,-s)}if(y){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,E||v||l===ej.AUDIO?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=iv(i,s,this._initPTS,this._initDTS)),r.samples.length&&(u=iS(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;
1let 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):ic.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:ic.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,iy(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;let l=e.inputTimeScale,o=e.samples,h=[],d=o.length,u=this._initPTS,c=this.nextAvcDts,f=8,g=this.videoSampleDuration,m=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,E=!1;if(!i||null===c){let e=o[0].pts-iy(o[0].dts,o[0].pts);c=t*l-e}let T=u.baseTime*l/u.timescale;for(let e=0;e<d;e++){let t=o[e];t.pts=iy(t.pts-T,c),t.dts=iy(t.dts-T,c),t.dts<o[e>0?e-1:e].dts&&(E=!0)}E&&o.sort(function(e,t){let i=e.dts-t.dts,r=e.pts-t.pts;return i||r}),s=o[0].dts,a=o[o.length-1].dts;let y=a-s,S=y?Math.round(y/(d-1)):g||e.inputTimeScale/30;if(i){let e=s-c,t=e>S,i=e<-1;if((t||i)&&(t?k.warn(`AVC: ${im(e,!0)} ms (${e}dts) hole between fragments detected, filling it`):k.warn(`AVC: ${im(-e,!0)} ms (${e}dts) overlapping between fragments detected`),!i||c>=o[0].pts)){s=c;let t=o[0].pts-e;o[0].dts=s,o[0].pts=t,k.log(`Video: First PTS/DTS adjusted: ${im(t,!0)}/${im(s,!0)}, delta: ${im(e,!0)} ms`)}}s=Math.max(0,s);let I=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,I+=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 b=D+4*I+8;try{n=new Uint8Array(b)}catch(e){this.observer.emit(A.ERROR,A.ERROR,{type:L.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:b,reason:`fail allocating video mdat ${b}`});return}let _=new DataView(n.buffer);_.setUint32(0,b),n.set(ic.types.mdat,4);let C=!1,w=Number.POSITIVE_INFINITY,P=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let e=0;e<d;e++){let t;let 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;_.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:S;if(t=e>0?i.pts-o[e-1].pts:S,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:C=!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),x=Math.max(x,g),P=Math.min(P,t),O=Math.max(O,t),h.push(new iA(i.key,g,a,u))}if(h.length){if(ip){if(ip<70){let e=h[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(iE&&O-P<x-w&&S/x<.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:S;h[t].cts=0,e=r}}}g=C||!g?S:g,this.nextAvcDts=c=a+g,this.videoSampleDuration=g,this.isVideoContiguous=!0;let F=ic.moof(e.sequenceNumber++,s,v({},e,{samples:h})),M={data1:F,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;let 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.typeSupp
1orted.mpeg,f=[],g=void 0!==s,m=e.samples,p=c?0:8,E=this.nextAudioPts||-1,T=t*n,y=u.baseTime*n/u.timescale;if(this.isAudioContiguous=i=i||m.length&&E>0&&(r&&9e3>Math.abs(T-E)||Math.abs(iy(m[0].pts-y,T)-E)<20*d),m.forEach(function(e){e.pts=iy(e.pts-y,T)}),!i||E<0){if(!(m=m.filter(e=>e.pts>=0)).length)return;E=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=E;i<m.length;i++){let s=m[i],a=s.pts,l=a-r,o=Math.abs(1e3*l/n);if(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=E=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=E=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 S=null,I=null,D=0,b=m.length;for(;b--;)D+=m[b].unit.byteLength;for(let t=0,r=m.length;t<r;t++){let r=m[t],s=r.unit,n=r.pts;if(null!==I){let e=f[t-1];e.duration=Math.round((n-I)/o)}else{if(i&&"aac"===e.segmentCodec&&(n=E),S=n,!(D>0))return;D+=p;try{a=new Uint8Array(D)}catch(e){this.observer.emit(A.ERROR,A.ERROR,{type:L.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:D,reason:`fail allocating audio mdat ${D}`});return}if(!c){let e=new DataView(a.buffer);e.setUint32(0,D),a.set(ic.types.mdat,4)}}a.set(s,p);let l=s.byteLength;p+=l,f.push(new iA(!0,h,l,0)),I=n}let _=f.length;if(!_)return;let C=f[f.length-1];this.nextAudioPts=E=I+o*C.duration;let w=c?new Uint8Array(0):ic.moof(e.sequenceNumber++,S/o,v({},e,{samples:f}));e.samples=[];let P=S/n,x=E/n,O={data1:w,data2:a,startPTS:P,endPTS:x,startDTS:P,endDTS:x,type:"audio",hasAudio:!0,hasVideo:!1,nb:_};return this.isAudioContiguous=!0,O}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){k.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}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 iy(e,t){let i;if(null===t)return e;for(i=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=i;return e}function iv(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=iy(s.pts-i.baseTime*a/i.timescale,t*a)/a,s.dts=iy(s.dts-r.baseTime*a/r.timescale,t*a)/a}let n=e.samples;return e.samples=[],{samples:n}}function iS(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=iy(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 iA{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 iL(e)}}class iL{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?0:1}}function iR(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===O.VIDEO?"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="undefined"!=typeof self&&self.Date.now}let iI=[{demux:class{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=tj("video",1),a=this.audioTrack=tj("audio",1),n=this.txtTrack=tj("text",1);if(this.id3Track=tj("id3",1),this.timeOffset=0,!(null!=e&&e.byteLength))return;let l=ey(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=ec.text,s.sampleDuration=0,s.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return eT(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=eS(this.remainderData,e));let t=function(e){let t={valid:null,remainder:null},i=eT(e,["moof"]);if(!i)return t;if(i.length<2)return t.remainder=e,t;let r=i[i.length-1];return t.valid=j(e,0,r.byteOffset-8),t.remainder=j(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=eA(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=eA(e,t),{videoTrack:t,audioTrack:tj(),id3Track:r,textTrack:tj()}}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let r=eT(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(;"\x00"!==ef(e.subarray(h,h+1));)i+=ef(e.subarray(h,h+1)),h+=1;for(i+=ef(e.subarray(h,h+1)),h+=1;"\x00"!==ef(e.subarray(h,h+1));)r+=ef(e.subarray(h,h+1)),h+=1;r+=ef(e.subarray(h,h+1)),h+=1,s=em(e,12),a=em(e,16),l=em(e,20),o=em(e,24),h=28}else if(1===t){h+=4,s=em(e,h),h+=4;let t=em(e,h);h+=4;let a=em(e,h);for(h+=4,Number.isSafeInteger(n=4294967296*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=em(e,h),h+=4,o=em(e,h),h+=4;"\x00"!==ef(e.subarray(h,h+1));)i+=ef(e.subarray(h,h+1)),h+=1;for(i+=ef(e.subarray(h,h+1)),h+=1;"\x00"!==ef(e.subarray(h,h+1));)r+=ef(e.subarray(h,h+1)),h+=1;r+=ef(e.subarray(h,h+1)),h+=1}let d=e.subarray(h,e.byteLength);return{schemeIdUri:i,value:r,timeScale:s,presentationTime:n,presentationTimeDelta:a,eventDuration:l,id:o,payload:d}}(e);if(t4.test(r.schemeIdUri)){let e=S(r.presentationTime)?r.presentationTime/r.timeScale:t+r.presentationTimeDelta/r.timeScale,s=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;s<=.001&&(s=Number.POSITIVE_INFINITY);let a=r.payload;i.samples.push({data:a,len:a.byteLength,dts:e,pts:e,type:e2.emsg,duration:s})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(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;if(i&&t.isCommonEncryption){let t=eT(e,["moov","trak"]);t.forEach(e=>{let t=eT(e,["mdia","minf","stbl","stsd"])[0],r=t.subarray(8),s=eT(r,["enca"]),a=s.length>0;a||(s=eT(r,["encv"])),s.forEach(e=>{let t=a?e.subarray(28):e.subarray(78),r=eT(t,["sinf"]);r.forEach(e=>{let t=ev(e);if(t){let e=t.subarray(8,24);e.some(e=>0!==e)||(k.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${ed.hexDump(e)} -> ${ed.hexDump(i)}`),t.set(i,8))}})})})}return 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=ey(e);t||(t=iR(r.audio,O.AUDIO)),i||(i=iR(r.video,O.VIDEO));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;let{initPTS:h,lastEndTime:d}=this,u={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};S(d)||(d=this.lastEndTime=s||0);let c=t.samples;if(!(null!=c&&c.length))return u;let f={initPTS:void 0,timescale:1},g=this.initData;if(null!=(n=g)&&n.length||(this.generateInitSegment(c),g=this.initData),!(null!=(l=g)&&l.length))return k.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);let m=function(e,t){let i=0,r=0,s=0,a=eT(e,["moof","traf"]);for(let e=0;e<a.length;e++){let n=a[e],l=eT(n,["tfhd"])[0],o=em(l,4),h=t[o];if(!h)continue;let d=h.default,u=em(l,0)|(null==d?void 0:d.flags),c=null==d?void 0:d.duration;8&u&&(c=2&u?em(l,12):em(l,8));let f=h.timescale||9e4,g=eT(n,["trun"]);for(let e=0;e<g.length;e++){if(!(i=function(e){let t=em(e,0),i=8;1&t&&(i+=4),4&t&&(i+=4);let r=0,s=em(e,4);for(let a=0;a<s;a++){if(256&t){let t=em(e,i);r+=t,i+=4}512&t&&(i+=4),1024&t&&(i+=4),2048&t&&(i+=4)}return r}(g[e]))&&c){let t=em(g[e],4);i=c*t}h.type===O.VIDEO?r+=i/f:h.type===O.AUDIO&&(s+=i/f)}}if(0===r&&0===s){let t=0,i=eT(e,["sidx"]);for(let e=0;e<i.length;e++){let r=function(e){let t=[],i=e[0],r=8,s=em(e,r);r+=4,0===i?r+=8:r+=16,r+=2;let a=e.length+0,n=eg(e,r);r+=2;
1for(let i=0;i<n;i++){let i=r,n=em(e,i);i+=4;let l=2147483647&n,o=(2147483648&n)>>>31;if(1===o)return k.warn("SIDX has hierarchical references (not supported)"),null;let h=em(e,i);i+=4,t.push({referenceSize:l,subsegmentDuration:h,info:{duration:h/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}(c,g),p=(o=g,eT(c,["moof","traf"]).reduce((e,t)=>{let i=eT(t,["tfdt"])[0],r=i[0],s=eT(t,["tfhd"]).reduce((e,t)=>{let s=em(t,4),a=o[s];if(a){let t=em(i,4);if(1===r){if(4294967295===t)return k.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),e;t*=4294967296,t+=em(i,8)}let s=a.timescale||9e4,n=t/s;if(isFinite(n)&&(null===e||n<e))return n}return e},null);return null!==s&&isFinite(s)&&(null===e||s<e)?s:e},null)),E=null===p?s:p;((function(e,t,i,r){if(null===e)return!0;let s=t-e.baseTime/e.timescale;return Math.abs(s-i)>Math.max(r,1)})(h,E,s,m)||f.timescale!==h.timescale&&a)&&(f.initPTS=E-s,h&&1===h.timescale&&k.warn(`Adjusting initPTS by ${f.initPTS-h.baseTime}`),this.initPTS=h={baseTime:f.initPTS,timescale:1});let T=e?E-h.baseTime/h.timescale:d,y=T+m;!function(e,t,i){eT(t,["moof","traf"]).forEach(t=>{eT(t,["tfhd"]).forEach(r=>{let s=em(r,4),a=e[s];if(!a)return;let n=a.timescale||9e4;eT(t,["tfdt"]).forEach(e=>{let t=e[0],r=em(e,4);if(0===t)r-=i*n,r=Math.max(r,0),eE(e,4,r);else{r*=4294967296,r+=em(e,8),r-=i*n,r=Math.max(r,0);let t=Math.floor(r/4294967296),s=Math.floor(r%4294967296);eE(e,4,t),eE(e,8,s)}})})})}(g,c,h.baseTime/h.timescale),m>0?this.lastEndTime=y:(k.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let v=!!g.audio,A=!!g.video,L="";v&&(L+="audio"),A&&(L+="video");let R={data1:c,startPTS:T,startDTS:T,endPTS:y,endDTS:y,type:L,hasAudio:v,hasVideo:A,nb:1,dropped:0};return u.audio="audio"===R.type?R:void 0,u.video="audio"!==R.type?R:void 0,u.initSegment=f,u.id3=iv(i,s,h,h),r.samples.length&&(u.text=iS(r,s,h)),u}}},{demux:ia,remux:iT},{demux:class extends tX{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=Q(e,0)||[],i=t.length;for(let t=e.length;i<t;i++)if(function(e,t){if(t0(e,t)){let i=tJ(e,t);if(t+i>=e.length)return!1;let r=tZ(e,t);if(r<=i)return!1;let s=t+r;return s===e.length||t0(e,s)}return!1}(e,i))return k.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return t+5<e.length&&tQ(e,t)&&tZ(e,t)<=e.length-t}appendFrame(e,t,i){t1(e,this.observer,t,i,e.manifestCodec);let r=t2(e,t,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:iT},{demux:class extends tX{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=Q(e,0)||[],i=t.length;for(let t=e.length;i<t;i++)if(function(e,t){if(t+1<e.length&&it(e,t)){let i=ie(e,t),r=4;null!=i&&i.frameLength&&(r=i.frameLength);let s=t+r;return s===e.length||ii(e,s)}return!1}(e,i))return k.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return it(e,t)&&4<=e.length-t}appendFrame(e,t,i){if(null!==this.basePTS)return t7(e,t,i,this.basePTS,this.frameIndex)}},remux:iT}];class iD{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){let s;let n=i.transmuxing;n.executeStart=a();let l=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:h}=this;r&&(this.currentTransmuxState=r);
1let{contiguous:d,discontinuity:u,trackSwitch:c,accurateTimeOffset:f,timeOffset:g,initSegmentChange:m}=r||o,{audioCodec:p,videoCodec:E,defaultInitPts:T,duration:y,initSegmentData:v}=h,S=(s=null,l.byteLength>0&&null!=t&&null!=t.key&&null!==t.iv&&null!=t.method&&(s=t),s);if(S&&"AES-128"===S.method){let e=this.getDecrypter();if(!e.isSync())return this.decryptionPromise=e.webCryptoDecrypt(l,S.key.buffer,S.iv.buffer).then(e=>{let t=this.push(e,null,i);return this.decryptionPromise=null,t}),this.decryptionPromise;{let t=e.softwareDecrypt(l,S.key.buffer,S.iv.buffer),r=i.part>-1;if(r&&(t=e.flush()),!t)return n.executeEnd=a(),ib(i);l=new Uint8Array(t)}}let I=this.needsProbing(u,c);if(I){let e=this.configureTransmuxer(l);if(e)return k.warn(`[transmuxer] ${e.message}`),this.observer.emit(A.ERROR,A.ERROR,{type:L.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),n.executeEnd=a(),ib(i)}(u||c||m||I)&&this.resetInitSegment(v,p,E,y,t),(u||m||I)&&this.resetInitialTimestamp(T),d||this.resetContiguity();let D=this.transmux(l,S,g,f,i),b=this.currentTransmuxState;return b.contiguous=!0,b.discontinuity=!1,b.trackSwitch=!1,n.executeEnd=a(),D}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(),[ib(e)];let d=o.flush(l);return ik(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),o=this.remuxer.remux(s,a,n,l,t,i,!1,this.id);return{remuxResult:o,chunkMeta:r}}transmuxSampleAes(e,t,i,r,s){return this.demuxer.demuxSampleAes(e,t,i).then(e=>{let t=this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,this.id);return{remuxResult:t,chunkMeta:s}})}configureTransmuxer(e){let t;
1let{config:i,observer:r,typeSupported:s,vendor:a}=this;for(let i=0,r=iI.length;i<r;i++)if(iI[i].demux.probe(e)){t=iI[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 tH(this.config)),e}}let ib=e=>({remuxResult:{},chunkMeta:e});function ik(e){return"then"in e&&e.then instanceof Function}class i_{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 iC{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 iw={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}(iw);var iP=(m=iw.exports)&&m.__esModule&&Object.prototype.hasOwnProperty.call(m,"default")?m.default:m;let ix=ew()||{isTypeSupported:()=>!1};class iO{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;let s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;let a=(e,t)=>{(t=t||{}).frag=this.frag,t.id=this.id,e===A.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new iP,this.observer.on(A.FRAG_DECRYPTED,a),this.observer.on(A.ERROR,a);let n={mp4:ix.isTypeSupported("video/mp4"),mpeg:ix.isTypeSupported("audio/mpeg"),mp3:ix.isTypeSupported('audio/mp4; codecs="mp3"')},l=navigator.vendor;if(this.useWorker&&"undefined"!=typeof Worker){let e=s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__;if(e){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,i=new self.Worker(t);return{worker:i,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),i=new self.Worker(t);return{worker:i,objectURL:t}}()),this.onwmsg=e=>this.onWorkerMessage(e);let{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(A.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 iD(this.observer,n,s,l,t)}return}}this.transmuxer=new iD(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),E=!(m&&o.level===m.level),T=m?o.sn-m.sn:-1,y=this.part?o.part-this.part.index:-1,v=0===T&&o.id>1&&o.id===(null==m?void 0:m.stats.chunkCount),S=!E&&(1===T||0===T&&(1===y||v&&y<=0)),A=self.performance.now();(E||T||0===s.stats.parsing.start)&&(s.stats.parsing.start=A),a&&(y||!S)&&(a.stats.parsing.start=A);let L=!(m&&(null==(d=s.initSegment)?void 0:d.url)===(null==(u=m.initSegment)?void 0:u.url)),R=new iC(p,S,l,E,f,L);if(!S||p||L){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: ${E}
4        contiguous: ${S}
5        accurateTimeOffset: ${l}
6        timeOffset: ${f}
7        initSegmentChange: ${L}`);let e=new i_(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:R},e instanceof ArrayBuffer?[e]:[]);else if(c){let t=c.push(e,g,o,R);ik(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),r=ik(i);r||t.async?(ik(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(A.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 iF{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||!tx.getBuffered(r).length)return;let h=tx.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?void 0:null==(c=t.details)?void 0:c.live,r=i?2*t.details.targetduration:2,s=this.fragmentTracker.getPartialFragment(a);if(e>0&&(e<=r||s)){this._trySkipBufferHole(s);return}}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=tx.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);if(n){let e=this._trySkipBufferHole(n);if(e||!this.media)return}(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(A.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=tx.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,ej.MAIN);e&&n<e.end&&(i=!0)}if(!i){let i=e||t.getAppendedFrag(s,ej.MAIN);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(A.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(A.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(A.ERROR,{type:L.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:i,fatal:!0})}}}class iM extends tW{constructor(e,t,i){super(e,t,i,"[stream-controller]",ej.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){let{hls:e}=this;
7e.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(A.MANIFEST_LOADING,this.onManifestLoading,this),e.on(A.MANIFEST_PARSED,this.onManifestParsed,this),e.on(A.LEVEL_LOADING,this.onLevelLoading,this),e.on(A.LEVEL_LOADED,this.onLevelLoaded,this),e.on(A.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(A.ERROR,this.onError,this),e.on(A.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(A.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(A.BUFFER_CREATED,this.onBufferCreated,this),e.on(A.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(A.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(A.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(A.MANIFEST_LOADING,this.onManifestLoading,this),e.off(A.MANIFEST_PARSED,this.onManifestParsed,this),e.off(A.LEVEL_LOADED,this.onLevelLoaded,this),e.off(A.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(A.ERROR,this.onError,this),e.off(A.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(A.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(A.BUFFER_CREATED,this.onBufferCreated,this),e.off(A.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(A.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(A.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=tY.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=tY.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){var e,t;switch(this.state){case tY.WAITING_LEVEL:{let{levels:t,level:i}=this,r=null==t?void 0:null==(e=t[i])?void 0:e.details;if(r&&(!r.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(r))break;this.state=tY.IDLE}else this.hls.nextLoadLevel!==this.level&&(this.state=tY.IDLE);break}case tY.FRAG_LOADING_WAITING_RETRY:{let e=self.performance.now(),i=this.retryDate;(!i||e>=i||null!=(t=this.media)&&t.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=tY.IDLE)}}this.state===tY.IDLE&&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(A.BUFFER_EOS,e),this.state=tY.ENDED;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===tY.WAITING_LEVEL||h.live&&this.levelLastLoaded!==a){this.level=a,this.state=tY.WAITING_LEVEL;return}let d=l.len,u=this.getMaxBufferLength(n.maxBitrate);if(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&&this.fragmentTracker.getState(f)!==tA.OK){var g;let e=(null!=(g=this.backtrackFragment)?g:f).sn,t=e-h.startSN,i=h.fragments[t-1];i&&f.cc===i.cc&&(f=i,this.fragmentTracker.removeFragment(i))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){let e=f.gap;if(!e){let e=this.audioOnly&&!this.altAudio?O.AUDIO:O.VIDEO,t=(e===O.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,ej.MAIN)}f=this.getNextFragmentLoopLoading(f,h,l,ej.MAIN,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===tA.NOT_LOADED||r===tA.PARTIAL?"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,ej.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){let{levels:e,media:t}=this;if(null!=t&&t.readyState){let i;let 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=this.hls.nextLoadLevel,r=e[t],s=this.fragLastKbps;i=s&&this.fragCurrent?this.fragCurrent.duration*r.maxBitrate/(1e3*s)+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,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case tY.KEY_LOADING:case tY.FRAG_LOADING:case tY.FRAG_LOADING_WAITING_RETRY:case tY.PARSING:case tY.PARSED:this.state=tY.IDLE}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 iF(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;S(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);let i=this.getMainFwdBufferInfo();
7if(null===i||0===i.len){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(A.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1}onManifestParsed(e,t){let i,r=!1,s=!1;t.levels.forEach(e=>{(i=e.audioCodec)&&(-1!==i.indexOf("mp4a.40.2")&&(r=!0),-1!==i.indexOf("mp4a.40.5")&&(s=!0))}),this.audioCodecSwitch=r&&s&&!function(){var e;let t=tq();return"function"==typeof(null==t?void 0:null==(e=t.prototype)?void 0:e.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==tY.IDLE)return;let r=i[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(r.details))&&(this.state=tY.WAITING_LEVEL)}onLevelLoaded(e,t){var i;let{levels:r}=this,s=t.level,a=t.details,n=a.totalduration;if(!r){this.warn(`Levels were reset while loading level ${s}`);return}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===tY.FRAG_LOADING||this.state===tY.FRAG_LOADING_WAITING_RETRY)&&(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(A.LEVEL_UPDATED,{details:a,level:s}),this.state===tY.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=tY.IDLE}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){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let n=a[i.level],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 iO(this.hls,ej.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=r?r.index:-1,g=new tO(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,r=!!t.url;if(!r){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(A.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(A.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;let s=t.tracks,a=!1;for(let e in s){let t=s[e];if("main"===t.id){if(r=e,i=t,"video"===e){let t=s[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i&&i.type!==ej.MAIN)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===tY.PARSED&&(this.state=tY.IDLE);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=tY.ERROR;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(ej.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==tY.WAITING_LEVEL||(null==(i=t.context)?void 0:i.type)!==eq.LEVEL||(this.state=tY.IDLE);break;case R.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}
7checkBuffer(){let{media:e,gapController:t}=this;if(e&&t&&e.readyState){if(this.loadedmetadata||!tx.getBuffered(e).length){let e=this.state!==tY.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=tY.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==O.AUDIO||this.audioOnly&&!this.altAudio){let e=(t===O.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,ej.MAIN)}}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){this.log(`could not seek to ${i}, already seeking at ${t}`);return}let r=tx.getBuffered(e),s=r.length?r.start(0):0,a=s-i;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),i+=a,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=tY.IDLE,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(A.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){this.resetWhenMissingContext(a);return}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)){this.fragmentTracker.removeFragment(l);return}if(this.state=tY.PARSING,f){if(null!=f&&f.tracks){let e=l.initSegment||l;this._bufferInitSegment(h,f.tracks,e,a),r.trigger(A.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:f.tracks})}let e=f.initPTS,t=f.timescale;S(e)&&(this.initPTS[l.cc]={baseTime:e,timescale:t},r.trigger(A.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)i&&(l.gap=!0);else{this.backtrack(l);return}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)l.gap=!0;else{this.backtrack(l);return}}if(m){let{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=m;o&&(o.elementaryStreams[O.AUDIO]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),l.setElementaryStreamInfo(O.AUDIO,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(A.FRAG_PARSING_METADATA,e)}if(g&&u){let e={id:i,frag:l,details:g,samples:u.samples};r.trigger(A.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,i,r){if(this.state!==tY.PARSING)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(A.BUFFER_CODECS,t),Object.keys(t).forEach(e
7=>{let s=t[e],a=s.initSegment;null!=a&&a.byteLength&&this.hls.trigger(A.BUFFER_APPENDING,{type:e,data:a,frag:i,part:null,chunkMeta:r,parent:i.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,ej.MAIN)}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=tY.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){let i=e.currentTime;if(tx.isBuffered(e,i)?t=this.getAppendedFrag(i):tx.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(A.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(A.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&&S(t)&&S(i.programDateTime)){let e=i.programDateTime+(t-i.start)*1e3;return new Date(e)}}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 iN{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 iU{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 iN(e),this.fast_=new iN(t),this.defaultTTFB_=r,this.ttfb_=new iN(e)}update(e,t){let{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==e&&(this.slow_=new iN(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new iN(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new iN(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);let i=e/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){this.ttfb_.sample(Math.sqrt(2)*Math.exp(-Math.pow(e/1e3,2)/2),Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}class iB{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let e;let{chunks:t,dataLength:i}=this;return t.length?(e=1===t.length?t[0]:function(e,t){let i=new Uint8Array(t),r=0;for(let t=0;t<e.length;t++){let s=e[t];i.set(s,r),r+=s.length}return i}(t,i),this.reset(),e):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function i$(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 iG{constructor(e){this.buffered=void 0;let t=(t,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}function iK(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 iH{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){let i=this.queues[t];i.unshift(e),this.executeNext(t)}appendBlocker(e){let t;let 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 iV=ew(),iY=/([ha]vc.)(?:\.[^.,]+)+/,iW={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},iq=function(e){let t=e;return iW.hasOwnProperty(e)&&(t=iW[e]),String.fromCharCode(t)},ij={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},iX={17:2,18:4,21:6,22:8,23:10,19:13,20:15},iz={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},iQ={25:2,26:4,29:6,30:8,31:10,27:13,28:15},iJ=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class iZ{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 i0=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class i1{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 i2{constructor(e,t,i,r,s,a){this.uchar=void 0,this.penState=void 0,this.uchar=e||" ",this.penState=new i1(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 i4{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 i2);this.logger=e,this.pos=0,this.currPenState=new i1}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}
7setCursor(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=iq(e);if(this.pos>=100){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<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);let t=this.chars[this.pos];t.setPenState(this.currPenState)}}class i3{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 i4(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(){let e=this.rows[this.currRow];e.backSpace()}clearToEndOfRow(){let e=this.rows[this.currRow];e.clearToEndOfRow()}insertChar(e){let t=this.rows[this.currRow];t.insertChar(e)}setPen(e){let t=this.rows[this.currRow];t.setPenStyles(e)}moveCursor(e){let t=this.rows[this.currRow];t.moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e);let t=this.rows[this.currRow];t.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=e.indent;i.setCursor(e.indent),e.color=i.chars[Math.max(t-1,0)].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){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;let t=[],i="",r=-1;for(let i=0;i<15;i++){let s=this.rows[i].getTextString();s&&(r=i+1,e?t.push("Row "+r+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join("\n")),i}getTextAndFormat(){return this.rows}}class i5{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 i3(i),this.nonDisplayedMemory=new i3(i),this.lastOutputScreen=new i3(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})}
7ccRDC(){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 i8{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;let r=new iZ;this.channels=[null,new i5(e,t,r),new i5(e+1,i,r)],this.cmdHistory=i7(),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;let 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,"["+i0([t[e],t[e+1]])+"] -> ("+i0([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;if(e&&e>0){let t=this.channels[e];t.insertChars(a)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}i||a||this.logger.log(2,"Couldn't parse cleaned data "+i0([r,s])+" orig: "+i0([t[e],t[e+1]]))}}parseCmd(e,t){let{cmdHistory:i}=this;if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;if(i9(e,t,i))return i6(null,null,i),this.logger.log(3,"Repeated command ("+i0([e,t])+") is dropped"),!0;let r=20===e||21===e||23===e?1:2,s=this.channels[r];return 20===e||21===e||28===e||29===e?32===t?s.ccRCL():33===t?s.ccBS():34===t?s.ccAOF():35===t?s.ccAON():36===t?s.ccDER():37===t?s.ccRU(2):38===t?s.ccRU(3):39===t?s.ccRU(4):40===t?s.ccFON():41===t?s.ccRDC():42===t?s.ccTR():43===t?s.ccRTD():44===t?s.ccEDM():45===t?s.ccCR():46===t?s.ccENM():47===t&&s.ccEOC():s.ccTO(t-32),i6(e,t,i),this.currentChannel=r,!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 ("+i0([e,t])+")"),!0)}return!1}parsePAC(e,t){let i;let r=this.cmdHistory;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;if(i9(e,t,r))return i6(null,null,r),!0;let s=e<=23?1:2;i=t>=64&&t<=95?1===s?ij[e]:iz[e]:1===s?iX[e]:iQ[e];let a=this.channels[s];return!!a&&(a.setPAC(this.interpretPAC(i,t)),i6(e,t,r),this.currentChannel=s,!0)}interpretPAC(e,t){let i;let r={color:null,italics:!1,indent:null,underline:!1,row:e};return i=t>95?t-96:t-64,r.underline=(1&i)==1,i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(e,t){let i;let r=null,s=null;if(e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,"Special char '"+iq(e)+"' in channel "+i),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);if(r){let i=i0(r);this.logger.log(3,"Char codes =  "+i.join(",")),i6(e,t,this.cmdHistory)}return r}
7parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;let i={};16===e||24===e?(i.background=iJ[Math.floor((t-32)/2)],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));let r=this.channels[e<=23?1:2];return r.setBkgData(i),i6(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=i7()}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e)}}}function i6(e,t,i){i.a=e,i.b=t}function i9(e,t,i){return i.a===e&&i.b===t}function i7(){return{a:null,b:null}}class re{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 rt=function(){if("undefined"!=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,...t){let i=1;for(;i<arguments.length;i++){let t=arguments[i];for(let i in t)e[i]=t[i]}return e}function s(s,a,n){let l=this,o={enumerable:!0};l.hasBeenReset=!1;let h="",d=!1,u=s,c=a,f=n,g=null,m="",p=!0,E="auto",T="start",y=50,v="middle",S=50,A="middle";Object.defineProperty(l,"id",r({},o,{get:function(){return h},set:function(e){h=""+e}})),Object.defineProperty(l,"pauseOnExit",r({},o,{get:function(){return d},set:function(e){d=!!e}})),Object.defineProperty(l,"startTime",r({},o,{get:function(){return u},set:function(e){if("number"!=typeof e)throw TypeError("Start time must be set to a number.");u=e,this.hasBeenReset=!0}})),Object.defineProperty(l,"endTime",r({},o,{get:function(){return c},set:function(e){if("number"!=typeof e)throw TypeError("End time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(l,"text",r({},o,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(l,"region",r({},o,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(l,"vertical",r({},o,{get:function(){return m},set:function(t){let r=i(e,t);if(!1===r)throw SyntaxError("An invalid or illegal string was specified.");m=r,this.hasBeenReset=!0}})),Object.defineProperty(l,"snapToLines",r({},o,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(l,"line",r({},o,{get:function(){return E},set:function(e){if("number"!=typeof e&&"auto"!==e)throw SyntaxError("An invalid number or illegal string was specified.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(l,"lineAlign",r({},o,{get:function(){return T},set:function(e){let r=i(t,e);if(!r)throw SyntaxError("An invalid or illegal string was specified.");T=r,this.hasBeenReset=!0}})),Object.defineProperty(l,"position",r({},o,{get:function(){return y},set:function(e){if(e<0||e>100)throw Error("Position must be between 0 and 100.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(l,"positionAlign",r({},o,{get:function(){return v},set:function(e){let r=i(t,e);if(!r)throw SyntaxError("An invalid or illegal string was specified.");v=r,this.hasBeenReset=!0}})),Object.defineProperty(l,"size",r({},o,{get:function(){return S},set:function(e){if(e<0||e>100)throw Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(l,"align",r({},o,{get:function(){return A},set:function(e){let r=i(t,e);if(!r)throw SyntaxError("An invalid or illegal string was specified.");A=r,this.hasBeenReset=!0}})),l.displayState=void 0}return s.prototype.getCueAsHTML=function(){let e=self.WebVTT;return e.convertCueToDOMTree(self,this.text)},s}();class ri{decode(e,t){if(!e)return"";if("string"!=typeof e)throw Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function rr(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 rs{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 ra(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)continue;let a=r[0],n=r[1];t(a,n)}}let rn=new rt(0,0,""),rl="middle"===rn.align?"middle":"center";function ro(e){return e.replace(/<br(?: \/)?>/gi,"\n")}class rh{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new ri,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=ro(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;e=i();let r=e.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,ra(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 rt(0,0,""),t.state="CUE",-1===e.indexOf("-->")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{!function(e,t,i){let r=e;function s(){let t=rr(e);if(null===t)throw Error("Malformed timestamp: "+r);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=s(),a(),"-->"!==e.slice(0,3))throw Error("Malformed time stamp (time stamps must be separated by '-->'): "+r);e=e.slice(3),a(),t.endTime=s(),a(),function(e,t){let r=new rs;ra(e,function(e,t){let s;switch(e){case"region":for(let s=i.length-1;s>=0;s--)if(i[s].id===t){r.set(e,i[s].region);break}break;case"vertical":r.alt(e,t,["rl","lr"]);break;case"line":s=t.split(","),r.integer(e,s[0]),r.percent(e,s[0])&&r.set("snapToLines",!1),r.alt(e,s[0],["auto"]),2===s.length&&r.alt("lineAlign",s[1],["start",rl,"end"]);break;case"position":s=t.split(","),r.percent(e,s[0]),2===s.length&&r.alt("positionAlign",s[1],["start",rl,"end","line-left","line-right","auto"]);break;case"size":r.percent(e,t);break;case"align":r.alt(e,t,["start",rl,"end","left","right"])}},/:/,/\s/),t.region=r.get("region",null),t.vertical=r.get("vertical","");let s=r.get("line","auto");"auto"===s&&-1===rn.line&&(s=-1),t.line=s,t.lineAlign=r.get("lineAlign","start"),t.snapToLines=r.get("snapToLines",!0),t.size=r.get("size",100),t.align=r.get("align",rl);let a=r.get("position","auto");"auto"===a&&50===rn.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}(e,t.cue,t.regionList)}catch(e){t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let i=-1!==e.indexOf("-->");if(!e||i&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}catch(e){"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){let e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}let rd=/\r\n|\n\r|\n|\r/g,ru=function(e,t,i=0){return e.slice(i,i+t.length)===t},rc=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(!S(t)||!S(i)||!S(r)||!S(s))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+(1e3*i+6e4*r+36e5*s)},rf=function(e){let t=5381,i=e.length;for(;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()};function rg(e,t,i){return rf(e.toString())+rf(t.toString())+rf(i)}
7let rm=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},rp="stpp.ttml.im1t",rE=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,rT=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ry={left:"start",center:"center",right:"end",start:"start",end:"end"};function rv(e,t,i,r){let s=eT(new Uint8Array(e),["mdat"]);if(0===s.length){r(Error("Could not parse IMSC1 mdat"));return}let a=s.map(e=>eh(e)),n=function(e,t,i=1,r=!1){return ig(e,1,1/i,r)}(t.baseTime,0,t.timescale);try{a.forEach(e=>i(function(e,t){let i=new DOMParser,r=i.parseFromString(e,"text/xml"),s=r.getElementsByTagName("tt")[0];if(!s)throw Error("Invalid ttml");let a={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(a).reduce((e,t)=>(e[t]=s.getAttribute(`ttp:${t}`)||a[t],e),{}),l="preserve"!==s.getAttribute("xml:space"),o=rA(rS(s,"styling","style")),h=rA(rS(s,"layout","region")),d=rS(s,"body","[begin]");return[].map.call(d,e=>{let i=function e(t,i){return[].slice.call(t.childNodes).reduce((t,r,s)=>{var a;return"br"===r.nodeName&&s?t+"\n":null!=(a=r.childNodes)&&a.length?e(r,i):i?t+r.textContent.trim().replace(/\s+/g," "):t+r.textContent},"")}(e,l);if(!i||!e.hasAttribute("begin"))return null;let r=rI(e.getAttribute("begin"),n),s=rI(e.getAttribute("dur"),n),a=rI(e.getAttribute("end"),n);if(null===r)throw rR(e);if(null===a){if(null===s)throw rR(e);a=r+s}let d=new rt(r-t,a-t,i);d.id=rg(d.startTime,d.endTime,d.text);let u=h[e.getAttribute("region")],c=o[e.getAttribute("style")],f=function(e,t,i){let r="http://www.w3.org/ns/ttml#styling",s=null,a=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return a&&i.hasOwnProperty(a)&&(s=i[a]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((i,a)=>{let n=rL(t,r,a)||rL(e,r,a)||rL(s,r,a);return n&&(i[a]=n),i},{})}(u,c,o),{textAlign:g}=f;if(g){let e=ry[g];e&&(d.lineAlign=e),d.align=g}
7return v(d,f),d}).filter(e=>null!==e)}(e,n)))}catch(e){r(e)}}function rS(e,t,i){let r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function rA(e){return e.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function rL(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function rR(e){return Error(`Could not parse ttml timestamp ${e}`)}function rI(e,t){if(!e)return null;let i=rr(e);return null===i&&(rE.test(e)?i=function(e,t){let i=rE.exec(e),r=(0|i[4])+(0|i[5])/t.subFrameRate;return(0|i[1])*3600+(0|i[2])*60+(0|i[3])+r/t.frameRate}(e,t):rT.test(e)&&(i=function(e,t){let i=rT.exec(e),r=Number(i[1]),s=i[2];switch(s){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),i}function rD(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class rb{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=Number.POSITIVE_INFINITY,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(A.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(A.MEDIA_ATTA
7CHING,this.onMediaAttaching,this),e.on(A.MANIFEST_PARSED,this.onManifestParsed,this),e.on(A.BUFFER_CODECS,this.onBufferCodecs,this),e.on(A.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(A.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(A.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(A.MANIFEST_PARSED,this.onManifestParsed,this),e.off(A.BUFFER_CODECS,this.onBufferCodecs,this),e.off(A.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){let i=this.hls;i.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,rb.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;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){let t=this.restrictedLevels;return!t.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.length-1;for(let a=0;a<e.length;a+=1){var s;let n=e[a];if((n.width>=t||n.height>=i)&&(!(s=e[a+1])||n.width!==s.width||n.height!==s.height)){r=a;break}}return r}}let rk="[eme]";class r_{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=r_.CDMCleanupPromise?[r_.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=k.debug.bind(k,rk),this.log=k.log.bind(k,rk),this.warn=k.warn.bind(k,rk),this.error=k.error.bind(k,rk),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}
7registerListeners(){this.hls.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(A.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(A.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(A.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(A.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(A.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(A.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===G.WIDEVINE&&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 rC?i(t):i(new rC({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===q&&"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){let s;switch(e){case G.FAIRPLAY:s=["cenc","sinf"];break;case G.WIDEVINE:case G.PLAYREADY:s=["cenc"];break;case G.CLEARKEY:s=["cenc","keyids"];break;default:throw Error(`Unknown key-system: ${e}`)}return function(e,t,i,r){let s={initDataTypes:e,persistentState:r.persistentState||"not-allowed",distinctiveIdentifier:r.distinctiveIdentifier||"not-allowed",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs="${e}"`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:i.map(e=>({contentType:`video/mp4; codecs="${e}"`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))};return[s]}(s,t,i,r)}(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: ${ed.hexDump(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 ed.hexDump(e.keyId)}updateKeySession(e,t){var i;let r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${ed.hexDump((null==(i=e.decryptdata)?void 0:i.keyId)||[])}
8      } (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=W(this.config),s=e.map(H).filter(e=>!!e&&-1!==r.indexOf(e));return this.getKeySystemSelectionPromise(s).then(({keySystem:e})=>{let r=Y(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 rC?this.hls.trigger(A.ERROR,e.data):this.hls.trigger(A.ERROR,{type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}
8getKeySystemForKeyPromise(e){let t=this.getKeyIdString(e),i=this.keyIdToKeySessionPromise[t];if(!i){let t=H(e.keyFormat),i=t?[t]:W(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=W(this.config)),0===e.length)throw new rC({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;let{initDataType:r,initData:s}=e;if(this.debug(`"${e.type}" event: init data type: "${r}"`),null===s)return;if("sinf"===r&&this.config.drmSystems[G.FAIRPLAY]){let e=ef(new Uint8Array(s));try{let r=B(JSON.parse(e).sinf),s=ev(new Uint8Array(r));if(!s)return;t=s.subarray(8,24),i=G.FAIRPLAY}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)return null;let s=i.getUint32(4);if(1886614376!==s||(t.version=i.getUint32(8)>>>24,t.version>1))return null;t.systemId=ed.hexDump(new Uint8Array(e,12,16));let a=i.getUint32(28);if(0===t.version){if(r-32<a)return null;t.data=new Uint8Array(e,32,a)}else if(1===t.version){t.kids=[];for(let i=0;i<a;i++)t.kids.push(new Uint8Array(e,32+16*i,16))}return t}(s);if(null===e)return;0===e.version&&e.systemId===V.WIDEVINE&&e.data&&(t=e.data.subarray(8,24)),i=function(e){if(e===V.WIDEVINE)return G.WIDEVINE}(e.systemId)}if(!i||!t)return;let a=ed.hexDump(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=ed.hexDump(h.keyId);if(a===d||-1!==h.uri.replace(/-/g,"").indexOf(a)){o=n[d],delete n[d],h.pssh=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 eD("ISO-23001-7",a,null!=(n=Y(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)?void 0: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 iP;e.mediaKeysSession.onmessage=t=>{let i=e.mediaKeysSession;if(!i){h.emit("error",Error("invalid state"));return}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===G.FAIRPLAY&&(this.updateKeySession(e,$("acknowledged")),this.removeSession(e)):this.warn(`unhandled media ke
8y message type "${r}"`)},e.mediaKeysSession.onkeystatuseschange=t=>{let i=e.mediaKeysSession;if(!i){h.emit("error",Error("invalid state"));return}this.onKeyStatusChange(e);let r=e.keyStatus;h.emit("keyStatus",r),"expired"===r&&(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 rC({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===i?t(new rC({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 rC({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: ${ed.hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${ed.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){let t=this.config,i=t.loader,r=new i(t),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching serverCertificate for "${e}"`),new Promise((i,a)=>{let n={responseType:"arraybuffer",url:s},l=t.certLoadPolicy.default,o={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(n,o,{onSuccess:(e,t,r,s)=>{i(e.data)},onError:(t,i,r,l)=>{a(new rC({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:y({url:n.url,data:void 0},t)},`"${e}" certificate request failed (${s}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,r)=>{a(new rC({type:L.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:n.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},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 rC({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 rC({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(()=>{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 rC({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={},eD.clearKeyUriToKeyIdMap();let i=t.length;r_.CDMCleanupPromise=Promise.all(t.map(e=>this.removeSession(e)).concat(null==e?void 0:e.setMediaKeys(null).cat
8ch(t=>{this.log(`Could not clear media keys: ${t}. media.src: ${null==e?void 0:e.src}`)}))).then(()=>{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}`)})}}}r_.CDMCleanupPromise=void 0;class rC extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=Error(t)),this.data=e,e.err=e.error}}var rw={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",
8KEY:"k",OTHER:"o"};class rP{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:rw.MANIFEST,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};(r===rw.VIDEO||r===rw.AUDIO||r==rw.MUXED)&&(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;let t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||rP.uuid(),this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.registerListeners())}registerListeners(){let e=this.hls;
8e.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(A.MEDIA_DETACHED,this.onMediaDetached,this),e.on(A.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(A.MEDIA_DETACHED,this.onMediaDetached,this),e.off(A.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={}){v(t,this.createData());let i=t.ot===rw.INIT||t.ot===rw.VIDEO||t.ot===rw.MUXED;if(this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering),this.useHeaders){let i=rP.toHeaders(t);if(!Object.keys(i).length)return;e.headers||(e.headers={}),v(e.headers,i)}else{let i=rP.toQuery(t);if(!i)return;e.url=rP.appendQueryToUri(e.url,i)}}getObjectType(e){let{type:t}=e;return"subtitle"===t?rw.TIMED_TEXT:"initSegment"===e.sn?rw.INIT:"audio"===t?rw.AUDIO:"main"===t?this.hls.audioTracks.length?rw.VIDEO:rw.MUXED:void 0}getTopBandwidth(e){let t,i=0,r=this.hls;if(e===rw.AUDIO)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=e===rw.AUDIO?this.audioBuffer:this.videoBuffer;if(!i||!t)return NaN;let r=tx.bufferInfo(i,t.currentTime,this.config.maxBufferHole);return 1e3*r.len}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=e=>encodeURIComponent(e),n={br:r,d:r,bl:s,dl:s,mtp:s,nor:a,rtp:s,tb:r},l=Object.keys(e||{}).sort();for(let r of l){let s,a=e[r];if(!i(a)||"v"===r&&1===a||"pr"==r&&1===a)continue;let l=n[r];l&&(a=l(a));let o=typeof a;s="ot"===r||"sf"===r||"st"===r?`${r}=${a}`:"boolean"===o?r:"number"===o?`${r}=${a}`:`${r}=${JSON.stringify(a)}`,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){let t=null!=a[i]?a[i]:1;s[t][i]=e[i]}for(let e=0;e<s.length;e++){let t=rP.serialize(s[e]);t&&(i[`CMCD-${r[e]}`]=t)}return i}static toQuery(e){return`CMCD=${encodeURIComponent(rP.serialize(e))}`}static appendQueryToUri(e,t){if(!t)return e;let i=e.includes("?")?"&":"?";return`${e}${i}${t}`}}function rx(e,t,i,r){e&&Object.keys(t).forEach(s=>{let a=e.filter(e=>e.groupId===s).map(e=>{let a=v({},e);return a.details=void 0,a.attrs=new w(a.attrs),a.url=a.attrs.URI=rO(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 rO(e,t,i,r){let s;let{HOST:a,PARAMS:n,[i]:l}=r;t&&(s=null==l?void 0:l[t])&&(e=s);let o=new self.URL(e);
8return a&&!s&&(o.host=a),n&&Object.keys(n).sort().forEach(e=>{e&&o.searchParams.set(e,n[e])}),o.href}let rF=/^age:\s*[\d.]+\s*$/im;class rM{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(()=>{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&&S(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,n="arraybuffer"===t.responseType?s.byteLength:s.length;if(i.loaded=i.total=n,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first),!this.callbacks)return;let l=this.callbacks.onProgress;if(l&&l(i,e,s,t),!this.callbacks)return;let o={url:t.responseURL,data:s,code:r};this.callbacks.onSuccess(o,i,e,t)}else{let a=s.loadPolicy.errorRetry,n=i.retry;tc(a,n,!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,i=this.stats.retry;if(tc(t,i,!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=td(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&&rF.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 rN=/(\d+)-(\d+)\/(\d+)/;class rU{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||rB,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){let r=this.stats;if(r.loading.start)throw Error("Loader can only be used once.");r.loading.start=self.performance.now();let s=function(e,t){let i={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(v({},e.headers))};return e.rangeEnd&&i.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),i}(e,this.controller.signal),a=i.onProgress,n="arraybuffer"===e.responseType,l=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=o&&S(o)?o:h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},t.timeout),self.fetch(this.request).then(s=>{this.response=this.loader=s;let l=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(r,e,this.response)},h-(l-r.loading.start)),!s.ok){let{status:e,statusText:t}=s;throw new r$(t||"fetch, bad network response",e,s)}return(r.loading.first=l,r.total=function(e){let t=e.get("Content-Range");if(t){let e=function(e){let t=rN.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(S(e))return e}let i=e.get("Content-Length");if(i)return parseInt(i)}(s.headers)||r.total,a&&S(t.highWaterMark))?this.loadProgressively(s,r,e,t.highWaterMark,a):n?s.arrayBuffer():"json"===e.responseType?s.json():s.text()}).then(s=>{let{response:n}=this;self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let o=s[l];o&&(r.loaded=r.total=o);let h={url:n.url,data:s,code:n.status};a&&!S(t.highWaterMark)&&a(r,e,s,n),i.onSuccess(h,r,e,n)}).catch(t=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;let s=t&&t.code||0,a=t?t.message:null;i.onError({code:s,text:a},e,t?t.details:null,r)}
8)}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 iB,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 rB(e,t){return new self.Request(e.url,t)}class r$ extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}let rG=/\s/,rK=y(y({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:rM,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class{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;let t=e.config;this.bwEstimator=new iU(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(A.FRAG_LOADING,this.onFragLoading,this),e.on(A.FRAG_LOADED,this.onFragLoaded,this),e.on(A.FRAG_BUFFERED,this.onFragBuffered,this),e.on(A.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(A.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){let{hls:e}=this;e.off(A.FRAG_LOADING,this.onFragLoading,this),e.off(A.FRAG_LOADED,this.onFragLoaded,this),e.off(A.FRAG_BUFFERED,this.onFragBuffered,this),e.off(A.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(A.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){let s=r?this.lastLevelLoadSec:0;return e+i/t+s}onLevelLoaded(e,t){let i=this.hls.config,{total:r,bwEstimate:s}=t.stats;S(r)&&S(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;let{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,1e3*(o/(2*c))))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:E,minAutoLevel:T}=r,y=E[t.level],v=l.total||Math.max(l.loaded,Math.round(o*y.maxBitrate/8)),L=h-g;L<1&&m&&(L=Math.min(h,8*l.loaded/p));let R=m?1e3*l.loaded/L:0,I=R?(v-l.loaded)/R:8*v/p+u/1e3;if(I<=f)return;let D=R?8*R:p,b=Number.POSITIVE_INFINITY;for(e=t.level-1;e>T;e--){let t=E[e].maxBitrate;if((b=this.getTimeToLoadFrag(u/1e3,D,o*t,!E[e].details))<f)break}b>=I||b>
810*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;
9      Time to underbuffer: ${f.toFixed(3)} s
10      Estimated load time for current fragment: ${I.toFixed(3)} s
11      Estimated load time for down switch fragment: ${b.toFixed(3)} s
12      TTFB estimate: ${g}
13      Current BW estimate: ${S(p)?(p/1024).toFixed(3):"Unknown"} Kb/s
14      New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s
15      Aborting and switching to level ${e}`),t.loader&&(this.fragCurrent=this.partCurrent=null,t.abortRequests()),r.trigger(A.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:i,stats:l}))}onFragLoaded(e,{frag:t,part:i}){let r=i?i.stats:t.stats;if(t.type===ej.MAIN&&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(A.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!==ej.MAIN||"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;if(e){let t=l?Math.min(l,s.maxLoadingDelay):s.maxLoadingDelay;f=t-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,E=-1;for(let n=i;n>=t;n--){let t;let i=d[n];if(!i||f&&i.codecSet!==f){i&&(p=Math.min(n,p),E=Math.max(n,E));continue}-1!==E&&k.trace(`[abr] Skipped level(s) ${p}-${E} with CODECS:"${d[E].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 y=d[n].maxBitrate,v=this.getTimeToLoadFrag(m,t,y*T,void 0===l);if(k.trace(`[abr] level:${n} adjustedbw-bitrate:${Math.round(t-y)} avgDuration:${T.toFixed(1)} maxFetchDuration:${r.toFixed(1)} fetchDuration:${v.toFixed(1)}`),t>y&&(0===v||!S(v)||c&&!this.bitrateTestDelay||v<r))return n}return -1}set nextAutoLevel(e){this._nextAutoLevel=e}},bufferController:class{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(A.MEDIA_ATTA
15CHED,{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(A.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(A.MANIFEST_LOADING,this.onManifestLoading,this),e.on(A.MANIFEST_PARSED,this.onManifestParsed,this),e.on(A.BUFFER_RESET,this.onBufferReset,this),e.on(A.BUFFER_APPENDING,this.onBufferAppending,this),e.on(A.BUFFER_CODECS,this.onBufferCodecs,this),e.on(A.BUFFER_EOS,this.onBufferEos,this),e.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(A.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(A.FRAG_PARSED,this.onFragParsed,this),e.on(A.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){let{hls:e}=this;
15e.off(A.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(A.MANIFEST_LOADING,this.onManifestLoading,this),e.off(A.MANIFEST_PARSED,this.onManifestParsed,this),e.off(A.BUFFER_RESET,this.onBufferReset,this),e.off(A.BUFFER_APPENDING,this.onBufferAppending,this),e.off(A.BUFFER_CODECS,this.onBufferCodecs,this),e.off(A.BUFFER_EOS,this.onBufferEos,this),e.off(A.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(A.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(A.FRAG_PARSED,this.onFragParsed,this),e.off(A.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new iH(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&&iV){let e=this.mediaSource=new iV;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(A.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(iY,"$1"),h=(a||s).replace(iY,"$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}
15)`),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]=tx.getBuffered(t[e]);this.appendError=0,this.hls.trigger(A.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(A.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(A.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[O.AUDIOVIDEO]?s.push("audiovideo"):(a[O.AUDIO]&&s.push("audio"),a[O.VIDEO]&&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(A.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){let i=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);i&&(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(!S(a)||a<0)return;let n=i.currentTime,l=t.levelTargetDuration,o=Math.floor(n/l)*l-Math.max(a,l);s.forEach(i=>{let s=r[i];if(s){let r=tx.getBuffered(s);if(r.length>0&&o>r.start(0)){if(e.trigger(A.BACK_BUFFER_REACHED,{bufferEnd:o}),t.live)e.trigger(A.LIVE_BACK_BUFFER_REACHED,{bufferEnd:o});else if(s.ended&&r.end(r.length-1)-n<2*l){k.info(`[buffer-controller]: Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}e.trigger(A.BUFFER_FLUSHING,{startOffset:0,endOffset:o,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=S(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||!S(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,r=i.length;if(r&&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(A.BUFFER_CREATED,{tracks:this.tracks}
15),e.forEach(e=>{t.executeNext(e)});else{let e=Error("could not create source buffer for media codec(s)");this.hls.trigger(A.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),l=r;this.addBufferListener(l,"updatestart",this._onSBUpdateStart),this.addBufferListener(l,"updateend",this._onSBUpdateEnd),this.addBufferListener(l,"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(A.ERROR,{type:L.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:n})}}}_onSBUpdateStart(e){let{operationQueue:t}=this,i=t.current(e);i.onStart()}_onSBUpdateEnd(e){let{operationQueue:t}=this,i=t.current(e);i.onComplete(),t.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){let i=Error(`${e} SourceBuffer error`);k.error(`[buffer-controller]: ${i}`,t),this.hls.trigger(A.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=S(r.duration)?r.duration:1/0,h=S(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,r=t.map(e=>i.appendBlocker(e));Promise.all(r).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)})}},capLevelController:rb,errorController:class{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(A.ERROR,this.onError,this),e.on(A.MANIFEST_LOADING,this.onManifestLoading,this),e.on(A.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(A.ERROR,this.onError,this),e.off(A.ERROR,this.onErrorOut,this),e.off(A.MANIFEST_LOADING,this.onManifestLoading,this),e.off(A.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)===ej.MAIN?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:tp.DoNothing,flags:tE.None};return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=tp.SendAlternateToPenaltyBox;return;case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{let e=t.parent===ej.MAIN?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===eq.AUDIO_TRACK&&l.groupId===e.audioGroupId||l.type===eq.SUBTITLE_TRACK&&l.groupId===e.textGroupId)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=tp.SendAlternateToPenaltyBox,t.errorAction.flags=tE.MoveAllAlternatesMatchingHost)}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:tp.SendAlternateToPenaltyBox,flags:tE.MoveAllAlternatesMatchingHDCP,hdcpLevel:i})}return;
15case 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:tp.DoNothing,flags:tE.None};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=this.hls,s=th(r.config.playlistLoadPolicy,e),a=this.playlistError++,n=null==(i=e.response)?void 0:i.code,l=tc(s,a,to(e),n);if(l)return{action:tp.RetryRequest,flags:tE.None,retryConfig:s,retryCount:a};let o=this.getLevelSwitchAction(e,t);return s&&(o.retryConfig=s,o.retryCount=a),o}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:a}=t.config,n=th(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,i=tc(n,l,to(e),t);if(i)return{action:tp.RetryRequest,flags:tE.None,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=tg(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else if(u===eq.AUDIO_TRACK&&c===i.audioGroupId||u===eq.SUBTITLE_TRACK&&c===i.textGroupId)continue;else if(d===ej.AUDIO&&r.audioGroupId===i.audioGroupId||d===ej.SUBTITLE&&r.textGroupId===i.textGroupId)continue;t=s;break}}if(t>-1&&i.loadLevel!==t)return e.levelRetry=!0,this.playlistError=0,{action:tp.SendAlternateToPenaltyBox,flags:tE.None,nextAutoLevel:t}}return{action:tp.SendAlternateToPenaltyBox,flags:tE.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case tp.DoNothing:break;case tp.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===R.FRAG_GAP||(t.fatal=!0)}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let{flags:r,hdcpLevel:s,nextAutoLevel:a}=i;switch(r){case tE.None:this.switchLevel(e,a);break;case tE.MoveAllAlternatesMatchingHost:i.resolved||(i.resolved=this.redundantFailover(e));break;case tE.MoveAllAlternatesMatchingHDCP:s&&(t.maxHdcpLevel=e9[e9.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===ej.MAIN?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=tg(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}`),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}},fpsController:class{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}
15registerListeners(){this.hls.on(A.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(A.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(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=this.hls;if(n.trigger(A.FPS_DROP,{currentDropped:s,currentDecoded:a,totalDroppedFrames:i}),1e3*s/e>0&&s>n.config.fpsDroppedMonitoringThreshold*a){let e=n.currentLevel;k.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===n.autoLevelCapping||n.autoLevelCapping>=e)&&(e-=1,n.trigger(A.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:n.currentLevel}),n.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)}}},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:q,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:{newCue(e,t,i,r){let s,a,n,l,o;let 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++)rG.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=ro(o.trim()),f=rg(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)=>
15"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),h.forEach(t=>eZ(e,t))),h}},enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends tW{constructor(e,t,i){super(e,t,i,"[subtitle-stream-controller]",ej.SUBTITLE),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(A.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(A.MANIFEST_LOADING,this.onManifestLoading,this),e.on(A.LEVEL_LOADED,this.onLevelLoaded,this),e.on(A.ERROR,this.onError,this),e.on(A.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(A.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(A.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(A.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(A.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;
15e.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(A.MANIFEST_LOADING,this.onManifestLoading,this),e.off(A.LEVEL_LOADED,this.onLevelLoaded,this),e.off(A.ERROR,this.onError,this),e.off(A.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(A.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(A.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(A.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(A.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(A.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=tY.IDLE,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;let{frag:r,success:s}=t;if(this.fragPrevious=r,this.state=tY.IDLE,!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!==Number.POSITIVE_INFINITY){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,ej.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===ej.MAIN){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)===ej.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==tY.STOPPED&&(this.state=tY.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(i$(this.levels,t)){this.levels=t.map(e=>new tt(e));return}this.tracksBuffered=[],this.levels=t.map(e=>{let t=new tt(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,ej.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){if(this.currentTrackId=t.id,!this.levels.length||-1===this.currentTrackId){this.clearInterval();return}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&&ta(r,o=t.start):r.hasProgramDateTime&&e.hasProgramDateTime?(tB(r,e),o=r.fragments[0].start):t&&ta(r,o=t.start)}if(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===tY.IDLE){let e=tg(null,r.fragments,this.media.currentTime,0);e||(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(A.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(A.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:r}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=tY.IDLE})}}doTick(){if(!this.media){this.state=tY.IDLE;return}if(this.state===tY.IDLE){let{currentTrackId:e,levels:t}=this,i=t[e];if(!t.length||!i||!i.details)return;let{config:r}=this,s=this.getLoadPosition(),a=tx.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),{end:n,len:l}=a,o=this.getFwdBufferInfo(this.media,ej.MAIN),h=i.details,d=this.getMaxBufferLength(null==o?void 0:o.len)+h.levelTargetDuration;if(l>d)return;let u=h.fragments,c=u.length,f=h.edge,g=null,m=this.fragPrevious;if(n<f){let e=r.maxFragLookUpTolerance;(g=tg(m,u,Math.max(u[0].start,n),n>f-e?0:e))||!m||!(m.start<u[0].start)||(g=u[0])}else g=u[c-1];if(!g)return;if("initSegment"!==(g=this.mapToInitFragWhenRequired(g)).sn){let e=g.sn-h.startSN,t=u[e-1];t&&t.cc===g.cc&&this.fragmentTracker.getState(t)===tA.NOT_LOADED&&(g=t)}this.fragmentTracker.getState(g)===tA.NOT_LOADED&&this.loadFragment(g,i,n)}}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 iG(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends tT{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;
15e.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(A.MANIFEST_LOADING,this.onManifestLoading,this),e.on(A.MANIFEST_PARSED,this.onManifestParsed,this),e.on(A.LEVEL_LOADING,this.onLevelLoading,this),e.on(A.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(A.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(A.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(A.MANIFEST_LOADING,this.onManifestLoading,this),e.off(A.MANIFEST_PARSED,this.onManifestParsed,this),e.off(A.LEVEL_LOADING,this.onLevelLoading,this),e.off(A.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(A.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(A.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(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId);let e=iK(this.media.textTracks);e.forEach(e=>{e0(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){this.warn(`Invalid subtitle track id ${i}`);return}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(A.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===eq.SUBTITLE_TRACK&&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(A.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=iK(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(A.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(A.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1,t=iK(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)}},timelineController:class{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=rD(),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){let e=new re(this,"textTrack1"),t=new re(this,"textTrack2"),i=new re(this,"textTrack3"),r=new re(this,"textTrack4");this.cea608Parser1=new i8(1,e,t),this.cea608Parser2=new i8(3,i,r)}
15e.on(A.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(A.MANIFEST_LOADING,this.onManifestLoading,this),e.on(A.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(A.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(A.FRAG_LOADING,this.onFragLoading,this),e.on(A.FRAG_LOADED,this.onFragLoaded,this),e.on(A.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(A.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(A.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(A.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(A.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(A.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(A.MANIFEST_LOADING,this.onManifestLoading,this),e.off(A.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(A.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(A.FRAG_LOADING,this.onFragLoading,this),e.off(A.FRAG_LOADED,this.onFragLoaded,this),e.off(A.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(A.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(A.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(A.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(A.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;let r=s[e],l=(n=r[0],Math.min(r[1],i)-Math.max(n,t));if(l>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],i),a=!0,l/(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(A.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(A.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,e0(i[e]),eJ(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=t.label,r={_id:e,label:i,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(A.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}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=>{e0(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=rD(),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++)e0(t[e])}onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],r=i.some(e=>e.textCodec===rp);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){let e=i$(this.tracks,i);if(e){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;if((s=e[r])&&s.label===t.name&&!(s.textTrack1||s.textTrack2)){i=e[r];break}}i&&(r=i)}if(r)e0(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=>
15({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(A.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===ej.MAIN){var n,l;let e=t.frag.sn,o=null!=(n=null==t?void 0: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===ej.SUBTITLE){if(r.byteLength){let e=i.decryptdata;if(null==e||!e.encrypted||"stats"in t){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===rp?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:Error("Empty subtitle payload")})}}_parseIMSC1(e,t){let i=this.hls;rv(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),i.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{k.log(`Failed to parse IMSC1: ${t}`),i.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;let{frag:i,payload:r}=e,{initPTS:s,unparsedVttFrags:a}=this,n=s.length-1;if(!s[i.cc]&&-1===n){a.push(e);return}let l=this.hls,o=null!=(t=i.initSegment)&&t.data?eS(i.initSegment.data,new Uint8Array(r)):r;!function(e,t,i,r,s,a,n){let l;let o=new rh,h=eh(new Uint8Array(e)).trim().replace(rd,"\n").split("\n"),d=[],u=t?function(e,t=1){return ig(e,9e4,1/t)}(t.baseTime,t.timescale):0,c="00:00.000",f=0,g=0,m=!0;o.oncue=function(e){let a=i[r],n=i.ccOffset,o=(f-u)/9e4;if(null!=a&&a.new&&(void 0!==g?n=i.ccOffset=a.start:rm(i,r,o)),o){if(!t){l=Error("Missing initPTS for VTT MPEGTS");return}n=o-i.presentationOffset}let h=e.endTime-e.startTime,c=iy((e.startTime+n-g)*9e4,9e4*s)/9e4;e.startTime=Math.max(c,0),e.endTime=Math.max(c+h,0);let m=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(m)),e.id||(e.id=rg(e.startTime,e.endTime,m)),e.endTime>0&&d.push(e)},o.onparsingerror=function(e){l=e},o.onflush=function(){if(l){n(l);return}a(d)},h.forEach(e=>{if(m){if(ru(e,"X-TIMESTAMP-MAP=")){m=!1,e.slice(16).split(",").forEach(e=>{ru(e,"LOCAL:")?c=e.slice(6):ru(e,"MPEGTS:")&&(f=parseInt(e.slice(7)))});try{g=rc(c)/1e3}catch(e){l=e}return}""===e&&(m=!1)}o.parse(e+"\n")}),o.flush()}(o,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,e=>{this._appendCues(e,i.level),l.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},t=>{let s="Missing initPTS for VTT MPEGTS"===t.message;s?a.push(e):this._fallbackToIMSC1(i,r),k.log(`Failed to parse VTT cue: ${t}`),s&&n>i.cc||l.trigger(A.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:t})})}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||rv(t,this.initPTS[e.cc],()=>{i.textCodec=rp,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=>eZ(i,e))}else{let r=this.tracks[t];if(!r)return;let s=r.default?"default":"subtitles"+t;i.trigger(A.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===ej.SUBTITLE&&this.onFragLoaded(A.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!==ej.MAIN||"NONE"!==this.closedCaptionsForLevel(s))for(let e=0;e<a.length;e++){let t=a[e].bytes;if(t){let s=this.extractCea608Data(t);
15i.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=>e1(e[r],t,i))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){let{textTracks:e}=this;Object.keys(e).forEach(i=>e1(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)continue;let n=(4&i)!=0;if(n){let e=3&i;(0===e||1===e)&&(t[e].push(s),t[e].push(a))}}return t}},audioStreamController:class extends tW{constructor(e,t,i){super(e,t,i,"[audio-stream-controller]",ej.AUDIO),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;
15e.on(A.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(A.MANIFEST_LOADING,this.onManifestLoading,this),e.on(A.LEVEL_LOADED,this.onLevelLoaded,this),e.on(A.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(A.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(A.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(A.ERROR,this.onError,this),e.on(A.BUFFER_RESET,this.onBufferReset,this),e.on(A.BUFFER_CREATED,this.onBufferCreated,this),e.on(A.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(A.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(A.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(A.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(A.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(A.MANIFEST_LOADING,this.onManifestLoading,this),e.off(A.LEVEL_LOADED,this.onLevelLoaded,this),e.off(A.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(A.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(A.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(A.ERROR,this.onError,this),e.off(A.BUFFER_RESET,this.onBufferReset,this),e.off(A.BUFFER_CREATED,this.onBufferCreated,this),e.off(A.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(A.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(A.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===tY.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=tY.STOPPED;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=tY.IDLE):(this.loadedmetadata=!1,this.state=tY.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){var e,t;switch(this.state){case tY.IDLE:this.doTickIdle();break;case tY.WAITING_TRACK:{let{levels:t,trackId:i}=this,r=null==t?void 0:null==(e=t[i])?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=tY.WAITING_INIT_PTS}break}case tY.FRAG_LOADING_WAITING_RETRY:{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=tY.IDLE);break}case tY.WAITING_INIT_PTS:{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=tY.FRAG_LOADING;let e=r.flush(),a={frag:t,part:i,payload:e,networkDetails:null};this._handleFragmentLoadProgress(a),s&&super._handleFragmentLoadComplete(a)}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=tx.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole),r=tm(i.end,this.config.maxFragLookUpTolerance,t);r<0&&(this.log(`Waiting fragment cc (${t.cc}) @ ${t.start} cancelled because another fragment at ${i.end} is needed`),this.clearWaitingFragment())}}else this.state=tY.IDLE}}this.onTickEnd()}clearWaitingFragment(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=tY.IDLE)}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=tY.WAITING_TRACK;return}let l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,O.AUDIO,ej.AUDIO));let o=this.getFwdBufferInfo(l,ej.AUDIO);if(null===o)return;let{bufferedTrack:h,switchingTrack:d}=this;if(!d&&this._streamEnded(o,n)){e.trigger(A.BUFFER_EOS,{type:"audio"}),this.state=tY.ENDED;return}let u=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,ej.MAIN),c=o.len,f=this.getMaxBufferLength(null==u?void 0:u.len);if(c>=f&&!d)return;let g=n.fragments,m=g[0].start,p=o.end;if(d&&i){let e=this.getLoadPosition();h&&d.attrs!==h.attrs&&(p=e),n.PTSKnown&&e<m&&(o.end>m||o.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=m+.05)}let E=this.getNextFragment(p,n),T=!1;if(E&&this.isLoopLoading(E,p)&&(T=!!E.gap,E=this.getNextFragmentLoopLoading(E,n,o,ej.MAIN,f)),!E){this.bufferFlushed=!0;return}let y=u&&E.start>u.end+n.targetduration;if(y||!(null!=u&&u.len)&&o.len){let e=this.getAppendedFrag(E.start,ej.MAIN);if(null===e||(T||(T=!!e.gap||!!y&&0===u.len),y&&!T||T&&o.nextStart&&o.nextStart<e.end))return}this.loadFragment(E,a,p)}getMaxBufferLength(e){let t=super.getMaxBufferLength();
15return 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 tt(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=tY.IDLE):(this.switchingTrack=null,this.bufferedTrack=t,this.state=tY.STOPPED),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(A.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){this.warn(`Audio tracks were reset while loading level ${a}`);return}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?(tB(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!==tY.WAITING_TRACK||this.waitForCdnTuneIn(s)||(this.state=tY.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let{frag:i,part:r,payload:s}=e,{config:a,trackId:n,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}let o=l[n];if(!o){this.warn("Audio track is undefined on fragment load progress");return}let h=o.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let d=a.defaultAudioCodec||o.audioCodec||"mp4a.40.2",u=this.transmuxer;u||(u=this.transmuxer=new iO(this.hls,ej.AUDIO,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 tO(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 iB,complete:!1};e.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=tY.WAITING_INIT_PTS}}_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!==ej.AUDIO){if(!this.loadedmetadata&&i.type===ej.MAIN){let e=this.videoBuffer||this.media;if(e){let t=tx.getBuffered(e);t.length&&(this.loadedmetadata=!0)}}return}if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if("initSegment"!==i.sn){this.fragPrevious=i;let e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(A.AUDIO_TRACK_SWITCHED,y({},e)))}this.fragBufferedComplete(i,r)}onError(e,t){var i;if(t.fatal){this.state=tY.ERROR;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(ej.AUDIO,t);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==tY.WAITING_TRACK||(null==(i=t.context)?void 0:i.type)!==eq.AUDIO_TRACK||(this.state=tY.IDLE);break;case R.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushed(e,{type:t}){t===O.AUDIO&&(this.bufferFlushed=!0,this.state===tY.ENDED&&(this.state=tY.IDLE))}_handleTransmuxComplete(e){var t;let i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:a}=e,n=this.getCurrentContext(a);if(!n){this.resetWhenMissingContext(a);return}let{frag:l,part:o,level:h}=n,{details:d}=h,{audio:u,text:c,id3:f,initSegment:g}=s;if(this.fragContextChanged(l)||!d){this.fragmentTracker.removeFragment(l);return}if(this.state=tY.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){let e=l.initSegment||l;this._bufferInitSegment(g.tracks,e,a),r.trigger(A.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[O.AUDIO]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),l.setElementaryStreamInfo(O.AUDIO,e,t,i,r),this.bufferFragmentData(u,l,o,a)}if(null!=f&&null!=(t=f.samples)&&t.length){let e=v({id:i,frag:l,details:d},f);r.trigger(A.FRAG_PARSING_METADATA,e)}if(c){let e=v({id:i,frag:l,details:d},c);r.trigger(A.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,i){if(this.state!==tY.PARSING)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(A.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(A.BUFFER_APPENDING,e)}this.tick()}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||r===tA.NOT_LOADED||r===tA.PARTIAL){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=tY.WAITING_INIT_PTS):(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;
15i&&s&&(s.CHANNELS!==a.CHANNELS||s.NAME!==a.NAME||s.LANGUAGE!==a.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(A.AUDIO_TRACK_SWITCHED,y({},e))}},audioTrackController:class extends tT{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(A.MANIFEST_LOADING,this.onManifestLoading,this),e.on(A.MANIFEST_PARSED,this.onManifestParsed,this),e.on(A.LEVEL_LOADING,this.onLevelLoading,this),e.on(A.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(A.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(A.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(A.MANIFEST_LOADING,this.onManifestLoading,this),e.off(A.MANIFEST_PARSED,this.onManifestParsed,this),e.off(A.LEVEL_LOADING,this.onLevelLoading,this),e.off(A.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(A.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(A.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:i,groupId:r,details:s}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r){this.warn(`Track with id:${i} and group:${r} not found in active group ${a.groupId}`);return}let n=a.details;a.details=t.details,this.log(`audio-track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,n)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!(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(A.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===eq.AUDIO_TRACK&&t.context.id===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){this.warn("Invalid id passed to audio-track controller");return}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(A.AUDIO_TRACK_SWITCHING,y({},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(A.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(A.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:e||null})}}},emeController:r_,cmcdController:rP,contentSteeringController:class{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(A.MANIFEST_LOADING,this.onManifestLoading,this),e.on(A.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(A.MANIFEST_PARSED,this.onManifestParsed,this),e.on(A.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(A.MANIFEST_LOADING,this.onManifestLoading,this),e.off(A.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(A.MANIFEST_PARSED,this.onManifestParsed,this),e.off(A.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)===tp.SendAlternateToPenaltyBox&&i.flags===tE.MoveAllAlternatesMatchingHost){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(A.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=v({},e);t.details=void 0,t.url=rO(e.uri,e.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",n);let a=new w(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 tt(t);return tv(h,"audio",l),tv(h,"text",o),h});t.push(...l),rx(this.audioTracks,i,n,s),rx(this.subtitleTracks,r,n,s)})}loadSteeringManifest(e){let t;let i=this.hls.config,r=i.loader;this.loader&&this.loader.destroy(),this.loader=new r(i);try{t=new self.URL(e)}catch(t){this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if("data:"!==t.protocol){let e=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);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){this.log(`Steering VERSION ${a.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=a.TTL;let{"RELOAD-URI":n,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":o}=a;if(n)try{this.uri=new self.URL(n,t).href}catch(e){this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${n}`);return}this.scheduleRefresh(this.uri||r.url),l&&this.clonePathways(l),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)}}});class rH{static get version(){return"1.4.12"}static isSupported(){return function(){let e=ew();if(!e)return!1;let t=tq(),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 A}static get ErrorTypes(){return L}static get ErrorDetails(){return R}static get DefaultConfig(){return rH.defaultConfig?rH.defaultConfig:rK}static set DefaultConfig(e){rH.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new iP,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){b[t]=e[t]?e[t].bind(e):function(e){let t=self.console[e];return t?t.bind(self.console,`[${e}] >`):I}(t)})}(e,"debug","log","info","warn","error");try{b.log(`Debug logs enabled for "${t}
15" in hls.js version 1.4.12`)}catch(e){b=D}}else b=D}(e.debug||!1,"Hls instance");let 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"];return["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])}`)}),y(y({},i),t)}(rH.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,t.progressive&&function(e){let t=e.loader;if(t!==rU&&t!==rM)k.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1;else{let t=function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}();t&&(e.loader=rU,e.progressive=!0,e.enableSoftwareAES=!0,k.log("[config]: Progressive streaming enabled, using FetchLoader"))}}(t);let{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 eQ(this),f=new e8(this),g=t.contentSteeringController,m=g?new g(this):null,p=this.levelController=new ty(this,m),E=new tL(this),T=new tC(this.config),v=this.streamController=new iM(this,E,T);d.setStreamController(v),u.setStreamController(v);let S=[c,p,v];m&&S.splice(1,0,m),this.networkControllers=S;let L=[o,h,d,u,f,E];this.audioTrackController=this.createController(t.audioTrackController,S);let R=t.audioStreamController;R&&S.push(new R(this,E,T)),this.subtitleTrackController=this.createController(t.subtitleTrackController,S);let _=t.subtitleStreamController;_&&S.push(new _(this,E,T)),this.createController(t.timelineController,L),T.emeController=this.emeController=this.createController(t.emeController,L),this.cmcdController=this.createController(t.cmcdController,L),this.latencyController=this.createController(e6,L),this.coreComponents=L,S.push(l);let C=l.onErrorOut;"function"==typeof C&&this.on(A.ERROR,C,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(A.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(A.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEac
15h(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(A.MEDIA_ATTACHING,{media:e})}detachMedia(){k.log("detachMedia"),this.trigger(A.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();let t=this.media,i=this.url,r=this.url=E.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(A.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(){let e=this.levelController.levels;return e||[]}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){e9.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;let{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}}rH.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.