PageSourceSearch

https://mutigers.com/_nuxt/DH4Q3RLg.js

js mutigers.com collected 2026-09-24 08:00:02 UTC 351,845 bytes, 26 lines download raw bytes

1(function(){try{var e=typeof window<`u`?window:typeof global<`u`?global:typeof globalThis<`u`?globalThis:typeof self<`u`?self:{};e._sentryModuleMetadata=e._sentryModuleMetadata||{},e._sentryModuleMetadata[new e.Error().stack]=function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];if(n!=null)for(var r in n)n.hasOwnProperty(r)&&(e[r]=n[r])}return e}({},e._sentryModuleMetadata[new e.Error().stack],{"_sentryBundlerPluginAppKey:astra-oas-frontend":!0});var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]=`af91ab75-518f-44fe-8839-30dc697184a2`,e._sentryDebugIdIdentifier=`sentry-dbid-af91ab75-518f-44fe-8839-30dc697184a2`)}catch{}})();function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var t={exports:{}};(function(e,t){(function(t){var n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(e,t,n){if(n||={},e=e.trim(),t=t.trim(),!t){if(!n.alwaysNormalize)return e;var i=o.parseURL(e);if(!i)throw Error(`Error trying to parse base URL.`);return i.path=o.normalizePath(i.path),o.buildURLFromParts(i)}var a=o.parseURL(t);if(!a)throw Error(`Error trying to parse relative URL.`);if(a.scheme)return n.alwaysNormalize?(a.path=o.normalizePath(a.path),o.buildURLFromParts(a)):t;var s=o.parseURL(e);if(!s)throw Error(`Error trying to parse base URL.`);if(!s.netLoc&&s.path&&s.path[0]!==`/`){var c=r.exec(s.path);s.netLoc=c[1],s.path=c[2]}s.netLoc&&!s.path&&(s.path=`/`);var l={scheme:s.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(l.netLoc=s.netLoc,a.path[0]!==`/`)){if(!a.path)l.path=s.path,a.params||(l.params=s.params,a.query||(l.query=s.query));else{var u=s.path,d=u.substring(0,u.lastIndexOf(`/`)+1)+a.path;l.path=o.normalizePath(d)}}return l.path===null&&(l.path=n.alwaysNormalize?o.normalizePath(a.path):a.path),o.buildURLFromParts(l)},parseURL:function(e){var t=n.exec(e);return t?{scheme:t[1]||``,netLoc:t[2]||``,path:t[3]||``,params:t[4]||``,query:t[5]||``,fragment:t[6]||``}:null},normalizePath:function(e){for(e=e.split(``).reverse().join(``).replace(i,``);e.length!==(e=e.replace(a,``)).length;);return e.split(``).reverse().join(``)},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=o})()})(t);var n=t.exports;function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?r(Object(n),!0).forEach(function(t){a(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function a(e,t,n){return t=c(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(){return o=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o.apply(this,arguments)}function s(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function c(e){var t=s(e,`string`);return typeof t==`symbol`?t:String(t)}var l=Number.isFinite||function(e){return typeof e==`number`&&isFinite(e)},u=function(e){return e.MEDIA_ATTACHING=`hlsMediaAttaching`,e.MEDIA_ATTACHED=`hlsMediaAttached`,e.MEDIA_DETACHING=`hlsMediaDetaching`,e.MEDIA_DETACHED=`hlsMediaDetached`,e.BUFFER_RESET=`hlsBufferReset`,e.BUFFER_CODECS=`hlsBufferCodecs`,e.BUFFER_CREATED=`hlsBufferCreated`,e.BUFFER_APPENDING=`hlsBufferAppending`,e.BUFFER_APPENDED=`hlsBufferAppended`,e.BUFFER_EOS=`hlsBufferEos`,e.BUFFER_FLUSHING=`hlsBufferFlushing`,e.BUFFER_FLUSHED=`hlsBufferFlushed`,e.MANIFEST_LOADING=`hlsManifestLoading`,e.MANIFEST_LOADED=`hlsManifestLoaded`,e.MANIFEST_PARSED=`hlsManifestParsed`,e.LEVEL_SWITCHING=`hlsLevelSwitching`,e.LEVEL_SWITCHED=`hlsLevelSwitched`,e.LEVEL_LOADING=`hlsLevelLoading`,e.LEVEL_LOADED=`hlsLevelLoaded`,e.LEVEL_UPDATED=`hlsLevelUpdated`,e.LEVEL_PTS_UPDATED=`hlsLevelPtsUpdated`,e.LEVELS_UPDATED=`hlsLevelsUpdated`,e.AUDIO_TRACKS_UPDATED=`hlsAudioTracksUpdated`,e.AUDIO_TRACK_SWITCHING=`hlsAudioTrackSwitching`,e.AUDIO_TRACK_SWITCHED=`hlsAudioTrackSwitched`,e.AUDIO_TRACK_LOADING=`hlsAudioTrackLoading`,e.AUDIO_TRACK_LOADED=`hlsAudioTrackLoaded`,e.SUBTITLE_TRACKS_UPDATED=`hlsSubtitleTracksUp
1dated`,e.SUBTITLE_TRACKS_CLEARED=`hlsSubtitleTracksCleared`,e.SUBTITLE_TRACK_SWITCH=`hlsSubtitleTrackSwitch`,e.SUBTITLE_TRACK_LOADING=`hlsSubtitleTrackLoading`,e.SUBTITLE_TRACK_LOADED=`hlsSubtitleTrackLoaded`,e.SUBTITLE_FRAG_PROCESSED=`hlsSubtitleFragProcessed`,e.CUES_PARSED=`hlsCuesParsed`,e.NON_NATIVE_TEXT_TRACKS_FOUND=`hlsNonNativeTextTracksFound`,e.INIT_PTS_FOUND=`hlsInitPtsFound`,e.FRAG_LOADING=`hlsFragLoading`,e.FRAG_LOAD_EMERGENCY_ABORTED=`hlsFragLoadEmergencyAborted`,e.FRAG_LOADED=`hlsFragLoaded`,e.FRAG_DECRYPTED=`hlsFragDecrypted`,e.FRAG_PARSING_INIT_SEGMENT=`hlsFragParsingInitSegment`,e.FRAG_PARSING_USERDATA=`hlsFragParsingUserdata`,e.FRAG_PARSING_METADATA=`hlsFragParsingMetadata`,e.FRAG_PARSED=`hlsFragParsed`,e.FRAG_BUFFERED=`hlsFragBuffered`,e.FRAG_CHANGED=`hlsFragChanged`,e.FPS_DROP=`hlsFpsDrop`,e.FPS_DROP_LEVEL_CAPPING=`hlsFpsDropLevelCapping`,e.ERROR=`hlsError`,e.DESTROYING=`hlsDestroying`,e.KEY_LOADING=`hlsKeyLoading`,e.KEY_LOADED=`hlsKeyLoaded`,e.LIVE_BACK_BUFFER_REACHED=`hlsLiveBackBufferReached`,e.BACK_BUFFER_REACHED=`hlsBackBufferReached`,e}({}),d=function(e){return e.NETWORK_ERROR=`networkError`,e.MEDIA_ERROR=`mediaError`,e.KEY_SYSTEM_ERROR=`keySystemError`,e.MUX_ERROR=`muxError`,e.OTHER_ERROR=`otherError`,e}({}),f=function(e){return e.KEY_SYSTEM_NO_KEYS=`keySystemNoKeys`,e.KEY_SYSTEM_NO_ACCESS=`keySystemNoAccess`,e.KEY_SYSTEM_NO_SESSION=`keySystemNoSession`,e.KEY_SYSTEM_NO_CONFIGURED_LICENSE=`keySystemNoConfiguredLicense`,e.KEY_SYSTEM_LICENSE_REQUEST_FAILED=`keySystemLicenseRequestFailed`,e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED=`keySystemServerCertificateRequestFailed`,e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED=`keySystemServerCertificateUpdateFailed`,e.KEY_SYSTEM_SESSION_UPDATE_FAILED=`keySystemSessionUpdateFailed`,e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED=`keySystemStatusOutputRestricted`,e.KEY_SYSTEM_STATUS_INTERNAL_ERROR=`keySystemStatusInternalError`,e.MANIFEST_LOAD_ERROR=`manifestLoadError`,e.MANIFEST_LOAD_TIMEOUT=`manifestLoadTimeOut`,e.MANIFEST_PARSING_ERROR=`manifestParsingError`,e.MANIFEST_INCOMPATIBLE_CODECS_ERROR=`manifestIncompatibleCodecsError`,e.LEVEL_EMPTY_ERROR=`levelEmptyError`,e.LEVEL_LOAD_ERROR=`levelLoadError`,e.LEVEL_LOAD_TIMEOUT=`levelLoadTimeOut`,e.LEVEL_PARSING_ERROR=`levelParsingError`,e.LEVEL_SWITCH_ERROR=`levelSwitchError`,e.AUDIO_TRACK_LOAD_ERROR=`audioTrackLoadError`,e.AUDIO_TRACK_LOAD_TIMEOUT=`audioTrackLoadTimeOut`,e.SUBTITLE_LOAD_ERROR=`subtitleTrackLoadError`,e.SUBTITLE_TRACK_LOAD_TIMEOUT=`subtitleTrackLoadTimeOut`,e.FRAG_LOAD_ERROR=`fragLoadError`,e.FRAG_LOAD_TIMEOUT=`fragLoadTimeOut`,e.FRAG_DECRYPT_ERROR=`fragDecryptError`,e.FRAG_PARSING_ERROR=`fragParsingError`,e.FRAG_GAP=`fragGap`,e.REMUX_ALLOC_ERROR=`remuxAllocError`,e.KEY_LOAD_ERROR=`keyLoadError`,e.KEY_LOAD_TIMEOUT=`keyLoadTimeOut`,e.BUFFER_ADD_CODEC_ERROR=`bufferAddCodecError`,e.BUFFER_INCOMPATIBLE_CODECS_ERROR=`bufferIncompatibleCodecsError`,e.BUFFER_APPEND_ERROR=`bufferAppendError`,e.BUFFER_APPENDING_ERROR=`bufferAppendingError`,e.BUFFER_STALLED_ERROR=`bufferStalledError`,e.BUFFER_FULL_ERROR=`bufferFullError`,e.BUFFER_SEEK_OVER_HOLE=`bufferSeekOverHole`,e.BUFFER_NUDGE_ON_STALL=`bufferNudgeOnStall`,e.INTERNAL_EXCEPTION=`internalException`,e.INTERNAL_ABORTED=`aborted`,e.UNKNOWN=`unknown`,e}({}),p=function(){},m={trace:p,debug:p,log:p,warn:p,info:p,error:p},h=m;function g(e){let t=self.console[e];return t?t.bind(self.console,`[${e}] >`):p}function _(e,...t){t.forEach(function(t){h[t]=e[t]?e[t].bind(e):g(t)})}function v(e,t){if(self.console&&e===!0||typeof e==`object`){_(e,`debug`,`log`,`info`,`warn`,`error`);try{h.log(`Debug logs enabled for "${t}" in hls.js version 1.4.10`)}catch{h=m}}else h=m}var y=h,b=/^(\d+)x(\d+)$/,x=/(.+?)=(".*?"|.*?)(?:,|$)/g,S=class e{constructor(t){typeof t==`string`&&(t=e.parseAttrList(t));for(let e in t)t.hasOwnProperty(e)&&(e.substring(0,2)===`X-`&&(this.clientAttrs=this.clientAttrs||[],this.clientAttrs.push(e)),this[e]=t[e])}decimalInteger(e){let t=parseInt(this[e],10);return t>2**53-1?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||`0x`).slice(2);t=(t.length&1?`0`:``)+t;let n=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>2**53-1?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let n=this[e];return n?parseFloat(n):t}enumeratedString(e){return this[e]}bool(e){return this[e]===`YES`}decimalResolution(e){let t=b.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t,n={};for(x.lastIndex=0;(t=x.exec(e))!==null;){let e=t[2];e.indexOf(`"`)===0&&e.lastIndexOf(`"`)===e.length-1&&(e=e.slice(1,-1));let r=t[1].trim();n[r]=e}return n}};function C(e){return e!==`ID`&&e!==`CLASS`&&e!==`START-DATE`&&e!==`DURATION`&&e!==`END-DATE`&&e!==`END-ON-NEXT`}function w(e){return e===`SCTE35-OUT`||e===`SCTE35-IN`}var T=class{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){let n=t.attr;for(let t in n)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==n[t]){y.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=o(new S({}),n,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`]);l(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 e===null?null:new Date(this._startDate.getTime()+e*1e3)}get duration(){if(`DURATION`in this.attr){let e=this.attr.decimalFloatingPoint(`DURATION`);if(l(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&&l(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}},E=class{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}}},D={AUDIO:`audio`,VIDEO:`video`,AUDIOVIDEO:`audiovideo`},O=class{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[D.AUDIO]:null,[D.VIDEO]:null,[D.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){let n=e.split(`@`,2),r=[];r[0]=n.length===1?t?t.byteRangeEndOffset:0:parseInt(n[1]),r[1]=parseInt(n[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=n.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||``}set url(e){this._url=e}},ee=class extends O{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new E,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(e.length===1)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!l(this.programDateTime))return null;let e=l(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;
1if(this.levelkeys){let e=Object.keys(this.levelkeys),t=e.length;if(t>1||t===1&&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;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,n,r,i,a=!1){let{elementaryStreams:o}=this,s=o[e];if(!s){o[e]={startPTS:t,endPTS:n,startDTS:r,endDTS:i,partial:a};return}s.startPTS=Math.min(s.startPTS,t),s.endPTS=Math.max(s.endPTS,n),s.startDTS=Math.min(s.startDTS,r),s.endDTS=Math.max(s.endDTS,i)}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[D.AUDIO]=null,e[D.VIDEO]=null,e[D.AUDIOVIDEO]=null}},k=class extends O{constructor(e,t,n,r,i){super(n),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 E,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,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}},te=10,A=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8=``,this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!t,this.advanced=this.endSN>e.endSN||t>0||t===0&&n>0,this.misses=this.updated||this.advanced?Math.floor(e.misses*.6):e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?l(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||te}
1get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&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(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}};function ne(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function re(e){let t=oe(e).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function ie(e){let t=function(e,t,n){let r=e[t];e[t]=e[n],e[n]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function ae(e){let t=e.split(`:`),n=null;if(t[0]===`data`&&t.length===2){let e=t[1].split(`;`),r=e[e.length-1].split(`,`);if(r.length===2){let t=r[0]===`base64`,i=r[1];t?(e.splice(-1,1),n=ne(i)):n=re(i)}}return n}function oe(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}var j={CLEARKEY:`org.w3.clearkey`,FAIRPLAY:`com.apple.fps`,PLAYREADY:`com.microsoft.playready`,WIDEVINE:`com.widevine.alpha`},M={CLEARKEY:`org.w3.clearkey`,FAIRPLAY:`com.apple.streamingkeydelivery`,PLAYREADY:`com.microsoft.playready`,WIDEVINE:`urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed`};function se(e){switch(e){case M.FAIRPLAY:return j.FAIRPLAY;case M.PLAYREADY:return j.PLAYREADY;case M.WIDEVINE:return j.WIDEVINE;case M.CLEARKEY:return j.CLEARKEY}}var ce={WIDEVINE:`edef8ba979d64acea3c827dcd51d21ed`};function le(e){if(e===ce.WIDEVINE)return j.WIDEVINE}function ue(e){switch(e){case j.FAIRPLAY:return M.FAIRPLAY;case j.PLAYREADY:return M.PLAYREADY;case j.WIDEVINE:return M.WIDEVINE;case j.CLEARKEY:return M.CLEARKEY}}function de(e){let{drmSystems:t,widevineLicenseUrl:n}=e,r=t?[j.FAIRPLAY,j.WIDEVINE,j.PLAYREADY,j.CLEARKEY].filter(e=>!!t[e]):[];return!r[j.WIDEVINE]&&n&&r.push(j.WIDEVINE),r}var fe=function(){return typeof self<`u`&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function pe(e,t,n,r){let i;switch(e){case j.FAIRPLAY:i=[`cenc`,`sinf`];break;case j.WIDEVINE:case j.PLAYREADY:i=[`cenc`];break;case j.CLEARKEY:i=[`cenc`,`keyids`];break;default:throw Error(`Unknown key-system: ${e}`)}return me(i,t,n,r)}function me(e,t,n,r){return[{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:n.map(e=>({contentType:`video/mp4; codecs="${e}"`,robustness:r.videoRobustness||``,encryptionScheme:r.videoEncryptionScheme||null}))}]}function he(e,t,n){return Uint8Array.prototype.slice?e.slice(t,n):new Uint8Array(Array.prototype.slice.call(e,t,n))}var ge=(e,t)=>t+10<=e.length&&e[t]===73&&e[t+1]===68&&e[t+2]===51&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,_e=(e,t)=>t+10<=e.length&&e[t]===51&&e[t+1]===68&&e[t+2]===73&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128,ve=(e,t)=>{let n=t,r=0;for(;ge(e,t);){r+=10;let n=ye(e,t+6);r+=n,_e(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(n,n+r)},ye=(e,t)=>{let n=0;return n=(e[t]&127)<<21,n|=(e[t+1]&127)<<14,n|=(e[t+2]&127)<<7,n|=e[t+3]&127,n},be=(e,t)=>ge(e,t)&&ye(e,t+6)+10<=e.length-t,xe=e=>{let t=we(e);for(let e=0;e<t.length;e++){let n=t[e];if(Se(n))return ke(n)}},Se=e=>e&&e.key===`PRIV`&&e.info===`com.apple.streaming.transportStreamTimestamp`,Ce=e=>{let t=String.fromCharCode(e[0],e[1],e[2],e[3]),n=ye(e,4);return{type:t,size:n,data:e.subarray(10,10+n)}},we=e=>{let t=0,n=[];for(;ge(e,t);){let r=ye(e,t+6);t+=10;let i=t+r;for(;t+8<i;){let r=Ce(e.subarray(t)),i=Te(r);i&&n.push(i),t+=r.size+10}_e(e,t)&&(t+=10)}return n},Te=e=>e.type===`PRIV`?Ee(e):e.type[0]===`W`?Oe(e):De(e),Ee=e=>{if(e.size<2)return;let t=N(e.data,!0),n=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:n.buffer}},De=e=>{if(e.size<2)return;if(e.type===`TXXX`){let t=1,n=N(e.data.subarray(t),!0);t+=n.length+1;let r=N(e.data.subarray(t));return{key:e.type,info:n,data:r}}let t=N(e.data.subarray(1));return{key:e.type,data:t}},Oe=e=>{if(e.type===`WXXX`){if(e.size<2)return;let t=1,n=N(e.data.subarray(t),!0);t+=n.length+1;let r=N(e.data.subarray(t));return{key:e.type,info:n,data:r}}let t=N(e.data);return{key:e.type,data:t}},ke=e=>{if(e.data.byteLength===8){let t=new Uint8Array(e.data),n=t[3]&1,r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,n&&(r+=47721858.84),Math.round(r)}},N=(e,t=!1)=>{let n=je();if(n){let r=n.decode(e);if(t){let e=r.indexOf(`\0`);return e===-1?r:r.substring(0,e)}return r.replace(/\0/g,``)}let r=e.length,i,a,o,s=``,c=0;for(;c<r;){if(i=e[c++],i===0&&t)return s;if(i!==0&&i!==3)switch(i>>
14){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:s+=String.fromCharCode(i);break;case 12:case 13:a=e[c++],s+=String.fromCharCode((i&31)<<6|a&63);break;case 14:a=e[c++],o=e[c++],s+=String.fromCharCode((i&15)<<12|(a&63)<<6|(o&63)<<0)}}return s},Ae;function je(){return!Ae&&self.TextDecoder!==void 0&&(Ae=new self.TextDecoder(`utf-8`)),Ae}var P={hexDump:function(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n].toString(16);r.length<2&&(r=`0`+r),t+=r}return t}},Me=2**32-1,Ne=[].push,Pe={video:1,audio:2,id3:3,text:4};function F(e){return String.fromCharCode.apply(null,e)}function Fe(e,t){let n=e[t]<<8|e[t+1];return n<0?65536+n:n}function I(e,t){let n=Ie(e,t);return n<0?4294967296+n:n}function Ie(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function Le(e,t,n){e[t]=n>>24,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255}function L(e,t){let n=[];if(!t.length)return n;let r=e.byteLength;for(let i=0;i<r;){let a=I(e,i),o=F(e.subarray(i+4,i+8)),s=a>1?i+a:r;if(o===t[0]){if(t.length===1)n.push(e.subarray(i+8,s));else{let r=L(e.subarray(i+8,s),t.slice(1));r.length&&Ne.apply(n,r)}}i=s}return n}function Re(e){let t=[],n=e[0],r=8,i=I(e,r);r+=4,r+=n===0?8:16,r+=2;let a=e.length+0,o=Fe(e,r);r+=2;for(let n=0;n<o;n++){let n=r,o=I(e,n);n+=4;let s=o&2147483647;if((o&2147483648)>>>31==1)return y.warn(`SIDX has hierarchical references (not supported)`),null;let c=I(e,n);n+=4,t.push({referenceSize:s,subsegmentDuration:c,info:{duration:c/i,start:a,end:a+s-1}}),a+=s,n+=4,r=n}return{earliestPresentationTime:0,timescale:i,version:n,referencesCount:o,references:t}}function ze(e){let t=[],n=L(e,[`moov`,`trak`]);for(let e=0;e<n.length;e++){let r=n[e],i=L(r,[`tkhd`])[0];if(i){let e=i[0],n=e===0?12:20,a=I(i,n),o=L(r,[`mdia`,`mdhd`])[0];if(o){e=o[0],n=e===0?12:20;let i=I(o,n),s=L(r,[`mdia`,`hdlr`])[0];if(s){let e=F(s.subarray(8,12)),n={soun:D.AUDIO,vide:D.VIDEO}[e];if(n){let e=L(r,[`mdia`,`minf`,`stbl`,`stsd`])[0],o;e&&(o=F(e.subarray(12,16))),t[a]={timescale:i,type:n},t[n]={timescale:i,id:a,codec:o}}}}}}return L(e,[`moov`,`mvex`,`trex`]).forEach(e=>{let n=I(e,4),r=t[n];r&&(r.default={duration:I(e,12),flags:I(e,20)})}),t}function Be(e,t){if(!e||!t)return e;let n=t.keyId;return n&&t.isCommonEncryption&&L(e,[`moov`,`trak`]).forEach(e=>{let t=L(e,[`mdia`,`minf`,`stbl`,`stsd`])[0].subarray(8),r=L(t,[`enca`]),i=r.length>0;i||(r=L(t,[`encv`])),r.forEach(e=>{L(i?e.subarray(28):e.subarray(78),[`sinf`]).forEach(e=>{let t=Ve(e);if(t){let e=t.subarray(8,24);e.some(e=>e!==0)||(y.log(`[eme] Patching keyId in 'enc${i?`a`:`v`}>sinf>>tenc' box: ${P.hexDump(e)} -> ${P.hexDump(n)}`),t.set(n,8))}})})}),e}function Ve(e){let t=L(e,[`schm`])[0];if(t){let n=F(t.subarray(4,8));if(n===`cbcs`||n===`cenc`)return L(e,[`schi`,`tenc`])[0]}return y.error(`[eme] missing 'schm' box`),null}function He(e,t){return L(t,[`moof`,`traf`]).reduce((t,n)=>{let r=L(n,[`tfdt`])[0],i=r[0],a=L(n,[`tfhd`]).reduce((t,n)=>{let a=e[I(n,4)];if(a){let e=I(r,4);if(i===1){if(e===Me)return y.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`),t;e*=Me+1,e+=I(r,8)}let n=a.timescale||9e4,o=e/n;if(isFinite(o)&&(t===null||o<t))return o}return t},null);return a!==null&&isFinite(a)&&(t===null||a<t)?a:t},null)}function Ue(e,t){let n=0,r=0,i=0,a=L(e,[`moof`,`traf`]);for(let e=0;e<a.length;e++){let o=a[e],s=L(o,[`tfhd`])[0],c=t[I(s,4)];if(!c)continue;let l=c.default,u=I(s,0)|l?.flags,d=l?.duration;u&8&&(d=u&2?I(s,12):I(s,8));let f=c.timescale||9e4,p=L(o,[`trun`]);for(let e=0;e<p.length;e++){if(n=We(p[e]),!n&&d){let t=I(p[e],4);n=d*t}c.type===D.VIDEO?r+=n/f:c.type===D.AUDIO&&(i+=n/f)}}if(r===0&&i===0){let t=0,n=L(e,[`sidx`]);for(let e=0;e<n.length;e++){let r=Re(n[e]);r!=null&&r.references&&(t+=r.references.reduce((e,t)=>e+t.info.duration||0,0))}return t}return r||i}function We(e){let t=I(e,0),n=8;t&1&&(n+=4),t&4&&(n+=4);let r=0,i=I(e,4);for(let a=0;a<i;a++){if(t&256){let t=I(e,n);r+=t,n+=4}t&512&&(n+=4),t&1024&&(n+=4),t&2048&&(n+=4)}return r}function Ge(e,t,n){L(t,[`moof`,`traf`]).forEach(t=>{L(t,[`tfhd`]).forEach(r=>{let i=e[I(r,4)];if(!i)return;let a=i.timescale||9e4;
1L(t,[`tfdt`]).forEach(e=>{let t=e[0],r=I(e,4);if(t===0)r-=n*a,r=Math.max(r,0),Le(e,4,r);else{r*=2**32,r+=I(e,8),r-=n*a,r=Math.max(r,0);let t=Math.floor(r/(Me+1)),i=Math.floor(r%(Me+1));Le(e,4,t),Le(e,8,i)}})})})}function Ke(e){let t={valid:null,remainder:null},n=L(e,[`moof`]);if(!n)return t;if(n.length<2)return t.remainder=e,t;let r=n[n.length-1];return t.valid=he(e,0,r.byteOffset-8),t.remainder=he(e,r.byteOffset-8),t}function qe(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function Je(e,t){let n=[],r=t.samples,i=t.timescale,a=t.id,o=!1;return L(r,[`moof`]).map(s=>{let c=s.byteOffset-8;L(s,[`traf`]).map(s=>{let l=L(s,[`tfdt`]).map(e=>{let t=e[0],n=I(e,4);return t===1&&(n*=2**32,n+=I(e,8)),n/i})[0];return l!==void 0&&(e=l),L(s,[`tfhd`]).map(l=>{let u=I(l,4),d=I(l,0)&16777215,f=!!(d&1),p=!!(d&2),m=!!(d&8),h=0,g=!!(d&16),_=0,v=!!(d&32),y=8;u===a&&(f&&(y+=8),p&&(y+=4),m&&(h=I(l,y),y+=4),g&&(_=I(l,y),y+=4),v&&(y+=4),t.type===`video`&&(o=Ye(t.codec)),L(s,[`trun`]).map(a=>{let s=a[0],l=I(a,0)&16777215,u=!!(l&1),d=0,f=!!(l&4),p=!!(l&256),m=0,g=!!(l&512),v=0,y=!!(l&1024),b=!!(l&2048),x=0,S=I(a,4),C=8;u&&(d=I(a,C),C+=4),f&&(C+=4);let w=d+c;for(let c=0;c<S;c++){if(p?(m=I(a,C),C+=4):m=h,g?(v=I(a,C),C+=4):v=_,y&&(C+=4),b&&(x=s===0?I(a,C):Ie(a,C),C+=4),t.type===D.VIDEO){let t=0;for(;t<v;){let a=I(r,w);w+=4,Xe(o,r[w])&&Ze(r.subarray(w,w+a),o?2:1,e+x/i,n),w+=a,t+=a+4}}e+=m/i}}))})})}),n}function Ye(e){if(!e)return!1;let t=e.indexOf(`.`),n=t<0?e:e.substring(0,t);return n===`hvc1`||n===`hev1`||n===`dvh1`||n===`dvhe`}function Xe(e,t){if(e){let e=t>>1&63;return e===39||e===40}return(t&31)==6}function Ze(e,t,n,r){let i=Qe(e),a=0;a+=t;let o=0,s=0,c=!1,l=0;for(;a<i.length;){o=0;do{if(a>=i.length)break;l=i[a++],o+=l}while(l===255);s=0;do{if(a>=i.length)break;l=i[a++],s+=l}while(l===255);let e=i.length-a;if(!c&&o===4&&a<i.length){if(c=!0,i[a++]===181){let e=Fe(i,a);if(a+=2,e===49){let e=I(i,a);if(a+=4,e===1195456820){let e=i[a++];if(e===3){let t=i[a++],s=31&t,c=64&t,l=c?2+s*3:0,u=new Uint8Array(l);if(c){u[0]=t;for(let e=1;e<l;e++)u[e]=i[a++]}r.push({type:e,payloadType:o,pts:n,bytes:u})}}}}}else if(o===5&&s<e){if(c=!0,s>16){let e=[];for(let t=0;t<16;t++){let n=i[a++].toString(16);e.push(n.length==1?`0`+n:n),(t===3||t===5||t===7||t===9)&&e.push(`-`)}let t=s-16,c=new Uint8Array(t);for(let e=0;e<t;e++)c[e]=i[a++];r.push({payloadType:o,pts:n,uuid:e.join(``),userData:N(c),userDataBytes:c})}}else if(s<e)a+=s;else if(s>e)break}}function Qe(e){let t=e.byteLength,n=[],r=1;for(;r<t-2;)e[r]===0&&e[r+1]===0&&e[r+2]===3?(n.push(r+2),r+=2):r++;if(n.length===0)return e;let i=t-n.length,a=new Uint8Array(i),o=0;for(r=0;r<i;o++,r++)o===n[0]&&(o++,n.shift()),a[r]=e[o];return a}function $e(e){let t=e[0],n=``,r=``,i=0,a=0,o=0,s=0,c=0,l=0;if(t===0){for(;F(e.subarray(l,l+1))!==`\0`;)n+=F(e.subarray(l,l+1)),l+=1;for(n+=F(e.subarray(l,l+1)),l+=1;F(e.subarray(l,l+1))!==`\0`;)r+=F(e.subarray(l,l+1)),l+=1;r+=F(e.subarray(l,l+1)),l+=1,i=I(e,12),a=I(e,16),s=I(e,20),c=I(e,24),l=28}else if(t===1){l+=4,i=I(e,l),l+=4;let t=I(e,l);l+=4;let a=I(e,l);for(l+=4,o=2**32*t+a,Number.isSafeInteger(o)||(o=2**53-1,y.warn(`Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box`)),s=I(e,l),l+=4,c=I(e,l),l+=4;F(e.subarray(l,l+1))!==`\0`;)n+=F(e.subarray(l,l+1)),l+=1;for(n+=F(e.subarray(l,l+1)),l+=1;F(e.subarray(l,l+1))!==`\0`;)r+=F(e.subarray(l,l+1)),l+=1;r+=F(e.subarray(l,l+1)),l+=1}let u=e.subarray(l,e.byteLength);return{schemeIdUri:n,value:r,timeScale:i,presentationTime:o,presentationTimeDelta:a,eventDuration:s,id:c,payload:u}}function et(e,...t){let n=t.length,r=8,i=n;for(;i--;)r+=t[i].byteLength;let a=new Uint8Array(r);for(a[0]=r>>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=r&255,a.set(e,4),i=0,r=8;i<n;i++)a.set(t[i],r),r+=t[i].byteLength;return a}function tt(e,t,n){if(e.byteLength!==16)throw RangeError(`Invalid system id`);let r,i;if(t){r=1,i=new Uint8Array(t.length*16);for(let e=0;e<t.length;e++){let n=t[e];if(n.byteLength!==16)throw RangeError(`Invalid key`);i.set(n,e*16)}}else r=0,i=new Uint8Array;let a;r>0?(a=new Uint8Array(4),t.length>0&&new DataView(a.buffer).setUint32(0,t.length,!1)):a=new Uint8Array;let o=new Uint8Array(4);return n&&n.byteLength>0&&new DataView(o.buffer).setUint32(0,n.byteLength,!1),et([112,115,115,104],new Uint8Array([r,0,0,0]),e,a,i,o,n||new Uint8Array)}function nt(e){if(!(e instanceof ArrayBuffer)||e.byteLength<32)return null;let t={version:0,systemId:``,kids:null,data:null},n=new DataView(e),r=n.getUint32(0);if(e.byteLength!==r&&r>44||n.getUint32(4)!==1886614376||(t.version=n.getUint32(8)>>>24,t.version>1))return null;t.systemId=P.hexDump(new Uint8Array(e,12,16));let i=n.getUint32(28);if(t.version===0){if(r-32<i)return null;t.data=new Uint8Array(e,32,i)}else if(t.version===1){t.kids=[];for(let n=0;n<i;n++)t.kids.push(new Uint8Array(e,32+n*16,16))}return t}var rt={},it=class e{static clearKeyUriToKeyIdMap(){rt={}}constructor(e,t,n,r=[1],i=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pss
1h=null,this.method=e,this.uri=t,this.keyFormat=n,this.keyFormatVersions=r,this.iv=i,this.encrypted=e?e!==`NONE`:!1,this.isCommonEncryption=this.encrypted&&e!==`AES-128`}isSupported(){if(this.method){if(this.method===`AES-128`||this.method===`NONE`)return!0;if(this.keyFormat===`identity`)return this.method===`SAMPLE-AES`;switch(this.keyFormat){case M.FAIRPLAY:case M.WIDEVINE:case M.PLAYREADY:case M.CLEARKEY:return[`ISO-23001-7`,`SAMPLE-AES`,`SAMPLE-AES-CENC`,`SAMPLE-AES-CTR`].indexOf(this.method)!==-1}}return!1}getDecryptData(t){if(!this.encrypted||!this.uri)return null;if(this.method===`AES-128`&&this.uri&&!this.iv){typeof t!=`number`&&(this.method===`AES-128`&&!this.iv&&y.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0);let n=at(t);return new e(this.method,this.uri,`identity`,this.keyFormatVersions,n)}let n=ae(this.uri);if(n)switch(this.keyFormat){case M.WIDEVINE:this.pssh=n,n.length>=22&&(this.keyId=n.subarray(n.length-22,n.length-6));break;case M.PLAYREADY:{let e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=tt(e,null,n);let t=new Uint16Array(n.buffer,n.byteOffset,n.byteLength/2),r=String.fromCharCode.apply(null,Array.from(t)),i=r.substring(r.indexOf(`<`),r.length),a=new DOMParser().parseFromString(i,`text/xml`).getElementsByTagName(`KID`)[0];if(a){let e=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute(`VALUE`);if(e){let t=ne(e).subarray(0,16);ie(t),this.keyId=t}}break}default:{let e=n.subarray(0,16);if(e.length!==16){let t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||this.keyId.byteLength!==16){let e=rt[this.uri];if(!e){let t=Object.keys(rt).length%(2**53-1);e=new Uint8Array(16),new DataView(e.buffer,12,4).setUint32(0,t),rt[this.uri]=e}this.keyId=e}return this}};function at(e){let t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=e>>8*(15-n)&255;return t}var ot=/\{\$([a-zA-Z0-9-_]+)\}/g;function st(e){return ot.test(e)}function R(e,t,n){if(e.variableList!==null||e.hasVariableRefs)for(let r=n.length;r--;){let i=n[r],a=t[i];a&&(t[i]=ct(e,a))}}function ct(e,t){if(e.variableList!==null||e.hasVariableRefs){let n=e.variableList;return t.replace(ot,t=>{let r=t.substring(2,t.length-1),i=n?.[r];return i===void 0?(e.playlistParsingError||=Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`),t):i})}return t}function lt(e,t,n){let r=e.variableList;r||(e.variableList=r={});let i,a;if(`QUERYPARAM`in t){i=t.QUERYPARAM;try{let e=new self.URL(n).searchParams;if(e.has(i))a=e.get(i);else throw Error(`"${i}" does not match any query parameter in URI: "${n}"`)}catch(t){e.playlistParsingError||=Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`)}}else i=t.NAME,a=t.VALUE;i in r?e.playlistParsingError||=Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`):r[i]=a||``}function ut(e,t,n){let r=t.IMPORT;if(n&&r in n){let t=e.variableList;t||(e.variableList=t={}),t[r]=n[r]}else e.playlistParsingError||=Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`)}function dt(){if(!(typeof self>`u`))return self.MediaSource||self.WebKitMediaSource}var ft={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}},pt=dt();function mt(e,t){let n=ft[t];return!!n&&n[e.slice(0,4)]===!0}function ht(e,t){return pt?.isTypeSupported(`${t||`video`}/mp4;codecs="${e}"`)??!1}var gt=/#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,_t=/#EXT-X-MEDIA:(.*)/g,vt=/^#EXT(?:INF|-X-TARGETDURATION):/m,yt=new RegExp([`#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?`,`(?!#) *(\\S[\\S ]*)`,`#EXT-X-BYTERANGE:*(.+)`,`#EXT-X-PROGRAM-DATE-TIME:(.+)`,`#.*`].join(`|`),`g`),bt=new RegExp([`#(EXTM3U)`,`#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)`,`#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\\d+)`,`#EXT-X-(DISCONTINUITY|ENDLIST|GAP)`,`(#)([^:]*):(.*)`,`(#)(.*)(?:.*)\\r?\\n?`].join(`|`)),xt=class e{static findGroup(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r.id===t)return r}}static convertAVC1ToAVCOTI(e){let t=e.split(`.`);if(t.length>2){let e=t.shift()+`.`;return e+=parseInt(t.shift()).toString(16),e+=(`000`+parseInt(t.shift()).toString(16)).slice(-4),e}return e}static resolve(e,t){return n.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return vt.test(e)}static parseMasterPlaylist(t,n){let r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:st(t)},i=[];gt.lastIndex=0;let a;for(;(a=gt.exec(t))!=null;)if(a[1]){var o;let t=new S(a[1]);R(r,t,[`CODECS`,`SUPPLEMENTAL-CODECS`,`ALLOWED-CPC`,`PATHWAY-ID`,`STABLE-VARIANT-ID`,`AUDIO`,`VIDEO`,`SUBTITLES`,`CLOSED-CAPTIONS`,`NAME`]);let s=ct(r,a[2]),c={attrs:t,bitrate:t.decimalInteger(`AVERAGE-BANDWIDTH`)||t.decimalInteger(`BANDWIDTH`),name:t.NAME,url:e.resolve(s,n)},l=t.decimalResolution(`RESOLUTION`);l&&(c.width=l.width,c.height=l.height),wt((t.CODECS||``).split(/[ ,]+/).filter(e=>e),c),c.videoCodec&&c.videoCodec.indexOf(`avc1`)!==-1&&(c.videoCodec=e.convertAVC1ToAVCOTI(c.videoCodec)),(o=c.unknownCodecs)!=null&&o.length||i.push(c),r.levels.push(c)}else if(a[3]){let t=a[3],i=a[4];switch(t){case`SESSION-DATA`:{let e=new S(i);R(r,e,[`DATA-ID`,`LANGUAGE`,`VALUE`,`URI`]);let t=e[`DATA-ID`];t&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[t]=e);break}case`SESSION-KEY`:{let e=St(i,n,r);e.encrypted&&e.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(e)):y.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case`DEFINE`:{let e=new S(i);R(r,e,[`NAME`,`VALUE`,`QUERYPARAM`]),lt(r,e,n)}break;case`CONTENT-STEERING`:{let t=new S(i);R(r,t,[`SERVER-URI`,`PATHWAY-ID`]),r.contentSteering={uri:e.resolve(t[`SERVER-URI`],n),pathwayId:t[`PATHWAY-ID`]||`.`};break}case`START`:r.startTimeOffset=Ct(i)}}return r.levels=i.length>0&&i.length<r.levels.length?i:r.levels,r.levels.length===0&&(r.playlistParsingError=Error(`no levels found in manifest`)),r}static parseMasterPlaylistMedia(t,n,r){let i,a={},o=r.levels,s={AUDIO:o.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:o.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]},c=0;for(_t.lastIndex=0;(i=_t.exec(t))!==null;){let t=new S(i[1]),o=t.TYPE;if(o){let i=s[o],l=a[o]||[];a[o]=l,R(r,t,[`URI`,`GROUP-ID`,`LANGUAGE`,`ASSOC-LANGUAGE`,`STABLE-RENDITION-ID`,`NAME`,`INSTREAM-ID`,`CHARACTERISTICS`,`CHANNELS`]);let u={attrs:t,bitrate:0,id:c++,groupId:t[`GROUP-ID`]||``,instreamId:t[`INSTREAM-ID`],name:t.NAME||t.LANGUAGE||``,type:o,default:t.bool(`DEFAULT`),autoselect:t.bool(`AUTOSELECT`),forced:t.bool(`FORCED`),lang:t.LANGUAGE,url:t.URI?e.resolve(t.URI,n):``};if(i!=null&&i.length){let t=e.findGroup(i,u.groupId)||i[0];Tt(u,t,`audioCodec`),Tt(u,t,`textCodec`)}l.push(u)}}return a}static parseLevelPlaylist(e,t,n,r,i,a){let s=new A(t),c=s.fragments,u=null,d=0,f=0,p=0,m=0,h=null,g=new ee(r,t),_,v,b,x=-1,C=!1;for(yt.lastIndex=0,s.m3u8=e,s.hasVariableRefs=st(e);(_=yt.exec(e))!==null;){C&&(C=!1,g=new ee(r,t),g.start=p,g.sn=d,g.cc=m,g.level=n,u&&(g.initSegment=u,g.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null));let e=_[1];if(e){g.duration=parseFloat(e);let t=(` `+_[2]).slice(1);g.title=t||null,g.tagList.push(t?[`INF`,e,t]:[`INF`,e])}else if(_[3]){if(l(g.duration)){g.start=p,b&&kt(g,b,s),g.sn=d,g.level=n,g.cc=m,g.urlId=i,c.push(g);let e=(` `+_[3]).slice(1);g.relurl=ct(s,e),Dt(g,h),h=g,p+=g.duration,d++,f=0,C=!0}}else if(_[4]){let e=(` `+_[4]).slice(1);h?g.setByteRange(e,h):g.setByteRange(e)}else if(_[5])g.rawProgramDateTime=(` `+_[5]).slice(1),g.tagList.push([`PROGRAM-DATE-TIME`,g.rawProgramDateTime]),x===-1&&(x=c.length);
1else{if(_=_[0].match(bt),!_){y.warn(`No matches on slow regex match for level playlist!`);continue}for(v=1;v<_.length&&_[v]===void 0;v++);let e=(` `+_[v]).slice(1),i=(` `+_[v+1]).slice(1),p=_[v+2]?(` `+_[v+2]).slice(1):``;switch(e){case`PLAYLIST-TYPE`:s.type=i.toUpperCase();break;case`MEDIA-SEQUENCE`:d=s.startSN=parseInt(i);break;case`SKIP`:{let e=new S(i);R(s,e,[`RECENTLY-REMOVED-DATERANGES`]);let t=e.decimalInteger(`SKIPPED-SEGMENTS`);if(l(t)){s.skippedSegments=t;for(let e=t;e--;)c.unshift(null);d+=t}let n=e.enumeratedString(`RECENTLY-REMOVED-DATERANGES`);n&&(s.recentlyRemovedDateranges=n.split(`	`));break}case`TARGETDURATION`:s.targetduration=Math.max(parseInt(i),1);break;case`VERSION`:s.version=parseInt(i);break;case`EXTM3U`:break;case`ENDLIST`:s.live=!1;break;case`#`:(i||p)&&g.tagList.push(p?[i,p]:[i]);break;case`DISCONTINUITY`:m++,g.tagList.push([`DIS`]);break;case`GAP`:g.gap=!0,g.tagList.push([e]);break;case`BITRATE`:g.tagList.push([e,i]);break;case`DATERANGE`:{let e=new S(i);R(s,e,[`ID`,`CLASS`,`START-DATE`,`END-DATE`,`SCTE35-CMD`,`SCTE35-OUT`,`SCTE35-IN`]),R(s,e,e.clientAttrs);let t=new T(e,s.dateRanges[e.ID]);t.isValid||s.skippedSegments?s.dateRanges[t.id]=t:y.warn(`Ignoring invalid DATERANGE tag: "${i}"`),g.tagList.push([`EXT-X-DATERANGE`,i]);break}case`DEFINE`:{let e=new S(i);R(s,e,[`NAME`,`VALUE`,`IMPORT`,`QUERYPARAM`]),`IMPORT`in e?ut(s,e,a):lt(s,e,t)}break;case`DISCONTINUITY-SEQUENCE`:m=parseInt(i);break;case`KEY`:{let e=St(i,t,s);if(e.isSupported()){if(e.method===`NONE`){b=void 0;break}b||={},b[e.keyFormat]&&(b=o({},b)),b[e.keyFormat]=e}else y.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${i}"`);break}case`START`:s.startTimeOffset=Ct(i);break;case`MAP`:{let e=new S(i);if(R(s,e,[`BYTERANGE`,`URI`]),g.duration){let i=new ee(r,t);Ot(i,e,n,b),u=i,g.initSegment=u,u.rawProgramDateTime&&!g.rawProgramDateTime&&(g.rawProgramDateTime=u.rawProgramDateTime)}else Ot(g,e,n,b),u=g,C=!0;break}case`SERVER-CONTROL`:{let e=new S(i);s.canBlockReload=e.bool(`CAN-BLOCK-RELOAD`),s.canSkipUntil=e.optionalFloat(`CAN-SKIP-UNTIL`,0),s.canSkipDateRanges=s.canSkipUntil>0&&e.bool(`CAN-SKIP-DATERANGES`),s.partHoldBack=e.optionalFloat(`PART-HOLD-BACK`,0),s.holdBack=e.optionalFloat(`HOLD-BACK`,0);break}case`PART-INF`:s.partTarget=new S(i).decimalFloatingPoint(`PART-TARGET`);break;case`PART`:{let e=s.partList;e||=s.partList=[];let n=f>0?e[e.length-1]:void 0,r=f++,a=new S(i);R(s,a,[`BYTERANGE`,`URI`]);let o=new k(a,g,t,r,n);e.push(o),g.duration+=o.duration;break}case`PRELOAD-HINT`:{let e=new S(i);R(s,e,[`URI`]),s.preloadHint=e;break}case`RENDITION-REPORT`:{let e=new S(i);R(s,e,[`URI`]),s.renditionReports=s.renditionReports||[],s.renditionReports.push(e);break}default:y.warn(`line parsed but not handled: ${_}`)}}}h&&!h.relurl?(c.pop(),p-=h.duration,s.partList&&(s.fragmentHint=h)):s.partList&&(Dt(g,h),g.cc=m,s.fragmentHint=g,b&&kt(g,b,s));let w=c.length,E=c[0],D=c[w-1];if(p+=s.skippedSegments*s.targetduration,p>0&&w&&D){s.averagetargetduration=p/w;let e=D.sn;s.endSN=e===`initSegment`?0:e,s.live||(D.endList=!0),E&&(s.startCC=E.cc)}else s.endSN=0,s.startCC=0;return s.fragmentHint&&(p+=s.fragmentHint.duration),s.totalduration=p,s.endCC=m,x>0&&Et(c,x),s}};function St(e,t,n){let r=new S(e);R(n,r,[`KEYFORMAT`,`KEYFORMATVERSIONS`,`URI`,`IV`,`URI`]);let i=r.METHOD??``,a=r.URI,o=r.hexadecimalInteger(`IV`),s=r.KEYFORMATVERSIONS,c=r.KEYFORMAT??`identity`;return a&&r.IV&&!o&&y.error(`Invalid IV: ${r.IV}`),new it(i,a?xt.resolve(a,t):``,c,(s||`1`).split(`/`).map(Number).filter(Number.isFinite),o)}function Ct(e){let t=new S(e).decimalFloatingPoint(`TIME-OFFSET`);return l(t)?t:null}function wt(e,t){[`video`,`audio`,`text`].forEach(n=>{let r=e.filter(e=>mt(e,n));if(r.length){let i=r.filter(e=>e.lastIndexOf(`avc1`,0)===0||e.lastIndexOf(`mp4a`,0)===0);t[`${n}Codec`]=i.length>0?i[0]:r[0],e=e.filter(e=>r.indexOf(e)===-1)}}),t.unknownCodecs=e}function Tt(e,t,n){let r=t[n];r&&(e[n]=r)}function Et(e,t){let n=e[t];for(let r=t;r--;){let t=e[r];if(!t)return;t.programDateTime=n.programDateTime-t.duration*1e3,n=t}}function Dt(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):t!=null&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime),l(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}function Ot(e,t,n,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=n,e.sn=`initSegment`,r&&(e.levelkeys=r),e.initSegment=null}function kt(e,t,n){e.levelkeys=t;let{encryptedFragments:r}=n;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(e=>t[e].isCommonEncryption)&&r.push(e)}var z={MANIFEST:`manifest`,LEVEL:`level`,AUDIO_TRACK:`audioTrack`,SUBTITLE_TRACK:`
1subtitleTrack`},B={MAIN:`main`,AUDIO:`audio`,SUBTITLE:`subtitle`};function At(e){let{type:t}=e;switch(t){case z.AUDIO_TRACK:return B.AUDIO;case z.SUBTITLE_TRACK:return B.SUBTITLE;default:return B.MAIN}}function jt(e,t){let n=e.url;return(n===void 0||n.indexOf(`data:`)===0)&&(n=t.url),n}var Mt=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(u.MANIFEST_LOADING,this.onManifestLoading,this),e.on(u.LEVEL_LOADING,this.onLevelLoading,this),e.on(u.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(u.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){let{hls:e}=this;e.off(u.MANIFEST_LOADING,this.onManifestLoading,this),e.off(u.LEVEL_LOADING,this.onLevelLoading,this),e.off(u.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(u.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){let t=this.hls.config,n=t.pLoader,r=t.loader,i=new(n||r)(t);return this.loaders[e.type]=i,i}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:n}=t;this.variableList=null,this.load({id:null,level:0,responseType:`text`,type:z.MANIFEST,url:n,deliveryDirectives:null})}onLevelLoading(e,t){let{id:n,level:r,url:i,deliveryDirectives:a}=t;this.load({id:n,level:r,responseType:`text`,type:z.LEVEL,url:i,deliveryDirectives:a})}onAudioTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:z.AUDIO_TRACK,url:i,deliveryDirectives:a})}onSubtitleTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:z.SUBTITLE_TRACK,url:i,deliveryDirectives:a})}load(e){var t;let n=this.hls.config,r=this.getInternalLoader(e);if(r){let t=r.context;if(t&&t.url===e.url){y.trace(`[playlist-loader]: playlist request ongoing`);return}y.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),r.abort()}let i;if(i=e.type===z.MANIFEST?n.manifestLoadPolicy.default:o({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=this.createInternalLoader(e),(t=e.deliveryDirectives)!=null&&t.part){let t;if(e.type===z.LEVEL&&e.level!==null?t=this.hls.levels[e.level].details:e.type===z.AUDIO_TRACK&&e.id!==null?t=this.hls.audioTracks[e.id].details:e.type===z.SUBTITLE_TRACK&&e.id!==null&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,n=t.targetduration;if(e&&n){let t=Math.max(e*3,n*.8)*1e3;i=o({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}let a=i.errorRetry||i.timeoutRetry||{},s={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0};r.load(e,s,{onSuccess:(e,t,n,r)=>{let i=this.getInternalLoader(n);this.resetInternalLoader(n.type);let a=e.data;if(a.indexOf(`#EXTM3U`)!==0){this.handleManifestParsingError(e,n,Error(`no EXTM3U delimiter`),r||null,t);return}t.parsing.start=performance.now(),xt.isMediaPlaylist(a)?this.handleTrackOrLevelPlaylist(e,t,n,r||null,i):this.handleMasterPlaylist(e,t,n,r)},onError:(e,t,n,r)=>{this.handleNetworkError(t,n,!1,e,r)},onTimeout:(e,t,n)=>{this.handleNetworkError(t,n,!0,void 0,e)}})}handleMasterPlaylist(e,t,n,r){let i=this.hls,a=e.data,o=jt(e,n),s=xt.parseMasterPlaylist(a,o);if(s.playlistParsingError){this.handleManifestParsingError(e,n,s.playlistParsingError,r,t);return}let{contentSteering:c,levels:l,sessionData:d,sessionKeys:f,startTimeOffset:p,variableList:m}=s;this.variableList=m;let{AUDIO:h=[],SUBTITLES:g,"CLOSED-CAPTIONS":_}=xt.parseMasterPlaylistMedia(a,o,s);h.length&&!h.some(e=>!e.url)&&l[0].audioCodec&&!l[0].attrs.AUDIO&&(y.log(`[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one`),h.unshift({type:`main`,name:`main`,groupId:`main`,default:!1,autoselect:!1,forced:!1,id:-1,attrs:new S({}),bitrate:0,url:``})),i.trigger(u.MANIFEST_LOADED,{levels:l,audioTracks:h,subtitles:g,captions:_,contentSteering:c,url:o,stats:t,networkDetails:r,sessionData:d,sessionKeys:f,startTimeOffset:p,variableList:m})}handleTrackOrLevelPlaylist(e,t,n,r,i){let a=this.hls,{id:o,level:s,type:c}=n,d=jt(e,n),f=l(o)?o:0,p=l(s)?s:f,m=At(n),h=xt.parseLevelPlaylist(e.data,d,p,m,f,this.variableList);if(c===z.MANIFEST){let e={attrs:new S({}),bitrate:0,details:h,name:``,url:d};a.trigger(u.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:d,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),n.levelDetails=h,this.handlePlaylistLoaded(h,e,t,n,r,i)}handleManifestParsingError(e,t,n,r,i){this.hls.trigger(u.ERROR,{type:d.NETWORK_E
1RROR,details:f.MANIFEST_PARSING_ERROR,fatal:t.type===z.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:t,networkDetails:r,stats:i})}handleNetworkError(e,t,n=!1,r,a){let o=`A network ${n?`timeout`:`error`+(r?` (status `+r.code+`)`:``)} occurred while loading ${e.type}`;e.type===z.LEVEL?o+=`: ${e.level} id: ${e.id}`:(e.type===z.AUDIO_TRACK||e.type===z.SUBTITLE_TRACK)&&(o+=` id: ${e.id} group-id: "${e.groupId}"`);let s=Error(o);y.warn(`[playlist-loader]: ${o}`);let c=f.UNKNOWN,l=!1,p=this.getInternalLoader(e);switch(e.type){case z.MANIFEST:c=n?f.MANIFEST_LOAD_TIMEOUT:f.MANIFEST_LOAD_ERROR,l=!0;break;case z.LEVEL:c=n?f.LEVEL_LOAD_TIMEOUT:f.LEVEL_LOAD_ERROR,l=!1;break;case z.AUDIO_TRACK:c=n?f.AUDIO_TRACK_LOAD_TIMEOUT:f.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case z.SUBTITLE_TRACK:c=n?f.SUBTITLE_TRACK_LOAD_TIMEOUT:f.SUBTITLE_LOAD_ERROR,l=!1}p&&this.resetInternalLoader(e.type);let m={type:d.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:p,context:e,error:s,networkDetails:t,stats:a};r&&(m.response=i({url:t?.url||e.url,data:void 0},r)),this.hls.trigger(u.ERROR,m)}handlePlaylistLoaded(e,t,n,r,i,a){let o=this.hls,{type:s,level:c,id:l,groupId:p,deliveryDirectives:m}=r,h=jt(t,r),g=At(r),_=typeof r.level==`number`&&g===B.MAIN?c:void 0;if(!e.fragments.length){let e=Error(`No Segments found in Playlist`);o.trigger(u.ERROR,{type:d.NETWORK_ERROR,details:f.LEVEL_EMPTY_ERROR,fatal:!1,url:h,error:e,reason:e.message,response:t,context:r,level:_,parent:g,networkDetails:i,stats:n});return}e.targetduration||(e.playlistParsingError=Error(`Missing Target Duration`));let v=e.playlistParsingError;if(v){o.trigger(u.ERROR,{type:d.NETWORK_ERROR,details:f.LEVEL_PARSING_ERROR,fatal:!1,url:h,error:v,reason:v.message,response:t,context:r,level:_,parent:g,networkDetails:i,stats:n});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),s){case z.MANIFEST:case z.LEVEL:o.trigger(u.LEVEL_LOADED,{details:e,level:_||0,id:l||0,stats:n,networkDetails:i,deliveryDirectives:m});break;case z.AUDIO_TRACK:o.trigger(u.AUDIO_TRACK_LOADED,{details:e,id:l||0,groupId:p||``,stats:n,networkDetails:i,deliveryDirectives:m});break;case z.SUBTITLE_TRACK:o.trigger(u.SUBTITLE_TRACK_LOADED,{details:e,id:l||0,groupId:p||``,stats:n,networkDetails:i,deliveryDirectives:m})}}};function Nt(e,t){let n;try{n=new Event(`addtrack`)}catch{n=document.createEvent(`Event`),n.initEvent(`addtrack`,!1,!1)}n.track=e,t.dispatchEvent(n)}function Pt(e,t){let n=e.mode;if(n===`disabled`&&(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(n){y.debug(`[texttrack-utils]: ${n}`);try{let n=new self.TextTrackCue(t.startTime,t.endTime,t.text);n.id=t.id,e.addCue(n)}catch(e){y.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}n===`disabled`&&(e.mode=n)}function Ft(e){let t=e.mode;if(t===`disabled`&&(e.mode=`hidden`),e.cues)for(let t=e.cues.length;t--;)e.removeCue(e.cues[t]);t===`disabled`&&(e.mode=t)}function It(e,t,n,r){let i=e.mode;if(i===`disabled`&&(e.mode=`hidden`),e.cues&&e.cues.length>0){let i=Rt(e.cues,t,n);for(let t=0;t<i.length;t++)(!r||r(i[t]))&&e.removeCue(i[t])}i===`disabled`&&(e.mode=i)}function Lt(e,t){if(t<e[0].startTime)return 0;let n=e.length-1;if(t>e[n].endTime)return-1;let r=0,i=n;for(;r<=i;){let a=Math.floor((i+r)/2);if(t<e[a].startTime)i=a-1;else if(t>e[a].startTime&&r<n)r=a+1;else return a}return e[r].startTime-t<t-e[i].startTime?r:i}function Rt(e,t,n){let r=[],i=Lt(e,t);if(i>-1)for(let a=i,o=e.length;a<o;a++){let i=e[a];if(i.startTime>=t&&i.endTime<=n)r.push(i);else if(i.startTime>n)return r}return r}var V={audioId3:`org.id3`,dateRange:`com.apple.quicktime.HLS`,emsg:`https://aomedia.org/emsg/ID3`},zt=.25;function Bt(){if(!(typeof self>`u`))return self.WebKitDataCue||self.VTTCue||self.TextTrackCue}var Vt=(()=>{let e=Bt();try{new e(0,1/0,``)}catch{return Number.MAX_VALUE}return 1/0})();function Ht(e,t){return e.getTime()/1e3-t}function Ut(e){return Uint8Array.from(e.replace(/^0x/,``).replace(/([\da-fA-F]{2}) ?/g,`0x$1 `).replace(/ +$/,``).split(` `)).buffer}var Wt=class{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(u.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(u.MANIFEST_LOADING,this.onManifestLoading,this),e.on(u.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(u.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(u.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){let{hls:e}=this;e.off(u.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(u.MANIFEST_LOADING,this.onManifestLoading,this),e.off(u.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(u.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(u.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(Ft(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 n=e[t];if(n.kind===`metadata`&&n.label===`id3`)return Nt(n,this.media),n}return this.media.addTextTrack(`metadata`,`id3`)}}onFragParsingMetadata(e,t){if(!this.media)return;let{hls:{config:{enableEmsgMetadataCues:n,enableID3MetadataCues:r}}}=this;if(!n&&!r)return;let{samples:i}=t;this.id3Track||=this.createTrack(this.media);let a=Bt();for(let e=0;e<i.length;e++){let t=i[e].type;if(t===V.emsg&&!n||!r)continue;let o=we(i[e].data);if(o){let n=i[e].pts,r=n+i[e].duration;r>Vt&&(r=Vt),r-n<=0&&(r=n+zt);for(let e=0;e<o.length;e++){let i=o[e];if(!Se(i)){this.updateId3CueEnds(n,t);let e=new a(n,r,``);e.value=i,t&&(e.type=t),this.id3Track.addCue(e)}}}}}updateId3CueEnds(e,t){let n=this.id3Track?.cues;if(n)for(let r=n.length;r--;){let i=n[r];i.type===t&&i.startTime<e&&i.endTime===Vt&&(i.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:n,type:r}){let{id3Track:i,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:s}}=a;if(i&&(o||s)){let e;e=r===`audio`?e=>e.type===V.audioId3&&s:r===`video`?e=>e.type===V.emsg&&o:e=>e.type===V.audioId3&&s||e.type===V.emsg&&o,It(i,t,n,e)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;let{dateRangeCuesAppended:n,id3Track:r}=this,{dateRanges:i}=t,a=Object.keys(i);if(r){let e=Object.keys(n).filter(e=>!a.includes(e));for(let t=e.length;t--;){let i=e[t];Object.keys(n[i].cues).forEach(e=>{r.removeCue(n[i].cues[e])}),delete n[i]}}let o=t.fragments[t.fragments.length-1];if(a.length===0||!l(o?.programDateTime))return;this.id3Track||=this.createTrack(this.media);let s=o.programDateTime/1e3-o.start,c=Bt();for(let e=0;e<a.length;e++){let t=a[e],r=i[t],o=n[t],l=o?.cues||{},u=o?.durationKnown||!1,d=Ht(r.startDate,s),f=Vt,p=r.endDate;if(p)f=Ht(p,s),u=!0;else if(r.endOnNext&&!u){let e=a.reduce((e,t)=>{let n=i[t];return n.class===r.class&&n.id!==t&&n.startDate>r.startDate&&e.push(n),e},[]).sort((e,t)=>e.startDate.getTime()-t.startDate.getTime())[0];e&&(f=Ht(e.startDate,s),u=!0)}let m=Object.keys(r.attr);for(let e=0;e<m.length;e++){let n=m[e];if(!C(n))continue;let i=l[n];if(i)u&&!o.durationKnown&&(i.endTime=f);else{let e=r.attr[n];i=new c(d,f,``),w(n)&&(e=Ut(e)),i.value={key:n,data:e},i.type=V.dateRange,i.id=t,this.id3Track.addCue(i),l[n]=i}}n[t]={cues:l,dateRange:r,durationKnown:u}}}},Gt=class{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 e.liveMaxLatencyDuration===void 0?t?e.liveMaxLatencyDurationCount*t.targetduration:0:e.liveMaxLatencyDuration}get targetLatency(){let{levelDetails:e}=this;if(e===null)return null;let{holdBack:t,partHoldBack:n,targetduration:r}=e,{liveSyncDuration:i,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,s=this.hls.userConfig,c=o&&n||t;(s.liveSyncDuration||s.liveSyncDurationCount||c===0)&&(c=i===void 0?a*r:i);let l=r;return c+Math.min(this.stallCount*1,l)}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency,n=this.levelDetails;if(e===null||t===null||n===null)return null;let r=n.edge,i=e-t-this.edgeStalled,a=r-n.totalduration,o=r-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(a,i),o)}get drift(){let{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){let{levelDetails:e}=this;if(e===null)return 0;let t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e,levelDetails:t}=this;if(!e||!t)return 0;let n=e.buffered.length;return(n?e.buffered.end(n-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}
1registerListeners(){this.hls.on(u.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(u.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(u.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(u.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(u.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(u.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(u.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(u.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(u.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(u.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),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 n;t.details===f.BUFFER_STALLED_ERROR&&(this.stallCount++,(n=this.levelDetails)!=null&&n.live&&y.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 n=this.computeLatency();if(n===null)return;this._latency=n;let{lowLatencyMode:r,maxLiveSyncPlaybackRate:i}=this.config;if(!r||i===1)return;let a=this.targetLatency;if(a===null)return;let o=n-a,s=o<Math.min(this.maxLatency,a+t.targetduration);if(t.live&&s&&o>.05&&this.forwardBufferLength>1){let t=Math.min(2,Math.max(1,i)),n=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(t,Math.max(1,n))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){let{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},Kt=[`NONE`,`TYPE-0`,`TYPE-1`,null],qt={No:``,Yes:`YES`,v2:`v2`};function Jt(e,t){let{canSkipUntil:n,canSkipDateRanges:r,endSN:i}=e,a=t===void 0?0:t-i;return n&&a<n?r?qt.v2:qt.Yes:qt.No}var Yt=class{constructor(e,t,n){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=n}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set(`_HLS_msn`,this.msn.toString()),this.part!==void 0&&t.searchParams.set(`_HLS_part`,this.part.toString()),this.skip&&t.searchParams.set(`_HLS_skip`,this.skip),t.href}},Xt=class{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(){return this.audioGroupIds?.[this.urlId]}get textGroupId(){return this.textGroupIds?.[this.urlId]}addFallback(e){this.url.push(e.url),this._attrs.push(e.attrs)}};function Zt(e,t){let n=t.startPTS;if(l(n)){let r=0,i;t.sn>e.sn?(r=n-e.start,i=e):(r=e.start-n,i=t),i.duration!==r&&(i.duration=r)}else t.start=t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?e.start+(e.minEndPTS-e.start):e.start+e.duration:Math.max(e.start-t.duration,0)}function Qt(e,t,n,r,i,a){r-n<=0&&(y.warn(`Fragment should have a positive duration`,t),r=n+t.duration,a=i+t.duration);let o=n,s=r,c=t.startPTS,u=t.endPTS;if(l(c)){let e=Math.abs(c-n);t.deltaPTS=l(t.deltaPTS)?Math.max(e,t.deltaPTS):e,o=Math.max(n,c),n=Math.min(n,c),i=Math.min(i,t.startDTS),s=Math.min(r,u),r=Math.max(r,u),a=Math.max(a,t.endDTS)}let d=n-t.start;t.start!==0&&(t.start=n),t.duration=r-t.start,t.startPTS=n,t.maxStartPTS=o,t.startDTS=i,t.endPTS=r,t.minEndPTS=s,t.endDTS=a;let f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;let p,m=f-e.startSN,h=e.fragments;for(h[m]=t,p=m;p>0;p--)Zt(h[p],h[p-1]);for(p=m;p<h.length-1;p++)Zt(h[p],h[p+1]);return e.fragmentHint&&Zt(h[h.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function $t(e,t){let n=null,r=e.fragments;for(let e=r.length-1;e>=0;e--){let t=r[e].initSegment;if(t){n=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let i=0,a;if(nn(e,t,(e,r)=>{e.relurl&&(i=e.cc-r.cc),l(e.startPTS)&&l(e.endPTS)&&(r.start=r.startPTS=e.startPTS,r.startDTS=e.startDTS,r.maxStartPTS=e.maxStartPTS,r.endPTS=e.endPTS,r.endDTS=e.endDTS,r.minEndPTS=e.minEndPTS,r.duration=e.endPTS-e.startPTS,r.duration&&(a=r),t.PTSKnown=t.alignedSliding=!0),r.elementaryStreams=e.elementaryStreams,r.loader=e.loader,r.stats=e.stats,r.urlId=e.urlId,e.initSegment&&(r.initSegment=e.initSegment,n=e.initSegment)}),n&&(t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments).forEac
1h(e=>{(!e.initSegment||e.initSegment.relurl===n?.relurl)&&(e.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=t.fragments.some(e=>!e),t.deltaUpdateFailed){y.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=en(e.dateRanges,t.dateRanges,t.recentlyRemovedDateranges))}let o=t.fragments;if(i){y.warn(`discontinuity sliding from playlist, take drift into account`);for(let e=0;e<o.length;e++)o[e].cc+=i}t.skippedSegments&&(t.startCC=t.fragments[0].cc),tn(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),a?Qt(t,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS):rn(e,t),o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let s=t.advancedDateTime;if(t.advanced&&s){let e=t.edge;t.driftStart||=(t.driftStartTime=s,e),t.driftEndTime=s,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime}function en(e,t,n){let r=o({},e);return n&&n.forEach(e=>{delete r[e]}),Object.keys(t).forEach(e=>{let n=new T(t[e].attr,r[e]);n.isValid?r[e]=n:y.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(t[e].attr)}"`)}),r}function tn(e,t,n){if(e&&t){let r=0;for(let i=0,a=e.length;i<=a;i++){let a=e[i],o=t[i+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?n(a,o):r--}}}function nn(e,t,n){let r=t.skippedSegments,i=Math.max(e.startSN,t.startSN)-t.startSN,a=+!!e.fragmentHint+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,s=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,c=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let e=i;e<=a;e++){let i=c[o+e],a=s[e];r&&!a&&e<r&&(a=t.fragments[e]=i),i&&a&&n(i,a)}}function rn(e,t){let n=t.startSN+t.skippedSegments-e.startSN,r=e.fragments;n<0||n>=r.length||an(t,r[n].start)}function an(e,t){if(t){let n=e.fragments;for(let r=e.skippedSegments;r<n.length;r++)n[r].start+=t;e.fragmentHint&&(e.fragmentHint.start+=t)}}function on(e,t=1/0){let n=1e3*e.targetduration;if(e.updated){let r=e.fragments;if(r.length&&n*4>t){let e=r[r.length-1].duration*1e3;e<n&&(n=e)}}else n/=2;return Math.round(n)}function sn(e,t,n){if(!(e!=null&&e.details))return null;let r=e.details,i=r.fragments[t-r.startSN];return i||(i=r.fragmentHint,i&&i.sn===t)?i:t<r.startSN&&n&&n.sn===t?n:null}function cn(e,t,n){return e!=null&&e.details?ln(e.details?.partList,t,n):null}
1function ln(e,t,n){if(e)for(let r=e.length;r--;){let i=e[r];if(i.index===n&&i.fragment.sn===t)return i}return null}function un(e){switch(e.details){case f.FRAG_LOAD_TIMEOUT:case f.KEY_LOAD_TIMEOUT:case f.LEVEL_LOAD_TIMEOUT:case f.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function dn(e,t){let n=un(t);return e.default[`${n?`timeout`:`error`}Retry`]}function fn(e,t){let n=e.backoff===`linear`?1:2**t;return Math.min(n*e.retryDelayMs,e.maxRetryDelayMs)}function pn(e){return i(i({},e),{errorRetry:null,timeoutRetry:null})}function mn(e,t,n,r){return!!e&&t<e.maxNumRetry&&(hn(r)||!!n)}function hn(e){return e===0&&navigator.onLine===!1||!!e&&(e<400||e>499)}var gn={search:function(e,t){let n=0,r=e.length-1,i=null,a=null;for(;n<=r;){i=(n+r)/2|0,a=e[i];let o=t(a);if(o>0)n=i+1;else if(o<0)r=i-1;else return a}return null}};function _n(e,t,n){if(t===null||!Array.isArray(e)||!e.length||!l(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;n||=0;for(let r=0;r<e.length;++r){let i=e[r];if(bn(t,n,i))return i}return null}function vn(e,t,n=0,r=0){let i=null;if(e?i=t[e.sn-t[0].sn+1]||null:n===0&&t[0].start===0&&(i=t[0]),i&&yn(n,r,i)===0)return i;let a=gn.search(t,yn.bind(null,n,r));return a&&(a!==e||!i)?a:i}function yn(e=0,t=0,n){if(n.start<=e&&n.start+n.duration>e)return 0;let r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return n.start+n.duration-r<=e?1:n.start-r>e&&n.start?-1:0}function bn(e,t,n){let r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>e}function xn(e,t){return gn.search(e,e=>e.cc<t?1:e.cc>t?-1:0)}var Sn=3e5,H={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},U={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4},Cn=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=y.log.bind(y,`[info]:`),this.warn=y.warn.bind(y,`[warning]:`),this.error=y.error.bind(y,`[error]:`),this.registerListeners()}registerListeners(){let e=this.hls;e.on(u.ERROR,this.onError,this),e.on(u.MANIFEST_LOADING,this.onManifestLoading,this),e.on(u.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(u.ERROR,this.onError,this),e.off(u.ERROR,this.onErrorOut,this),e.off(u.MANIFEST_LOADING,this.onManifestLoading,this),e.off(u.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){this.playlistError=0}stopLoad(){}getVariantLevelIndex(e){return e?.type===B.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var n;if(t.fatal)return;let r=this.hls,i=t.context;switch(t.details){case f.FRAG_LOAD_ERROR:case f.FRAG_LOAD_TIMEOUT:case f.KEY_LOAD_ERROR:case f.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case f.FRAG_PARSING_ERROR:if((n=t.frag)!=null&&n.gap){t.errorAction={action:H.DoNothing,flags:U.None};return}case f.FRAG_GAP:case f.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=H.SendAlternateToPenaltyBox;return;case f.LEVEL_EMPTY_ERROR:case f.LEVEL_PARSING_ERROR:{var a,o;let e=t.parent===B.MAIN?t.level:r.loadLevel;t.details===f.LEVEL_EMPTY_ERROR&&(a=t.context)!=null&&(o=a.levelDetails)!=null&&o.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case f.LEVEL_LOAD_ERROR:case f.LEVEL_LOAD_TIMEOUT:typeof i?.level==`number`&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level));return;case f.AUDIO_TRACK_LOAD_ERROR:case f.AUDIO_TRACK_LOAD_TIMEOUT:case f.SUBTITLE_LOAD_ERROR:case f.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){let e=r.levels[r.loadLevel];if(e&&(i.type===z.AUDIO_TRACK&&i.groupId===e.audioGroupId||i.type===z.SUBTITLE_TRACK&&i.groupId===e.textGroupId)){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=H.SendAlternateToPenaltyBox,t.errorAction.flags=U.MoveAllAlternatesMatchingHost;return}}return;case f.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{let e=r.levels[r.loadLevel]?.attrs[`HDCP-LEVEL`];e&&(t.errorAction={action:H.SendAlternateToPenaltyBox,flags:U.MoveAllAlternatesMatchingHDCP,hdcpLevel:e})}return;
1case f.BUFFER_ADD_CODEC_ERROR:case f.REMUX_ALLOC_ERROR:t.errorAction=this.getLevelSwitchAction(t,t.level??r.loadLevel);return;case f.INTERNAL_EXCEPTION:case f.BUFFER_APPENDING_ERROR:case f.BUFFER_APPEND_ERROR:case f.BUFFER_FULL_ERROR:case f.LEVEL_SWITCH_ERROR:case f.BUFFER_STALLED_ERROR:case f.BUFFER_SEEK_OVER_HOLE:case f.BUFFER_NUDGE_ON_STALL:t.errorAction={action:H.DoNothing,flags:U.None};return}if(t.type===d.KEY_SYSTEM_ERROR){let e=this.getVariantLevelIndex(t.frag);t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e);return}}getPlaylistRetryOrSwitchAction(e,t){let n=this.hls,r=dn(n.config.playlistLoadPolicy,e),i=this.playlistError++,a=e.response?.code;if(mn(r,i,un(e),a))return{action:H.RetryRequest,flags:U.None,retryConfig:r,retryCount:i};let o=this.getLevelSwitchAction(e,t);return r&&(o.retryConfig=r,o.retryCount=i),o}getFragRetryOrSwitchAction(e){let t=this.hls,n=this.getVariantLevelIndex(e.frag),r=t.levels[n],{fragLoadPolicy:i,keyLoadPolicy:a}=t.config,o=dn(e.details.startsWith(`key`)?a:i,e),s=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(r){e.details!==f.FRAG_GAP&&r.fragmentError++;let t=e.response?.code;if(mn(o,s,un(e),t))return{action:H.RetryRequest,flags:U.None,retryConfig:o,retryCount:s}}let c=this.getLevelSwitchAction(e,n);return o&&(c.retryConfig=o,c.retryCount=s),c}getLevelSwitchAction(e,t){let n=this.hls;t??=n.loadLevel;let r=this.hls.levels[t];if(r&&(r.loadError++,n.autoLevelEnabled)){let t=-1,{levels:i,loadLevel:a,minAutoLevel:o,maxAutoLevel:s}=n,c=e.frag?.type,{type:l,groupId:u}=e.context??{};for(let n=i.length;n--;){let d=(n+a)%i.length;if(d!==a&&d>=o&&d<=s&&i[d].loadError===0){let n=i[d];if(e.details===f.FRAG_GAP&&e.frag){let t=i[d].details;if(t){let n=vn(e.frag,t.fragments,e.frag.start);if(n!=null&&n.gap)continue}}else if(l===z.AUDIO_TRACK&&u===n.audioGroupId||l===z.SUBTITLE_TRACK&&u===n.textGroupId)continue;else if(c===B.AUDIO&&r.audioGroupId===n.audioGroupId||c===B.SUBTITLE&&r.textGroupId===n.textGroupId)continue;t=d;break}}if(t>-1&&n.loadLevel!==t)return e.levelRetry=!0,this.playlistError=0,{action:H.SendAlternateToPenaltyBox,flags:U.None,nextAutoLevel:t}}return{action:H.SendAlternateToPenaltyBox,flags:U.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){switch(t.errorAction?.action){case H.DoNothing:break;case H.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==f.FRAG_GAP&&(t.fatal=!0)}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,n=e.errorAction;if(!n)return;let{flags:r,hdcpLevel:i,nextAutoLevel:a}=n;switch(r){case U.None:this.switchLevel(e,a);break;case U.MoveAllAlternatesMatchingHost:n.resolved||=this.redundantFailover(e);break;case U.MoveAllAlternatesMatchingHDCP:i&&(t.maxHdcpLevel=Kt[Kt.indexOf(i)-1],n.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}n.resolved||this.switchLevel(e,a)}switchLevel(e,t){t!==void 0&&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:n}=this,r=e.parent===B.MAIN?e.level:t.loadLevel,i=t.levels[r],a=i.url.length,o=e.frag?e.frag.urlId:i.urlId;i.urlId===o&&(!e.frag||i.details)&&this.penalizeRendition(i,e);for(let s=1;s<a;s++){let c=(o+s)%a,l=n[c];if(!l||wn(l,e,n[o]))return this.warn(`Switching to Redundant Stream ${c+1}/${a}: "${i.url[c]}" after ${e.details}`),this.playlistError=0,t.levels.forEach(e=>{e.urlId=c}),t.nextLoadLevel=r,!0}return!1}penalizeRendition(e,t){let{penalizedRenditions:n}=this,r=n[e.urlId]||{lastErrorPerfMs:0,errors:[],details:void 0};r.lastErrorPerfMs=performance.now(),r.errors.push(t),r.details=e.details,n[e.urlId]=r}};function wn(e,t,n){if(performance.now()-e.lastErrorPerfMs>Sn)return!0;let r=e.details;if(t.details===f.FRAG_GAP&&r&&t.frag){let e=t.frag.start,n=vn(null,r.fragments,e);if(n&&!n.gap)return!0}if(n&&e.errors.length<n.errors.length){let n=e.errors[e.errors.length-1];if(r&&n.frag&&t.frag&&Math.abs(n.frag.start-t.frag.start)>r.targetduration*3)return!0}return!1}var Tn=class{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=y.log.bind(y,`${t}:`),this.warn=y.warn.bind(y,`${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 n=t?.renditionReports;if(n){let r=-1;for(let i=0;i<n.length;i++){let a=n[i],o;try{o=new self.URL(a.URI,t.url).href}catch(e){y.warn(`Could not construct new URL for Rendition Report: ${e}`),o=a.URI||``}
1if(o===e){r=i;break}o===e.substring(0,o.length)&&(r=i)}if(r!==-1){let e=n[r],i=parseInt(e[`LAST-MSN`])||t?.lastPartSn,a=parseInt(e[`LAST-PART`])||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 Yt(i,a>=0?a:void 0,qt.No)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,n){let{details:r,stats:i}=t,a=self.performance.now(),o=i.loading.first?Math.max(0,a-i.loading.first):0;if(r.advancedDateTime=Date.now()-o,r.live||n!=null&&n.live){if(r.reloaded(n),n&&this.log(`live playlist ${e} ${r.advanced?`REFRESHED `+r.lastPartSn+`-`+r.lastPartIndex:`MISSED`}`),n&&r.fragments.length>0&&$t(n,r),!this.canLoad||!r.live)return;let o,s,c;if(r.canBlockReload&&r.endSN&&r.advanced){let e=this.hls.config.lowLatencyMode,i=r.lastPartSn,a=r.endSN,l=r.lastPartIndex,u=l!==-1,d=i===a,f=e?0:l;u?(s=d?a+1:i,c=d?f:l+1):s=a+1;let p=r.age,m=p+r.ageHeader,h=Math.min(m-r.partTarget,r.targetduration*1.5);if(h>0){if(n&&h>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${h} with playlist age: ${r.age}`),h=0;else{let e=Math.floor(h/r.targetduration);if(s+=e,c!==void 0){let e=Math.round(h%r.targetduration/r.partTarget);c+=e}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${p.toFixed(2)}s goal: ${h} skip sn ${e} to part ${c}`)}r.tuneInGoal=h}if(o=this.getDeliveryDirectives(r,t.deliveryDirectives,s,c),e||!d){this.loadPlaylist(o);return}}else r.canBlockReload&&(o=this.getDeliveryDirectives(r,t.deliveryDirectives,s,c));let l=this.hls.mainForwardBufferInfo,u=l?l.end-l.len:0,d=on(r,(r.edge-u)*1e3);r.updated&&a>this.requestScheduled+d&&(this.requestScheduled=i.loading.start),s!==void 0&&r.canBlockReload?this.requestScheduled=i.loading.first+d-(r.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+d<a?this.requestScheduled=a:this.requestScheduled-a<=0&&(this.requestScheduled+=d);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(o),f)}else this.clearTimer()}getDeliveryDirectives(e,t,n,r){let i=Jt(e,n);return t!=null&&t.skip&&e.deltaUpdateFailed&&(n=t.msn,r=t.part,i=qt.No),new Yt(n,r,i)}checkRetry(e){let t=e.details,n=un(e),r=e.errorAction,{action:i,retryCount:a=0,retryConfig:o}=r||{},s=!!r&&!!o&&(i===H.RetryRequest||!r.resolved&&i===H.SendAlternateToPenaltyBox);if(s){var c;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(n&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let e=fn(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return s}},En,Dn=class extends Tn{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(u.MANIFEST_LOADING,this.onManifestLoading,this),e.on(u.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(u.LEVEL_LOADED,this.onLevelLoaded,this),e.on(u.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(u.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(u.FRAG_LOADED,this.onFragLoaded,this),e.on(u.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(u.MANIFEST_LOADING,this.onManifestLoading,this),e.off(u.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(u.LEVEL_LOADED,this.onLevelLoaded,this),e.off(u.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(u.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(u.FRAG_LOADED,this.onFragLoaded,this),e.off(u.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}
1startLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.startLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let n=[],r={},i;t.levels.forEach(e=>{let t=e.attrs;e.audioCodec?.indexOf(`mp4a.40.34`)!==-1&&(En||=/chrome|firefox/i.test(navigator.userAgent),En&&(e.audioCodec=void 0));let{AUDIO:a,CODECS:o,"FRAME-RATE":s,"PATHWAY-ID":c,RESOLUTION:l,SUBTITLES:u}=t,d=`${`${c||`.`}-`}${e.bitrate}-${l}-${s}-${o}`;i=r[d],i?i.addFallback(e):(i=new Xt(e),r[d]=i,n.push(i)),On(i,`audio`,a),On(i,`text`,u)}),this.filterAndSortMediaOptions(n,t)}filterAndSortMediaOptions(e,t){let n=[],r=[],i=!1,a=!1,o=!1,s=e.filter(({audioCodec:e,videoCodec:t,width:n,height:r,unknownCodecs:s})=>(i||=!!(n&&r),a||=!!t,o||=!!e,!(s!=null&&s.length)&&(!e||ht(e,`audio`))&&(!t||ht(t,`video`))));if((i||a)&&o&&(s=s.filter(({videoCodec:e,width:t,height:n})=>!!e||!!(t&&n))),s.length===0){Promise.resolve().then(()=>{if(this.hls){let e=Error(`no level with compatible codecs found in manifest`);this.hls.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:e,reason:e.message})}});return}t.audioTracks&&(n=t.audioTracks.filter(e=>!e.audioCodec||ht(e.audioCodec,`audio`)),kn(n)),t.subtitles&&(r=t.subtitles,kn(r));let c=s.slice(0);s.sort((e,t)=>e.attrs[`HDCP-LEVEL`]===t.attrs[`HDCP-LEVEL`]?e.bitrate===t.bitrate?e.attrs[`FRAME-RATE`]===t.attrs[`FRAME-RATE`]?e.attrs.SCORE===t.attrs.SCORE?i&&e.height!==t.height?e.height-t.height:0:e.attrs.decimalFloatingPoint(`SCORE`)-t.attrs.decimalFloatingPoint(`SCORE`):e.attrs.decimalFloatingPoint(`FRAME-RATE`)-t.attrs.decimalFloatingPoint(`FRAME-RATE`):e.bitrate-t.bitrate:(e.attrs[`HDCP-LEVEL`]||``)>(t.attrs[`HDCP-LEVEL`]||``)?1:-1);let l=c[0];if(this.steering&&(s=this.steering.filterParsedLevels(s),s.length!==c.length)){for(let e=0;e<c.length;e++)if(c[e].pathwayId===s[0].pathwayId){l=c[e];break}}this._levels=s;for(let e=0;e<s.length;e++)if(s[e]===l){this._firstLevel=e,this.log(`manifest loaded, ${s.length} level(s) found, first bitrate: ${l.bitrate}`);break}let p=o&&!a,m={levels:s,audioTracks:n,subtitleTracks:r,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:o,video:a,altAudio:!p&&n.some(e=>!!e.url)};this.hls.trigger(u.MANIFEST_PARSED,m),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let n=Error(`invalid level idx`),r=e<0;if(this.hls.trigger(u.ERROR,{type:d.OTHER_ERROR,details:f.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:n,reason:n.message}),r)return;e=Math.min(e,t.length-1)}let n=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs[`PATHWAY-ID`]:void 0,a=t[e],s=a.attrs[`PATHWAY-ID`];if(this.currentLevelIndex=e,this.currentLevel=a,n===e&&a.details&&r&&i===s)return;this.log(`Switching to level ${e}${s?` with Pathway `+s:``} from level ${n}${i?` with Pathway `+i:``}`);let c=o({},a,{level:e,maxBitrate:a.maxBitrate,attrs:a.attrs,uri:a.uri,urlId:a.urlId});delete c._attrs,delete c._urlId,this.hls.trigger(u.LEVEL_SWITCHING,c);let l=a.details;if(!l||l.live){let e=this.switchParams(a.uri,r?.details);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e===void 0?this._firstLevel:e}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===z.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragLoaded(e,{frag:t}){if(t!==void 0&&t.type===B.MAIN){let e=this._levels[t.level];e!==void 0&&(e.loadError=0)}}onLevelLoaded(e,t){var n;let{level:r,details:i}=t,a=this._levels[r];if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}r===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(r,t,a.details)):(n=t.deliveryDirectives)!=null&&n.skip&&(i.deltaUpdateFailed=!0)}onAudioTrackSwitched(e,t){let n=this.currentLevel;if(!n)return;let r=this.hls.audioTracks[t.id].groupId;if(n.audioGroupIds&&n.audioGroupId!==r){let e=-1;for(let t=0;t<n.audioGroupIds.length;t++)if(n.audioGroupIds[t]===r){e=t;break}e!==-1&&e!==n.urlId&&(n.urlId=e,this.canLoad&&this.startLoad())}}loadPlaylist(e){super.loadPlaylist();let t=this.currentLevelIndex,n=this.currentLevel;if(n&&this.shouldLoadPlaylist(n)){let r=n.urlId,i=n.uri;if(e)try{i=e.addDirectives(i)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}let a=n.attrs[`PATHWAY-ID`];this.log(`Loading level index ${t}${e?.msn===void 0?``:` at sn `+e.msn+` part `+e.part} with${a?` Pathway `+a:``} URI ${r+1}/${n.url.length} ${i}`),this.clearTimer(),this.hls.trigger(u.LEVEL_LOADING,{url:i,level:t,id:r,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex===-1?this.hls.nextAutoLevel:this.manualLevelIndex}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e,t){let n=(e,n)=>n!==t,r=this._levels.filter((r,i)=>i===e?r.url.length>1&&t!==void 0?(r.url=r.url.filter(n),r.audioGroupIds&&=r.audioGroupIds.filter(n),r.textGroupIds&&=r.textGroupIds.filter(n),r.urlId=0,!0):(this.steering&&this.steering.removeLevel(r),!1):!0);this.hls.trigger(u.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){t.forEach((e,t)=>{let{details:n}=e;
1n!=null&&n.fragments&&n.fragments.forEach(e=>{e.level=t})}),this._levels=t}};function On(e,t,n){n&&(t===`audio`?(e.audioGroupIds||=[],e.audioGroupIds[e.url.length-1]=n):t===`text`&&(e.textGroupIds||=[],e.textGroupIds[e.url.length-1]=n))}function kn(e){let t={};e.forEach(e=>{let n=e.groupId||``;e.id=t[n]=t[n]||0,t[n]++})}var W={NOT_LOADED:`NOT_LOADED`,APPENDING:`APPENDING`,PARTIAL:`PARTIAL`,OK:`OK`},An=class{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(u.BUFFER_APPENDED,this.onBufferAppended,this),e.on(u.FRAG_BUFFERED,this.onFragBuffered,this),e.on(u.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){let{hls:e}=this;e.off(u.BUFFER_APPENDED,this.onBufferAppended,this),e.off(u.FRAG_BUFFERED,this.onFragBuffered,this),e.off(u.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let n=this.activePartLists[t];if(n)for(let t=n.length;t--;){let r=n[t];if(!r)break;let i=r.end;if(r.start<=e&&i!==null&&e<=i)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){let{fragments:n}=this,r=Object.keys(n);for(let i=r.length;i--;){let a=n[r[i]];if(a?.body.type===t&&a.buffered){let t=a.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,n,r){this.timeRanges&&(this.timeRanges[e]=t);let i=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(r=>{let a=this.fragments[r];if(!a||i>=a.body.sn)return;if(!a.buffered&&!a.loaded){a.body.type===n&&this.removeFragment(a.body);return}let o=a.range[e];o&&o.time.some(e=>{let n=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return n&&this.removeFragment(a.body),n})})}detectPartialFragments(e){let t=this.timeRanges,{frag:n,part:r}=e;if(!t||n.sn===`initSegment`)return;let i=Mn(n),a=this.fragments[i];if(!a||a.buffered&&n.gap)return;let o=!n.relurl;Object.keys(t).forEach(e=>{let i=n.elementaryStreams[e];if(!i)return;let s=t[e],c=o||i.partial===!0;a.range[e]=this.getBufferedTimes(n,r,c,s)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,a.body.endList&&(this.endListFragments[a.body.type]=a),jn(a)||this.removeParts(n.sn-1,n.type)):this.removeFragment(a.body)}removeParts(e,t){let n=this.activePartLists[t];n&&(this.activePartLists[t]=n.filter(t=>t.fragment.sn>=e))}fragBuffered(e,t){let n=Mn(e),r=this.fragments[n];!r&&t&&(r=this.fragments[n]={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,n,r){let i={time:[],partial:n},a=e.start,o=e.end,s=e.minEndPTS||o,c=e.maxStartPTS||a;for(let e=0;e<r.length;e++){let t=r.start(e)-this.bufferPadding,n=r.end(e)+this.bufferPadding;if(c>=t&&s<=n){i.time.push({startPTS:Math.max(a,r.start(e)),endPTS:Math.min(o,r.end(e))});break}if(a<n&&o>t)i.partial=!0,i.time.push({startPTS:Math.max(a,r.start(e)),endPTS:Math.min(o,r.end(e))});else if(o<=t)break}return i}getPartialFragment(e){let t=null,n,r,i,a=0,{bufferPadding:o,fragments:s}=this;return Object.keys(s).forEach(c=>{let l=s[c];l&&jn(l)&&(r=l.body.start-o,i=l.body.end+o,e>=r&&e<=i&&(n=Math.min(e-r,i-e),a<=n&&(t=l.body,a=n)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||jn(t))}getState(e){let t=Mn(e),n=this.fragments[t];return n?n.buffered?jn(n)?W.PARTIAL:W.OK:W.APPENDING:W.NOT_LOADED}isTimeBuffered(e,t,n){let r,i;for(let a=0;a<n.length;a++){if(r=n.start(a)-this.bufferPadding,i=n.end(a)+this.bufferPadding,e>=r&&t<=i)return!0;if(t<=r)return!1}return!1}onFragLoaded(e,t){let{frag:n,part:r}=t;if(n.sn===`initSegment`||n.bitrateTest)return;let i=r?null:t,a=Mn(n);this.fragments[a]={body:n,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:n,part:r,timeRanges:i}=t;if(n.sn===`initSegment`)return;let a=n.type;if(r){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(r)}
1this.timeRanges=i,Object.keys(i).forEach(e=>{let t=i[e];this.detectEvictedFragments(e,t,a,r)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=Mn(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,n,r,i){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let s=o.body;s.type!==n||r&&!s.gap||s.start<t&&s.end>e&&(o.buffered||i)&&this.removeFragment(s)})}removeFragment(e){let t=Mn(e);e.stats.loaded=0,e.clearElementaryStreamInfo();let n=this.activePartLists[e.type];if(n){let t=e.sn;this.activePartLists[e.type]=n.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 jn(e){return e.buffered&&(e.body.gap||e.range.video?.partial||e.range.audio?.partial||e.range.audiovideo?.partial)}function Mn(e){return`${e.type}_${e.level}_${e.urlId}_${e.sn}
1`}var Nn=2**17,Pn=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&=(this.loader.destroy(),null)}abort(){this.loader&&this.loader.abort()}load(e,t){let n=e.url;if(!n)return Promise.reject(new G({type:d.NETWORK_ERROR,details:f.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${n?`part list`:`url`}`),networkDetails:null}));this.abort();let r=this.config,a=r.fLoader,o=r.loader;return new Promise((s,c)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>e[0]===`GAP`)){c(In(e));return}e.gap=!1}let l=this.loader=e.loader=a?new a(r):new o(r),u=Fn(e),p=pn(r.fragLoadPolicy.default),m={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn===`initSegment`?1/0:Nn};e.stats=l.stats,l.load(u,m,{onSuccess:(t,n,r,i)=>{this.resetLoader(e,l);let a=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),s({frag:e,part:null,payload:a,networkDetails:i})},onError:(t,r,a,o)=>{this.resetLoader(e,l),c(new G({type:d.NETWORK_ERROR,details:f.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:i({url:n,data:void 0},t),error:Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:a,stats:o}))},onAbort:(t,n,r)=>{this.resetLoader(e,l),c(new G({type:d.NETWORK_ERROR,details:f.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error(`Aborted`),networkDetails:r,stats:t}))},onTimeout:(t,n,r)=>{this.resetLoader(e,l),c(new G({type:d.NETWORK_ERROR,details:f.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${m.timeout}ms`),networkDetails:r,stats:t}))},onProgress:(n,r,i,a)=>{t&&t({frag:e,part:null,payload:i,networkDetails:a})}})})}loadPart(e,t,n){this.abort();let r=this.config,a=r.fLoader,o=r.loader;return new Promise((s,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(In(e,t));return}let l=this.loader=e.loader=a?new a(r):new o(r),u=Fn(e,t),p=pn(r.fragLoadPolicy.default),m={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Nn};t.stats=l.stats,l.load(u,m,{onSuccess:(r,i,a,o)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);let c={frag:e,part:t,payload:r.data,networkDetails:o};n(c),s(c)},onError:(n,r,a,o)=>{this.resetLoader(e,l),c(new G({type:d.NETWORK_ERROR,details:f.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:i({url:u.url,data:void 0},n),error:Error(`HTTP Error ${n.code} ${n.text}`),networkDetails:a,stats:o}))},onAbort:(n,r,i)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new G({type:d.NETWORK_ERROR,details:f.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error(`Aborted`),networkDetails:i,stats:n}))},onTimeout:(n,r,i)=>{this.resetLoader(e,l),c(new G({type:d.NETWORK_ERROR,details:f.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${m.timeout}ms`),networkDetails:i,stats:n}))}})})}updateStatsFromPart(e,t){let n=e.stats,r=t.stats,i=r.total;if(n.loaded+=r.loaded,i){let r=Math.round(e.duration/t.duration),a=Math.min(Math.round(n.loaded/i),r),o=(r-a)*Math.round(n.loaded/a);n.total=n.loaded+o}else n.total=Math.max(n.loaded,n.total);let a=n.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function Fn(e,t=null){let n=t||e,r={frag:e,part:t,responseType:`arraybuffer`,url:n.url,headers:{},rangeStart:0,rangeEnd:0},i=n.byteRangeStartOffset,a=n.byteRangeEndOffset;if(l(i)&&l(a)){let t=i,n=a;if(e.sn===`initSegment`&&e.decryptdata?.method===`AES-128`){let e=a-i;e%16&&(n=a+(16-e%16)),i!==0&&(r.resetIV=!0,t=i-16)}r.rangeStart=t,r.rangeEnd=n}return r}function In(e,t){let n=Error(`GAP ${e.gap?`tag`:`attribute`} found`),r={type:d.MEDIA_ERROR,details:f.FRAG_GAP,fatal:!1,frag:e,error:n,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new G(r)}var G=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Ln=class{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let t in this.keyUriToKeyInfo){let n=this.keyUriToKeyInfo[t].loader;if(n){if(e&&e!==n.context.frag.type)return;n.abort()}}}detach(){for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyUriToKeyInfo){let t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=f.KEY_LOAD_ERROR,n,r,i){return new G({type:d.NETWORK_E
1RROR,details:t,fatal:!1,frag:e,response:i,error:n,networkDetails:r})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){let{sn:n,cc:r}=e;for(let e=0;e<t.length;e++){let i=t[e];if(r<=i.cc&&(n===`initSegment`||i.sn===`initSegment`||n<i.sn)){this.emeController.selectKeySystemFormat(i).then(e=>{i.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 n,r;t&&e.setKeyFormat(t);let i=e.decryptdata;if(!i){let n=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,f.KEY_LOAD_ERROR,n))}let a=i.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,f.KEY_LOAD_ERROR,Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((n=o)!=null&&n.decryptdata.key)return i.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((r=o)!=null&&r.keyLoadPromise)switch(o.mediaKeySessionContext?.keyStatus){case void 0:case`status-pending`:case`usable`:case`usable-in-future`:return o.keyLoadPromise.then(t=>(i.key=t.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}switch(o=this.keyUriToKeyInfo[a]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case`ISO-23001-7`:case`SAMPLE-AES`:case`SAMPLE-AES-CENC`:case`SAMPLE-AES-CTR`:return i.keyFormat===`identity`?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case`AES-128`:return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,f.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e,t){let n={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){let t=this.emeController.loadKey(n);if(t)return(e.keyLoadPromise=t.then(t=>(e.mediaKeySessionContext=t,n))).catch(t=>{throw e.keyLoadPromise=null,t})}return Promise.resolve(n)}loadKeyHTTP(e,t){let n=this.config,r=n.loader,a=new r(n);return t.keyLoader=e.loader=a,e.keyLoadPromise=new Promise((r,o)=>{let s={keyInfo:e,frag:t,responseType:`arraybuffer`,url:e.decryptdata.uri},c=n.keyLoadPolicy.default,l={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};a.load(s,l,{onSuccess:(e,t,n,i)=>{let{frag:a,keyInfo:s,url:c}=n;if(!a.decryptdata||s!==this.keyUriToKeyInfo[c])return o(this.createKeyLoadError(a,f.KEY_LOAD_ERROR,Error(`after key load, decryptdata unset or changed`),i));s.decryptdata.key=a.decryptdata.key=new Uint8Array(e.data),a.keyLoader=null,s.loader=null,r({frag:a,keyInfo:s})},onError:(e,n,r,a)=>{this.resetLoader(n),o(this.createKeyLoadError(t,f.KEY_LOAD_ERROR,Error(`HTTP Error ${e.code} loading key ${e.text}`),r,i({url:s.url,data:void 0},e)))},onTimeout:(e,n,r)=>{this.resetLoader(n),o(this.createKeyLoadError(t,f.KEY_LOAD_TIMEOUT,Error(`key loading timed out`),r))},onAbort:(e,n,r)=>{this.resetLoader(n),o(this.createKeyLoadError(t,f.INTERNAL_ABORTED,Error(`key loading aborted`),r))}})})}resetLoader(e){let{frag:t,keyInfo:n,url:r}=e,i=n.loader;t.keyLoader===i&&(t.keyLoader=null,n.loader=null),delete this.keyUriToKeyInfo[r],i&&i.destroy()}},Rn=class{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):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},zn={length:0,start:()=>0,end:()=>0},K=class e{static isBuffered(t,n){try{if(t){let r=e.getBuffered(t);for(let e=0;e<r.length;e++)if(n>=r.start(e)&&n<=r.end(e))return!0}}catch{}return!1}static bufferInfo(t,n,r){try{if(t){let i=e.getBuffered(t),a=[],o;for(o=0;o<i.length;o++)a.push({start:i.start(o),end:i.end(o)});return this.bufferedInfo(a,n,r)}}catch{}return{len:0,start:n,end:n,nextStart:void 0}}static bufferedInfo(e,t,n){t=Math.max(0,t),e.sort(function(e,t){return e.start-t.start||t.end-e.end});let r=[];if(n)for(let t=0;t<e.length;t++){let i=r.length;if(i){let a=r[i-1].end;e[t].start-a<n?e[t].end>a&&(r[i-1].end=e[t].end):r.push(e[t])}else r.push(e[t])}else r=e;let i=0,a,o=t,s=t;
1for(let e=0;e<r.length;e++){let c=r[e].start,l=r[e].end;if(t+n>=c&&t<l)o=c,s=l,i=s-t;else if(t+n<c){a=c;break}}return{len:i,start:o||0,end:s||0,nextStart:a}}static getBuffered(e){try{return e.buffered}catch(e){return y.log(`failed to get media.buffered`,e),zn}}},Bn=class{constructor(e,t,n,r=0,i=-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=Vn(),this.buffering={audio:Vn(),video:Vn(),audiovideo:Vn()},this.level=e,this.sn=t,this.id=n,this.size=r,this.part=i,this.partial=a}};function Vn(){return{start:0,executeStart:0,executeEnd:0,end:0}}function Hn(e,t){let n=null;for(let r=0,i=e.length;r<i;r++){let i=e[r];if(i&&i.cc===t){n=i;break}}return n}function Un(e,t,n){return!!(t.details&&(n.endCC>n.startCC||e&&e.cc<n.startCC))}function Wn(e,t,n=0){let r=e.fragments,i=t.fragments;if(!i.length||!r.length){y.log(`No fragments to align`);return}let a=Hn(r,i[0].cc);if(!a||a&&!a.startPTS){y.log(`No frag in previous level to align on`);return}return a}function Gn(e,t){if(e){let n=e.start+t;e.start=e.startPTS=n,e.endPTS=n+e.duration}}function Kn(e,t){let n=t.fragments;for(let t=0,r=n.length;t<r;t++)Gn(n[t],e);t.fragmentHint&&Gn(t.fragmentHint,e),t.alignedSliding=!0}function qn(e,t,n){t&&(Jn(e,n,t),!n.alignedSliding&&t.details&&Yn(n,t.details),!n.alignedSliding&&t.details&&!n.skippedSegments&&rn(t.details,n))}function Jn(e,t,n){if(Un(e,n,t)){let e=Wn(n.details,t);e&&l(e.start)&&(y.log(`Adjusting PTS using last level due to CC increase within current level ${t.url}`),Kn(e.start,t))}}function Yn(e,t){if(!t.fragments.length||!e.hasProgramDateTime||!t.hasProgramDateTime)return;let n=t.fragments[0].programDateTime,r=e.fragments[0].programDateTime,i=(r-n)/1e3+t.fragments[0].start;i&&l(i)&&(y.log(`Adjusting PTS using programDateTime delta ${r-n}ms, sliding:${i.toFixed(3)} ${e.url} `),Kn(i,e))}function Xn(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;let n=e.fragments,r=t.fragments;if(!n.length||!r.length)return;let i=r[Math.round(r.length/2)-1],a=Hn(n,i.cc)||n[Math.round(n.length/2)-1],o=i.programDateTime,s=a.programDateTime;o!==null&&s!==null&&Kn((s-o)/1e3-(a.start-i.start),e)}var Zn=class{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:`AES-CBC`,iv:this.aesIV},t,e)}},Qn=class{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`])}};function $n(e){let t=e.byteLength,n=t&&new DataView(e.buffer).getUint8(t-1);return n?he(e,0,t-n):e}var er=class{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,this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),n=new Uint32Array(4);for(let e=0;e<4;e++)n[e]=t.getUint32(e*4);return n}initTable(){let e=this.sBox,t=this.invSBox,n=this.subMix,r=n[0],i=n[1],a=n[2],o=n[3],s=this.invSubMix,c=s[0],l=s[1],u=s[2],d=s[3],f=new Uint32Array(256),p=0,m=0,h=0;for(h=0;h<256;h++)h<128?f[h]=h<<1:f[h]=h<<1^283;for(h=0;h<256;h++){let n=m^m<<1^m<<2^m<<3^m<<4;n=n>>>8^n&255^99,e[p]=n,t[n]=p;let s=f[p],h=f[s],g=f[h],_=f[n]*257^n*16843008;r[p]=_<<24|_>>>8,i[p]=_<<16|_>>>16,a[p]=_<<8|_>>>24,o[p]=_,_=g*16843009^h*65537^s*257^p*16843008,c[n]=_<<24|_>>>8,l[n]=_<<16|_>>>16,u[n]=_<<8|_>>>24,d[n]=_,p?(p=s^f[f[f[g^s]]],m^=f[f[m]]):p=m=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),n=!0,r=0;for(;r<t.length&&n;)n=t[r]===this.key[r],r++;if(n)return;this.key=t;let i=this.keySize=t.length;if(i!==4&&i!==6&&i!==8)throw Error(`Invalid aes key size=`+i);let a=this.ksRows=(i+6+1)*4,o,s,c=this.keySchedule=new Uint32Array(a),l=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,p=f[0],m=f[1],h=f[2],g=f[3],_,v;for(o=0;o<a;
1o++){if(o<i){_=c[o]=t[o];continue}v=_,o%i===0?(v=v<<8|v>>>24,v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255],v^=d[o/i|0]<<24):i>6&&o%i===4&&(v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255]),c[o]=_=(c[o-i]^v)>>>0}for(s=0;s<a;s++)o=a-s,v=s&3?c[o]:c[o-4],s<4||o<=4?l[s]=v:l[s]=p[u[v>>>24]]^m[u[v>>>16&255]]^h[u[v>>>8&255]]^g[u[v&255]],l[s]=l[s]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,n){let r=this.keySize+6,i=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,s=o[0],c=o[1],l=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(n),f=d[0],p=d[1],m=d[2],h=d[3],g=new Int32Array(e),_=new Int32Array(g.length),v,y,b,x,S,C,w,T,E,D,O,ee,k,te,A=this.networkToHostOrderSwap;for(;t<g.length;){for(E=A(g[t]),D=A(g[t+1]),O=A(g[t+2]),ee=A(g[t+3]),S=E^i[0],C=ee^i[1],w=O^i[2],T=D^i[3],k=4,te=1;te<r;te++)v=s[S>>>24]^c[C>>16&255]^l[w>>8&255]^u[T&255]^i[k],y=s[C>>>24]^c[w>>16&255]^l[T>>8&255]^u[S&255]^i[k+1],b=s[w>>>24]^c[T>>16&255]^l[S>>8&255]^u[C&255]^i[k+2],x=s[T>>>24]^c[S>>16&255]^l[C>>8&255]^u[w&255]^i[k+3],S=v,C=y,w=b,T=x,k+=4;v=a[S>>>24]<<24^a[C>>16&255]<<16^a[w>>8&255]<<8^a[T&255]^i[k],y=a[C>>>24]<<24^a[w>>16&255]<<16^a[T>>8&255]<<8^a[S&255]^i[k+1],b=a[w>>>24]<<24^a[T>>16&255]<<16^a[S>>8&255]<<8^a[C&255]^i[k+2],x=a[T>>>24]<<24^a[S>>16&255]<<16^a[C>>8&255]<<8^a[w&255]^i[k+3],_[t]=A(v^f),_[t+1]=A(x^p),_[t+2]=A(b^m),_[t+3]=A(y^h),f=E,p=D,m=O,h=ee,t+=4}return _.buffer}},tr=16,nr=class{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{}this.subtle===null&&(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 n=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?$n(n):n}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&=null}decrypt(e,t,n){return this.useSoftware?new Promise((r,i)=>{this.softwareDecrypt(new Uint8Array(e),t,n);let a=this.flush();a?r(a.buffer):i(Error(`[softwareDecrypt] Failed to decrypt data`))}):this.webCryptoDecrypt(new Uint8Array(e),t,n)}softwareDecrypt(e,t,n){let{currentIV:r,currentResult:i,remainderData:a}=this;this.logOnce(`JS AES decrypt`),a&&(e=qe(a,e),this.remainderData=null);let o=this.getValidChunk(e);if(!o.length)return null;r&&(n=r);let s=this.softwareDecrypter;s||=this.softwareDecrypter=new er,s.expandKey(t);let c=i;return this.currentResult=s.decrypt(o.buffer,0,n),this.currentIV=he(o,-16).buffer,c||null}webCryptoDecrypt(e,t,n){let r=this.subtle;return(this.key!==t||!this.fastAesKey)&&(this.key=t,this.fastAesKey=new Qn(r,t)),this.fastAesKey.expandKey().then(t=>r?(this.logOnce(`WebCrypto AES decrypt`),new Zn(r,new Uint8Array(n)).decrypt(e.buffer,t)):Promise.reject(Error(`web crypto not initialized`))).catch(r=>(y.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,n)))}onWebCryptoError(e,t,n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,n);let r=this.flush();if(r)return r.buffer;throw Error(`WebCrypto and softwareDecrypt: failed to decrypt data`)}getValidChunk(e){let t=e,n=e.length-e.length%tr;return n!==e.length&&(t=he(e,0,n),this.remainderData=he(e,n)),t}logOnce(e){this.logEnabled&&=(y.log(`[decrypter]: ${e}`),!1)}},rr={toString:function(e){let t=``,n=e.length;for(let r=0;r<n;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t}},q={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`},ir=class extends Rn{constructor(e,t,n,r,i){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=q.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=i,this.logPrefix=r,this.log=y.log.bind(y,`${r}:`),this.warn=y.warn.bind(y,`${r}:`),this.hls=e,this.fragmentLoader=new Pn(e.config),this.keyLoader=n,this.fragmentTracker=t,this.config=e.config,this.decrypter=new nr(e.config),e.on(u.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=q.STOPPED}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;let n=t.partList;if(n!=null&&n.length){let e=n[n.length-1];return K.isBuffered(this.media,e.start+e.duration/2)}let r=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(r)}
1getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levels[this.levelLastLoaded]?.details}onMediaAttached(e,t){let n=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),n.addEventListener(`seeking`,this.onvseeking),n.addEventListener(`ended`,this.onvended);let r=this.config;this.levels&&r.autoStartLoad&&this.state===q.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(){let e=this.media;e!=null&&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:n,mediaBuffer:r,state:i}=this,a=n?n.currentTime:0,o=K.bufferInfo(r||n,a,e.maxBufferHole);if(this.log(`media seeking to ${l(a)?a.toFixed(3):a}, state: ${i}`),this.state===q.ENDED)this.resetLoadingState();else if(t){let n=e.maxFragLookUpTolerance,r=t.start-n,i=t.start+t.duration+n;if(!o.len||i<o.start||r>o.end){let e=a>i;(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)}}n&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.stopLoad(),super.onHandlerDestroying()}onHandlerDestroyed(){this.state=q.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,n){this._loadFragForPlayback(e,t,n)}_loadFragForPlayback(e,t,n){this._doFragLoad(e,t,n,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)}).then(t=>{if(!t)return;let n=this.state;if(this.fragContextChanged(e)){(n===q.FRAG_LOADING||!this.fragCurrent&&n===q.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=q.IDLE);return}`payload`in t&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(u.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t)}).catch(t=>{this.state!==q.STOPPED&&this.state!==q.ERROR&&(this.warn(t),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){let{fragmentTracker:t}=this;if(t.getState(e)===W.APPENDING){let n=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,n),i=Math.max(e.duration,r?r.len:this.config.maxBufferLength);this.reduceMaxBufferLength(i)&&t.removeFragment(e)}else this.mediaBuffer?.buffered.length===0?t.removeAllFragments():t.hasParts(e.type)&&(t.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),t.getState(e)===W.PARTIAL&&t.removeFragment(e))}flushMainBuffer(e,t,n=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:n};this.hls.trigger(u.BUFFER_FLUSHING,r)}_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:n}=this,{payload:r}=t,i=e.decryptdata;if(r&&r.byteLength>0&&i&&i.key&&i.iv&&i.method===`AES-128`){let a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer).catch(t=>{throw n.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e}),t}).then(r=>{let i=self.performance.now();return n.trigger(u.FRAG_DECRYPTED,{frag:e,payload:r,stats:{tstart:a,tdecrypt:i}}),t.payload=r,t})}return t}).then(n=>{let{fragCurrent:r,hls:i,levels:a}=this;if(!a)throw Error(`init load aborted, missing levels`);let o=e.stats;this.state=q.IDLE,t.fragmentError=0,e.data=new Uint8Array(n.payload),o.parsing.start=o.buffering.start=self.performance.now(),o.parsing.end=o.buffering.end=self.performance.now(),n.frag===r&&i.trigger(u.FRAG_BUFFERED,{stats:o,frag:r,part:null,id:e.type}),this.tick()}).catch(t=>{this.state!==q.STOPPED&&this.state!==q.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){let n=this.mediaBuffer?this.mediaBuffer:this.media;this.log(`Buffered ${e.type} sn: ${e.sn}${t?` part: `+t.index:``} of ${this.playlistType===B.MAIN?`level`:`track`} ${e.level} (frag:[${(e.startPTS??NaN).toFixed(3)}-${(e.endPTS??NaN).toFixed(3)}] > buffer:${n?rr.toString(K.getBuffered(n)):`(detached)`})`),this.state=q.IDLE,n&&(!this.loadedmetadata&&e.type==B.MAIN&&n.buffered.length&&this.fragCurrent?.sn===this.fragPrevious?.sn&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:n,part:r,partsLoaded:i}=e,a=!i||i.length===0||i.some(e=>!e),o=new Bn(n.level,n.sn,n.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,n=null,r){var i;let a=t?.details;if(!this.levels||!a)throw Error(`frag load aborted, missing level${a?``:` detail`}s`);let o=null;if(e.encrypted&&!((i=e.decryptdata)!=null&&i.key)?(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix===`[stream-controller]`?`level`:`track`} ${e.level}`),this.state=q.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(u.KEY_LOADED,e),this.state===q.KEY_LOADING&&(this.state=q.IDLE),e}),this.hls.trigger(u.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(Error(`frag load aborted, context changed in KEY_LOADING`)))):!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments),n=Math.max(e.start,n||0),this.config.lowLatencyMode&&e.sn!==`initSegment`){let i=a.partList;if(i&&r){n>e.end&&a.fragmentHint&&(e=a.fragmentHint);let s=this.getNextPart(i,e,n);if(s>-1){let c=i[s];this.log(`Loading part sn: ${e.sn} p: ${c.index} cc: ${e.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${s}-${i.length-1}] ${this.logPrefix===`[stream-controller]`?`level`:`track`}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=c.start+c.duration,this.state=q.FRAG_LOADING;let l;return l=o?o.then(n=>!n||this.fragContextChanged(n.frag)?null:this.doFragPartsLoad(e,c,t,r)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,c,t,r).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(u.FRAG_LOADING,{frag:e,part:c,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(Error(`frag load aborted, context changed in FRAG_LOADING parts`)):l}if(!e.url||this.loadedEndOfParts(i,n))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${a?`of [`+a.startSN+`-`+a.endSN+`] `:``}${this.logPrefix===`[stream-controller]`?`level`:`track`}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),l(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=q.FRAG_LOADING;let s=this.config.progressive,c;return c=s&&o?o.then(t=>!t||this.fragContextChanged(t?.frag)?null:this.fragmentLoader.load(e,r)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,s?r:void 0),o]).then(([e])=>(!s&&e&&r&&r(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(u.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(Error(`frag load aborted, context changed in FRAG_LOADING`)):c}doFragPartsLoad(e,t,n,r){return new Promise((i,a)=>{let o=[],s=n.details?.partList,c=t=>{this.fragmentLoader.loadPart(e,t,r).then(r=>{o[t.index]=r;let a=r.part;this.hls.trigger(u.FRAG_LOADED,r);let l=cn(n,e.sn,t.index+1)||ln(s,e.sn,t.index+1);if(l)c(l);else return i({frag:e,part:a,partsLoaded:o})}).catch(a)};c(t)})}handleFragLoadError(e){if(`data`in e){let t=e.data;e.data&&t.details===f.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(u.ERROR,t)}else this.hls.trigger(u.ERROR,{type:d.OTHER_ERROR,details:f.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==q.PARSING){!this.fragCurrent&&this.state!==q.STOPPED&&this.state!==q.ERROR&&(this.state=q.IDLE);return}let{frag:n,part:r,level:i}=t,a=self.performance.now();n.stats.parsing.end=a,r&&(r.stats.parsing.end=a),this.updateLevelTiming(n,r,i,e.partial)}getCurrentContext(e){let{levels:t,fragCurrent:n}=this,{level:r,sn:i,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${i} of level ${r}. The current chunk will not be buffered.`),null;let o=t[r],s=a>-1?cn(o,i,a):null,c=s?s.fragment:sn(o,i,n);return c?(n&&n!==c&&(c.stats=n.stats),{frag:c,part:s,level:o}):null}bufferFragmentData(e,t,n,r,i){var a;if(!e||this.state!==q.PARSING)return;let{data1:o,data2:s}=e,c=o;if(o&&s&&(c=qe(o,s)),!((a=c)!=null&&a.length))return;let l={type:e.type,frag:t,part:n,chunkMeta:r,parent:t.type,data:c};if(this.hls.trigger(u.BUFFER_APPENDING,l),e.dropped&&e.independent&&!n){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!K.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let n=t.currentTime,r=K.bufferInfo(t,n,0),i=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(e.start-a,r.end-a),n+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){let n=this.getLoadPosition();return l(n)?this.getFwdBufferInfoAtPos(e,n,t):null}getFwdBufferInfoAtPos(e,t,n){let{config:{maxBufferHole:r}}=this,i=K.bufferInfo(e,t,r);if(i.len===0&&i.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,n);if(a&&i.nextStart<a.end)return K.bufferInfo(e,t,Math.max(i.nextStart,r))}return i}
1getMaxBufferLength(e){let{config:t}=this,n;return n=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(n,t.maxMaxBufferLength)}reduceMaxBufferLength(e){let t=this.config,n=e||t.maxBufferLength;return t.maxMaxBufferLength>=n&&(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0)}getAppendedFrag(e,t=B.MAIN){let n=this.fragmentTracker.getAppendedFrag(e,B.MAIN);return n&&`fragment`in n?n.fragment:n}getNextFragment(e,t){let n=t.fragments,r=n.length;if(!r)return null;let{config:i}=this,a=n[0].start,o;if(t.live){let a=i.initialLiveManifestSize;if(r<a)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${a})`),null;!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1&&(o=this.getInitialLiveFragment(t,n),this.startPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=a&&(o=n[0]);if(!o){let n=i.lowLatencyMode?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,n,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){let n=this.fragmentTracker.getState(e);return(n===W.OK||n===W.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,n,r,i){let a=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(o===null)return o;if(e=o,a&&e&&!e.gap&&n.nextStart){let t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,r);if(t!==null&&n.len+t.len>=i)return this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,n){let r=-1,i=!1,a=!0;for(let o=0,s=e.length;o<s;o++){let s=e[o];if(a&&=!s.independent,r>-1&&n<s.start)break;let c=s.loaded;c?r=-1:(i||s.independent||a)&&s.fragment===t&&(r=o),i=c}return r}loadedEndOfParts(e,t){let n=e[e.length-1];return n&&t>n.start&&n.loaded}getInitialLiveFragment(e,t){let n=this.fragPrevious,r=null;if(n){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`),r=_n(t,n.endProgramDateTime,this.config.maxFragLookUpTolerance)),!r){let i=n.sn+1;if(i>=e.startSN&&i<=e.endSN){let a=t[i-e.startSN];n.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=xn(t,n.cc),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{let t=this.hls.liveSyncPosition;t!==null&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,n){let{config:r}=this,{fragPrevious:i}=this,{fragments:a,endSN:o}=n,{fragmentHint:s}=n,c=r.maxFragLookUpTolerance,l=n.partList,u=!!(r.lowLatencyMode&&l!=null&&l.length&&s);u&&s&&!this.bitrateTest&&(a=a.concat(s),o=s.sn);let d;if(e<t){let n=e>t-c?0:c;d=vn(i,a,e,n)}else d=a[a.length-1];if(d){let e=d.sn-n.startSN,t=this.fragmentTracker.getState(d);if((t===W.OK||t===W.PARTIAL&&d.gap)&&(i=d),i&&d.sn===i.sn&&(!u||l[0].fragment.sn>d.sn)&&i&&d.level===i.level){let t=a[e+1];d=d.sn<o&&this.fragmentTracker.getState(t)!==W.OK?t:null}}return d}synchronizeToLiveEdge(e){let{config:t,media:n}=this;if(!n)return;let r=this.hls.liveSyncPosition,i=n.currentTime,a=e.fragments[0].start,o=e.edge,s=i>=a-t.maxFragLookUpTolerance&&i<=o;if(r!==null&&n.duration>r&&(i<r||!s)){let a=t.liveMaxLatencyDuration===void 0?t.liveMaxLatencyDurationCount*e.targetduration:t.liveMaxLatencyDuration;(!s&&n.readyState<4||i<o-a)&&(this.loadedmetadata||(this.nextLoadPosition=r),n.readyState&&(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),n.currentTime=r))}}alignPlaylists(e,t){let{levels:n,levelLastLoaded:r,fragPrevious:i}=this,a=r===null?null:n[r],o=e.fragments.length;if(!o)return this.warn(`No fragments in live playlist`),0;let s=e.fragments[0].start,c=!t,u=e.alignedSliding&&l(s);if(c||!u&&!s){qn(i,a,e);let n=e.fragments[0].start;return this.log(`Live playlist sliding: ${n.toFixed(2)} start-sn: ${t?t.startSN:`na`}->${e.startSN} prev-sn: ${i?i.sn:`na`} fragments: ${o}`),n}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let n=this.startPosition;if(n<t&&(n=-1),n===-1||this.lastCurrentTime===-1){let r=this.startTimeOffset!==null,i=r?this.startTimeOffset:e.startTimeOffset;i!==null&&l(i)?(n=t+i,i<0&&(n+=e.totalduration),n=Math.min(Math.max(t,n),t+e.totalduration),this.log(`Start time offset ${i} found in ${r?`multivariant`:`media`} playlist, adjust startPosition to ${n}`),this.startPosition=n):e.live?n=this.hls.liveSyncPosition||t:this.startPosition=n=0,this.lastCurrentTime=n}this.nextLoadPosition=n}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&&e.sn!==`initSegment`&&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!==q.FRAG_LOADING_WAITING_RETRY)&&(this.state=q.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}let n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){this.warn(`Frag load error must match current frag to retry ${n.url} > ${this.fragCurrent?.url}`);return}let r=t.details===f.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(n,!0);let i=t.errorAction,{action:a,retryCount:o=0,retryConfig:s}=i||{};if(i&&a===H.RetryRequest&&s){this.resetStartWhenNotLoaded(this.levelLastLoaded??n.level);let r=fn(s,o);this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${o+1}/${s.maxNumRetry} in ${r}ms`),i.resolved=!0,this.retryDate=self.performance.now()+r,this.state=q.FRAG_LOADING_WAITING_RETRY}else s&&i?(this.resetFragmentErrors(e),o<s.maxNumRetry?r||(i.resolved=!0):y.warn(`${t.details} reached or exceeded max retry (${o})`)):this.state=i?.action===H.SendAlternateToPenaltyBox?q.WAITING_LEVEL:q.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===q.PARSING||this.state===q.PARSED){let t=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,t),r=n&&n.len>.5;r&&this.reduceMaxBufferLength(n.len);let i=!r;return i&&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(),i}return!1}resetFragmentErrors(e){e===B.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==q.STOPPED&&(this.state=q.IDLE)}afterBufferFlushed(e,t,n){if(!e)return;let r=K.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,n),this.state===q.ENDED&&this.resetLoadingState()}
1resetLoadingState(){this.log(`Reset loading state`),this.fragCurrent=null,this.fragPrevious=null,this.state=q.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;let t=this.levels?this.levels[e].details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){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(this.levelLastLoaded??e.level),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,n,r){let i=n.details;if(!i){this.warn(`level.details undefined`);return}if(Object.keys(e.elementaryStreams).reduce((t,a)=>{let o=e.elementaryStreams[a];if(o){let s=o.endPTS-o.startPTS;if(s<=0)return this.warn(`Could not parse fragment ${e.sn} ${a} duration reliably (${s})`),t||!1;let c=r?0:Qt(i,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return this.hls.trigger(u.LEVEL_PTS_UPDATED,{details:i,level:n,drift:c,type:a,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1))n.fragmentError=0;else if(this.transmuxer?.error===null){let t=Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(n.fragmentError===0&&(n.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(t.message),this.hls.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of level "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=q.PARSED,this.hls.trigger(u.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&=(this.transmuxer.destroy(),null)}recoverWorkerError(e){e.event===`demuxerWorker`&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded??this.fragCurrent?.level??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 ar(){return self.SourceBuffer||self.WebKitSourceBuffer}function or(){let e=dt();if(!e)return!1;let t=ar(),n=e&&typeof e.isTypeSupported==`function`&&e.isTypeSupported(`video/mp4; codecs="avc1.42E01E,mp4a.40.2"`),r=!t||t.prototype&&typeof t.prototype.appendBuffer==`function`&&typeof t.prototype.remove==`function`;return!!n&&!!r}function sr(){return typeof ar()?.prototype?.changeType==`function`}function cr(){return typeof __HLS_WORKER_BUNDLE__==`function`}function lr(){let e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:`text/javascript`}),t=self.URL.createObjectURL(e);return{worker:new self.Worker(t),objectURL:t}}function ur(e){let t=new self.URL(e,self.location.href).href;return{worker:new self.Worker(t),scriptURL:t}}function J(e=``,t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var dr=class{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,n,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,n){}demux(e,t){this.cachedData&&=(e=qe(this.cachedData,e),null);let n=ve(e,0),r=n?n.length:0,i,a=this._audioTrack,o=this._id3Track,s=n?xe(n):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&l(s))&&(this.basePTS=fr(s,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),n&&n.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:V.audioId3,duration:1/0});r<c;){if(this.canParse(e,r)){let t=this.appendFrame(a,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,i=r):r=c}else be(e,r)?(n=ve(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:V.audioId3,duration:1/0}),r+=n.length,i=r):r++;if(r===c&&i!==c){let t=he(e,i);this.cachedData=this.cachedData?qe(this.cachedData,t):t}}return{audioTrack:a,videoTrack:J(),id3Track:o,textTrack:J()}}
1demuxSampleAes(e,t,n){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:J(),id3Track:this._id3Track,textTrack:J()}}destroy(){}},fr=(e,t,n)=>{if(l(e))return e*90;let r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r};function pr(e,t,n,r){let i,a,o,s,c=navigator.userAgent.toLowerCase(),l=r,p=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=((t[n+2]&192)>>>6)+1;let m=(t[n+2]&60)>>>2;if(m>p.length-1){e.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!0,reason:`invalid ADTS sampling index:${m}`});return}return o=(t[n+2]&1)<<2,o|=(t[n+3]&192)>>>6,y.log(`manifest codec:${r}, ADTS type:${i}, samplingIndex:${m}`),/firefox/i.test(c)?m>=6?(i=5,s=[,,,,],a=m-3):(i=2,s=[,,],a=m):c.indexOf(`android`)===-1?(i=5,s=[,,,,],r&&(r.indexOf(`mp4a.40.29`)!==-1||r.indexOf(`mp4a.40.5`)!==-1)||!r&&m>=6?a=m-3:((r&&r.indexOf(`mp4a.40.2`)!==-1&&(m>=6&&o===1||/vivaldi/i.test(c))||!r&&o===1)&&(i=2,s=[,,]),a=m)):(i=2,s=[,,],a=m),s[0]=i<<3,s[0]|=(m&14)>>1,s[1]|=(m&1)<<7,s[1]|=o<<3,i===5&&(s[1]|=(a&14)>>1,s[2]=(a&1)<<7,s[2]|=8,s[3]=0),{config:s,samplerate:p[m],channelCount:o,codec:`mp4a.40.`+i,manifestCodec:l}}function mr(e,t){return e[t]===255&&(e[t+1]&246)==240}function hr(e,t){return e[t+1]&1?7:9}function gr(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function _r(e,t){return t+5<e.length}function vr(e,t){return t+1<e.length&&mr(e,t)}function yr(e,t){return _r(e,t)&&mr(e,t)&&gr(e,t)<=e.length-t}function br(e,t){if(vr(e,t)){let n=hr(e,t);if(t+n>=e.length)return!1;let r=gr(e,t);if(r<=n)return!1;let i=t+r;return i===e.length||vr(e,i)}return!1}function xr(e,t,n,r,i){if(!e.samplerate){let a=pr(t,n,r,i);if(!a)return;e.config=a.config,e.samplerate=a.samplerate,e.channelCount=a.channelCount,e.codec=a.codec,e.manifestCodec=a.manifestCodec,y.log(`parsed codec:${e.codec}, rate:${a.samplerate}, channels:${a.channelCount}`)}}function Sr(e){return 9216e4/e}function Cr(e,t){let n=hr(e,t);if(t+n<=e.length){let r=gr(e,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function wr(e,t,n,r,i){let a=r+i*Sr(e.samplerate),o=Cr(t,n),s;if(o){let{frameLength:r,headerLength:i}=o,c=i+r,l=Math.max(0,n+c-t.length);l?(s=new Uint8Array(c-i),s.set(t.subarray(n+i,t.length),0)):s=t.subarray(n+i,n+c);let u={unit:s,pts:a};return l||e.samples.push(u),{sample:u,length:c,missing:l}}let c=t.length-n;return s=new Uint8Array(c),s.set(t.subarray(n,t.length),0),{sample:{unit:s,pts:a},length:c,missing:-1}}var Tr=class extends dr{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,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=(ve(e,0)||[]).length;for(let n=e.length;t<n;t++)if(br(e,t))return y.log(`ADTS sync word found !`),!0;return!1}canParse(e,t){return yr(e,t)}appendFrame(e,t,n){xr(e,this.observer,t,n,e.manifestCodec);let r=wr(e,t,n,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}},Er=/\/emsg[-/]ID3/i,Dr=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,n,r){let i=this.videoTrack=J(`video`,1),a=this.audioTrack=J(`audio`,1),o=this.txtTrack=J(`text`,1);if(this.id3Track=J(`id3`,1),this.timeOffset=0,!(e!=null&&e.byteLength))return;let s=ze(e);if(s.video){let{id:e,timescale:t,codec:n}=s.video;i.id=e,i.timescale=o.timescale=t,i.codec=n}if(s.audio){let{id:e,timescale:t,codec:n}=s.audio;a.id=e,a.timescale=t,a.codec=n}o.id=Pe.text,i.sampleDuration=0,i.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return e=e.length>16384?e.subarray(0,16384):e,L(e,[`moof`]).length>0}demux(e,t){this.timeOffset=t;let n=e,r=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(n=qe(this.remainderData,e));let t=Ke(n);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=n;let a=this.extractID3Track(r,t);return i.samples=Je(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,n=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return n.samples=Je(e,t),{videoTrack:t,audioTrack:J(),id3Track:r,textTrack:J()}}extractID3Track(e,t){let n=this.id3Track;if(e.samples.length){let r=L(e.samples,[`emsg`]);
1r&&r.forEach(e=>{let r=$e(e);if(Er.test(r.schemeIdUri)){let e=l(r.presentationTime)?r.presentationTime/r.timeScale:t+r.presentationTimeDelta/r.timeScale,i=r.eventDuration===4294967295?1/0:r.eventDuration/r.timeScale;i<=.001&&(i=1/0);let a=r.payload;n.samples.push({data:a,len:a.byteLength,dts:e,pts:e,type:V.emsg,duration:i})}})}return n}demuxSampleAes(e,t,n){return Promise.reject(Error(`The MP4 demuxer does not support SAMPLE-AES decryption`))}destroy(){}},Or=null,kr=[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],Ar=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],jr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Mr=[0,1,1,4];function Nr(e,t,n,r,i){if(n+24>t.length)return;let a=Pr(t,n);if(a&&n+a.frameLength<=t.length){let o=r+i*(a.samplesPerFrame*9e4/a.sampleRate),s={unit:t.subarray(n,n+a.frameLength),pts:o,dts:o};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(s),{sample:s,length:a.frameLength,missing:0}}}function Pr(e,t){let n=e[t+1]>>3&3,r=e[t+1]>>1&3,i=e[t+2]>>4&15,a=e[t+2]>>2&3;if(n!==1&&i!==0&&i!==15&&a!==3){let o=e[t+2]>>1&1,s=e[t+3]>>6,c=kr[(n===3?3-r:r===3?3:4)*14+i-1]*1e3,l=Ar[(n===3?0:n===2?1:2)*3+a],u=s===3?1:2,d=jr[n][r],f=Mr[r],p=d*8*f,m=Math.floor(d*c/l+o)*f;if(Or===null){let e=(navigator.userAgent||``).match(/Chrome\/(\d+)/i);Or=e?parseInt(e[1]):0}return Or&&Or<=87&&r===2&&c>=224e3&&s===0&&(e[t+3]=e[t+3]|128),{sampleRate:l,channelCount:u,frameLength:m,samplesPerFrame:p}}}function Fr(e,t){return e[t]===255&&(e[t+1]&224)==224&&!!(e[t+1]&6)}function Ir(e,t){return t+1<e.length&&Fr(e,t)}function Lr(e,t){return Fr(e,t)&&4<=e.length-t}function Rr(e,t){if(t+1<e.length&&Fr(e,t)){let n=Pr(e,t),r=4;n!=null&&n.frameLength&&(r=n.frameLength);let i=t+r;return i===e.length||Ir(e,i)}return!1}var zr=class{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,n=e.byteLength-t,r=new Uint8Array(4),i=Math.min(4,t);if(i===0)throw Error(`no bytes available`);r.set(e.subarray(n,n+i)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+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),n=this.word>>>32-t;if(e>32&&y.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,t>0&&this.bitsAvailable?n<<t|this.readBits(t):n}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)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 this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t=8,n=8,r;for(let i=0;i<e;i++)n!==0&&(r=this.readEG(),n=(t+r+256)%256),t=n===0?t:n}readSPS(){let e=0,t=0,n=0,r=0,i,a,o,s=this.readUByte.bind(this),c=this.readBits.bind(this),l=this.readUEG.bind(this),u=this.readBoolean.bind(this),d=this.skipBits.bind(this),f=this.skipEG.bind(this),p=this.skipUEG.bind(this),m=this.skipScalingList.bind(this);s();let h=s();if(c(5),d(3),s(),p(),h===100||h===110||h===122||h===244||h===44||h===83||h===86||h===118||h===128){let e=l();if(e===3&&d(1),p(),p(),d(1),u())for(a=e===3?12:8,o=0;o<a;o++)u()&&m(o<6?16:64)}p();let g=l();if(g===0)l();else if(g===1)for(d(1),f(),f(),i=l(),o=0;o<i;o++)f();p(),d(1);let _=l(),v=l(),y=c(1);y===0&&d(1),d(1),u()&&(e=l(),t=l(),n=l(),r=l());let b=[1,1];if(u()&&u())switch(s()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;
1case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[s()<<8|s(),s()<<8|s()]}return{width:Math.ceil((_+1)*16-e*2-t*2),height:(2-y)*(v+1)*16-(y?2:4)*(n+r),pixelRatio:b}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}},Br=class{constructor(e,t,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new nr(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,n){let r=e[t].unit;if(r.length<=16)return;let i=r.subarray(16,r.length-r.length%16),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(a).then(i=>{let a=new Uint8Array(i);r.set(a,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,n)})}decryptAacSamples(e,t,n){for(;;t++){if(t>=e.length){n();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)n.set(e.subarray(t,t+16),r);return n}getAvcDecryptedUnit(e,t){let n=new Uint8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(n.subarray(r,r+16),t);return e}decryptAvcSample(e,t,n,r,i){let a=Qe(i.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(o=>{i.data=this.getAvcDecryptedUnit(a,o),this.decrypter.isSync()||this.decryptAvcSamples(e,t,n+1,r)})}decryptAvcSamples(e,t,n,r){if(e instanceof Uint8Array)throw Error(`Cannot decrypt samples of type Uint8Array`);for(;;t++,n=0){if(t>=e.length){r();return}let i=e[t].units;for(;!(n>=i.length);n++){let a=i[n];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,n,r,a),!this.decrypter.isSync()))return}}}},Y=188,Vr=class e{constructor(e,t,n){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=e,this.config=t,this.typeSupported=n}static probe(t){let n=e.syncOffset(t);return n>0&&y.warn(`MPEG2-TS detected but first sync word found @ offset ${n}`),n!==-1}static syncOffset(e){let t=e.length,n=Math.min(940,e.length-Y)+1,r=0;for(;r<n;){let i=!1,a=-1,o=0;for(let s=r;s<t;s+=Y)if(e[s]===71){if(o++,a===-1&&(a=s,a!==0&&(n=Math.min(a+18612,e.length-Y)+1)),i||=Ur(e,s)===0,i&&o>1&&(a===0&&o>2||s+Y>n))return a}else if(o)return-1;else break;r++}return-1}static createTrack(e,t){return{container:e===`video`||e===`audio`?`video/mp2t`:void 0,type:e,id:Pe[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e===`audio`?t:void 0}}resetInitSegment(t,n,r,i){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=e.createTrack(`video`),this._audioTrack=e.createTrack(`audio`,i),this._id3Track=e.createTrack(`id3`),this._txtTrack=e.createTrack(`text`),this._audioTrack.segmentCodec=`aac`,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r,this._duration=i}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_avcTrack:t,_id3Track:n}=this;e&&(e.pesData=null),t&&(t.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null}demux(t,n,r=!1,i=!1){r||(this.sampleAes=null);let a,o=this._avcTrack,s=this._audioTrack,c=this._id3Track,l=this._txtTrack,p=o.pid,m=o.pesData,h=s.pid,g=c.pid,_=s.pesData,v=c.pesData,b=null,x=this.pmtParsed,S=this._pmtId,C=t.length;if(this.remainderData&&=(t=qe(this.remainderData,t),C=t.length,null),C<Y&&!i)return this.remainderData=t,{audioTrack:s,videoTrack:o,id3Track:c,textTrack:l};let w=Math.max(0,e.syncOffset(t));C-=(C-w)%Y,C<t.byteLength&&!i&&(this.remainderData=new Uint8Array(t.buffer,C,t.buffer.byteLength-C));let T=0;for(let e=w;e<C;e+=Y)if(t[e]===71){let n=!!(t[e+1]&64),i=Ur(t,e),u=(t[e+3]&48)>>4,d;if(u>1){if(d=e+5+t[e+4],d===e+Y)continue}else d=e+4;switch(i){case p:n&&(m&&(a=Kr(m))&&this.parseAVCPES(o,l,a,!1),m={data:[],size:0}),m&&(m.data.push(t.subarray(d,e+Y)),m.size+=e+Y-d);break;case h:if(n){if(_&&(a=Kr(_)))switch(s.segmentCodec){case`aac`:this.parseAACPES(s,a);break;case`mp3`:this.parseMPEGPES(s,a)}_={data:[],size:0}}_&&(_.data.push(t.subarray(d,e+Y)),_.size+=e+Y-d);break;case g:n&&(v&&(a=Kr(v))&&this.parseID3PES(c,a),v={data:[],size:0}),v&&(v.data.push(t.subarray(d,e+Y)),v.size+=e+Y-d);break;case 0:n&&(d+=t[d]+1),S=this._pmtId=Wr(t,d);break;case S:{n&&(d+=t[d]+1);
1let i=Gr(t,d,this.typeSupported,r);p=i.avc,p>0&&(o.pid=p),h=i.audio,h>0&&(s.pid=h,s.segmentCodec=i.segmentCodec),g=i.id3,g>0&&(c.pid=g),b!==null&&!x&&(y.warn(`MPEG-TS PMT found at ${e} after unknown PID '${b}'. Backtracking to sync byte @${w} to parse all TS packets.`),b=null,e=w-188),x=this.pmtParsed=!0;break}case 17:case 8191:break;default:b=i}}else T++;if(T>0){let e=Error(`Found ${T} TS packet/s that do not start with 0x47`);this.observer.emit(u.ERROR,u.ERROR,{type:d.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message})}o.pesData=m,s.pesData=_,c.pesData=v;let E={audioTrack:s,videoTrack:o,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(E),E}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return t=e?this.demux(e,-1,!1,!0):{videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:n,id3Track:r,textTrack:i}=e,a=n.pesData,o=t.pesData,s=r.pesData,c;if(a&&(c=Kr(a))?(this.parseAVCPES(n,i,c,!0),n.pesData=null):n.pesData=a,o&&(c=Kr(o))){switch(t.segmentCodec){case`aac`:this.parseAACPES(t,c);break;case`mp3`:this.parseMPEGPES(t,c)}t.pesData=null}else o!=null&&o.size&&y.log(`last AAC PES packet truncated,might overlap between fragments`),t.pesData=o;s&&(c=Kr(s))?(this.parseID3PES(r,c),r.pesData=null):r.pesData=s}demuxSampleAes(e,t,n){let r=this.demux(e,n,!0,!this.config.progressive),i=this.sampleAes=new Br(this.observer,this.config,t);return this.decrypt(r,i)}decrypt(e,t){return new Promise(n=>{let{audioTrack:r,videoTrack:i}=e;r.samples&&r.segmentCodec===`aac`?t.decryptAacSamples(r.samples,0,()=>{i.samples?t.decryptAvcSamples(i.samples,0,0,()=>{n(e)}):n(e)}):i.samples&&t.decryptAvcSamples(i.samples,0,0,()=>{n(e)})})}destroy(){this._duration=0}parseAVCPES(e,t,n,r){let i=this.parseAVCNALu(e,n.data),a=this.avcSample,o,s=!1;n.data=null,a&&i.length&&!e.audFound&&(qr(a,e),a=this.avcSample=Hr(!1,n.pts,n.dts,``)),i.forEach(r=>{var i;switch(r.type){case 1:{let t=!1;o=!0;let i=r.data;if(s&&i.length>4){let e=new zr(i).readSliceType();(e===2||e===4||e===7||e===9)&&(t=!0)}if(t){var c;(c=a)!=null&&c.frame&&!a.key&&(qr(a,e),a=this.avcSample=null)}a||=this.avcSample=Hr(!0,n.pts,n.dts,``),a.frame=!0,a.key=t;break}case 5:o=!0,(i=a)!=null&&i.frame&&!a.key&&(qr(a,e),a=this.avcSample=null),a||=this.avcSample=Hr(!0,n.pts,n.dts,``),a.key=!0,a.frame=!0;break;case 6:o=!0,Ze(r.data,1,n.pts,t.samples);break;case 7:if(o=!0,s=!0,!e.sps){let t=r.data,n=new zr(t).readSPS();e.width=n.width,e.height=n.height,e.pixelRatio=n.pixelRatio,e.sps=[t],e.duration=this._duration;let i=t.subarray(1,4),a=`avc1.`;for(let e=0;e<3;e++){let t=i[e].toString(16);t.length<2&&(t=`0`+t),a+=t}e.codec=a}break;case 8:o=!0,e.pps||=[r.data];break;case 9:o=!1,e.audFound=!0,a&&qr(a,e),a=this.avcSample=Hr(!1,n.pts,n.dts,``);break;case 12:o=!0;break;default:o=!1,a&&(a.debug+=`unknown NAL `+r.type+` `)}a&&o&&a.units.push(r)}),r&&a&&(qr(a,e),this.avcSample=null)}getLastNalUnit(e){var t;let n=this.avcSample,r;if((!n||n.units.length===0)&&(n=e[e.length-1]),(t=n)!=null&&t.units){let e=n.units;r=e[e.length-1]}return r}parseAVCNALu(e,t){let n=t.byteLength,r=e.naluState||0,i=r,a=[],o=0,s,c,l,u=-1,d=0;for(r===-1&&(u=0,d=t[0]&31,r=0,o=1);o<n;){if(s=t[o++],!r){r=+!s;continue}if(r===1){r=s?0:2;continue}if(!s)r=3;else if(s===1){if(u>=0){let e={data:t.subarray(u,o-r-1),type:d};a.push(e)}else{let n=this.getLastNalUnit(e.samples);if(n&&(i&&o<=4-i&&n.state&&(n.data=n.data.subarray(0,n.data.byteLength-i)),c=o-r-1,c>0)){let e=new Uint8Array(n.data.byteLength+c);e.set(n.data,0),e.set(t.subarray(0,c),n.data.byteLength),n.data=e,n.state=0}}o<n?(l=t[o]&31,u=o,d=l,r=0):r=-1}else r=0}if(u>=0&&r>=0){let e={data:t.subarray(u,n),type:d,state:r};a.push(e)}if(a.length===0){let n=this.getLastNalUnit(e.samples);if(n){let e=new Uint8Array(n.data.byteLength+t.byteLength);e.set(n.data,0),e.set(t,n.data.byteLength),n.data=e}}return e.naluState=r,a}parseAACPES(e,t){let n=0,r=this.aacOverFlow,i=t.data;if(r){this.aacOverFlow=null;let t=r.missing,a=r.sample.unit.byteLength;if(t===-1){let e=new Uint8Array(a+i.byteLength);e.set(r.sample.unit,0),e.set(i,a),i=e}else{let o=a-t;r.sample.unit.set(i.subarray(0,t),o),e.samples.push(r.sample),n=r.missing}}let a,o;for(a=n,o=i.length;a<o-1&&!vr(i,a);a++);if(a!==n){let e,t=a<o-1;e=t?`AAC PES did not start with ADTS header,offset:${a}`:`No ADTS header found in AAC PES`;let n=Error(e);
1if(y.warn(`parsing error: ${e}`),this.observer.emit(u.ERROR,u.ERROR,{type:d.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:n,reason:e}),!t)return}xr(e,this.observer,i,a,this.audioCodec);let s;if(t.pts!==void 0)s=t.pts;else if(r){let t=Sr(e.samplerate);s=r.sample.pts+t}else{y.warn(`[tsdemuxer]: AAC PES unknown PTS`);return}let c=0,l;for(;a<o;){if(l=wr(e,i,a,s,c),a+=l.length,l.missing){this.aacOverFlow=l;break}for(c++;a<o-1&&!vr(i,a);a++);}}parseMPEGPES(e,t){let n=t.data,r=n.length,i=0,a=0,o=t.pts;if(o===void 0){y.warn(`[tsdemuxer]: MPEG PES unknown PTS`);return}for(;a<r;)if(Ir(n,a)){let t=Nr(e,n,a,o,i);if(t)a+=t.length,i++;else break}else a++}parseID3PES(e,t){if(t.pts===void 0){y.warn(`[tsdemuxer]: ID3 PES unknown PTS`);return}let n=o({},t,{type:this._avcTrack?V.emsg:V.audioId3,duration:1/0});e.samples.push(n)}};function Hr(e,t,n,r){return{key:e,frame:!1,pts:t,dts:n,units:[],debug:r,length:0}}function Ur(e,t){return((e[t+1]&31)<<8)+e[t+2]}function Wr(e,t){return(e[t+10]&31)<<8|e[t+11]}function Gr(e,t,n,r){let i={audio:-1,avc:-1,id3:-1,segmentCodec:`aac`},a=(e[t+1]&15)<<8|e[t+2],o=t+3+a-4,s=(e[t+10]&15)<<8|e[t+11];for(t+=12+s;t<o;){let a=Ur(e,t);switch(e[t]){case 207:if(!r){y.log(`ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream`);break}case 15:i.audio===-1&&(i.audio=a);break;case 21:i.id3===-1&&(i.id3=a);break;case 219:if(!r){y.log(`H.264 with AES-128-CBC slice encryption found in unencrypted stream`);break}case 27:i.avc===-1&&(i.avc=a);break;case 3:case 4:n.mpeg!==!0&&n.mp3!==!0?y.log(`MPEG audio found, not supported in this browser`):i.audio===-1&&(i.audio=a,i.segmentCodec=`mp3`);break;case 36:y.warn(`Unsupported HEVC stream type found`)}t+=((e[t+3]&15)<<8|e[t+4])+5}return i}function Kr(e){let t=0,n,r,i,a,o,s=e.data;if(!e||e.size===0)return null;for(;s[0].length<19&&s.length>1;){let e=new Uint8Array(s[0].length+s[1].length);e.set(s[0]),e.set(s[1],s[0].length),s[0]=e,s.splice(1,1)}if(n=s[0],(n[0]<<16)+(n[1]<<8)+n[2]===1){if(r=(n[4]<<8)+n[5],r&&r>e.size-6)return null;let c=n[7];c&192&&(a=(n[9]&14)*536870912+(n[10]&255)*4194304+(n[11]&254)*16384+(n[12]&255)*128+(n[13]&254)/2,c&64?(o=(n[14]&14)*536870912+(n[15]&255)*4194304+(n[16]&254)*16384+(n[17]&255)*128+(n[18]&254)/2,a-o>54e5&&(y.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),i=n[8];let l=i+9;if(e.size<=l)return null;e.size-=l;let u=new Uint8Array(e.size);for(let e=0,r=s.length;e<r;e++){n=s[e];let r=n.byteLength;if(l){if(l>r){l-=r;continue}n=n.subarray(l),r-=l,l=0}u.set(n,t),t+=r}return r&&(r-=i+3),{data:u,pts:a,dts:o,len:r}}return null}function qr(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let n=t.samples,r=n.length;if(r){let t=n[r-1];e.pts=t.pts,e.dts=t.dts}else{t.dropped++;return}}t.samples.push(e)}e.debug.length&&y.log(e.pts+`/`+e.dts+`:`+e.debug)}var Jr=class extends dr{resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,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=(ve(e,0)||[]).length;for(let n=e.length;t<n;t++)if(Rr(e,t))return y.log(`MPEG Audio sync word found !`),!0;return!1}canParse(e,t){return Lr(e,t)}appendFrame(e,t,n){if(this.basePTS!==null)return Nr(e,t,n,this.basePTS,this.frameIndex)}},Yr=class{static getSilentFrame(e,t){switch(e){case`mp4a.40.2`:if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)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(t===2||t===3)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])}}},Xr=2**32-1,X=class e{static init(){e.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:[]};let t;for(t in e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);let n=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new 
vendor: 5,880 bytes, line 1
1Uint8Array([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]);e.HDLR_TYPES={video:n,audio:r};let i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),a=new Uint8Array([0,0,0,0,0,0,0,0]);e.STTS=e.STSC=e.STCO=a,e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let o=new Uint8Array([105,115,111,109]),s=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,o,c,o,s),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,i))}static box(e,...t){let n=8,r=t.length,i=r;for(;r--;)n+=t[r].byteLength;let a=new Uint8Array(n);for(a[0]=n>>24&255,a[1]=n>>16&255,a[2]=n>>8&255,a[3]=n&255,a.set(e,4),r=0,n=8;r<i;r++)a.set(t[r],n),n+=t[r].byteLength;return a}static hdlr(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])}static mdat(t){return e.box(e.types.mdat,t)}static mdhd(t,n){n*=t;let r=Math.floor(n/(Xr+1)),i=Math.floor(n%(Xr+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))}static mfhd(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type===`audio`?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}static moof(t,n,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,n))}static moov(t){let n=t.length,r=[];for(;n--;)r[n]=e.trak(t[n]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(r,e.mvex(t)))}static mvex(t){let n=t.length,r=[];for(;n--;)r[n]=e.trex(t[n]);return e.box.apply(null,[e.types.mvex,...r])}static mvhd(t,n){n*=t;let r=Math.floor(n/(Xr+1)),i=Math.floor(n%(Xr+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,i>>24,i>>16&255,i>>8&255,i&255,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 e.box(e.types.mvhd,a)}static sdtp(t){let n=t.samples||[],r=new Uint8Array(4+n.length),i,a;for(i=0;i<n.length;i++)a=n[i].flags,r[i+4]=a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy;return e.box(e.types.sdtp,r)}static stbl(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))}static avc1(t){let n=[],r=[],i,a,o;for(i=0;i<t.sps.length;i++)a=t.sps[i],o=a.byteLength,n.push(o>>>8&255),n.push(o&255),n=n.concat(Array.prototype.slice.call(a));for(i=0;i<t.pps.length;i++)a=t.pps[i],o=a.byteLength,r.push(o>>>8&255),r.push(o&255),r=r.concat(Array.prototype.slice.call(a));let s=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n,[t.pps.length],r))),c=t.width,l=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.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,c>>8&255,c&255,l>>8&255,l&255,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]),s,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&255])))}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,t].concat(e.config,[6,1,2]))}static mp4a(t){let n=t.samplerate;return e.box(e.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,n>>8&255,n&255,0,0]),e.box(e.types.esds,e.esds(t)))}static mp3(t){let n=t.samplerate;return e.box(e.types[`.mp3`],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,n>>8&255,n&255,0,0]))}static stsd(t){return t.type===`audio`?t.segmentCodec===`mp3`&&t.codec===`mp3`?e.box(e.types.stsd,e.STSD,e.mp3(t)):e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))}static tkhd(t){let n=t.id,r=t.duration*t.timescale,i=t.width,a=t.height,o=Math.floor(r/(Xr+1)),s=Math.floor(r%(Xr+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,n>>24&255,n>>16&255,n>>8&255,n&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,s>>24,s>>16&255,s>>8&255,s&255,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,i>>8&255,i&255,0,0,a>>8&255,a&255,0,0]))}static traf(t,n){let r=e.sdtp(t),i=t.id,a=Math.floor(n/(Xr+1)),o=Math.floor(n%(Xr+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255])),e.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}static trex(t){let n=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,n){let r=t.samples||[],i=r.length,a=12+16*i,o=new Uint8Array(a),s,c,l,u,d,f;for(n+=8+a,o.set([+(t.type===`video`),0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255],0),s=0;s<i;s++)c=r[s],l=c.duration,u=c.size,d=c.flags,f=c.cts,o.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,f>>>24&255,f>>>16&255,f>>>8&255,f&255],12+16*s);return e.box(e.types.trun,o)}
1static initSegment(t){e.types||e.init();let n=e.moov(t),r=new Uint8Array(e.FTYP.byteLength+n.byteLength);return r.set(e.FTYP),r.set(n,e.FTYP.byteLength),r}};X.types=void 0,X.HDLR_TYPES=void 0,X.STTS=void 0,X.STSC=void 0,X.STCO=void 0,X.STSZ=void 0,X.VMHD=void 0,X.SMHD=void 0,X.STSD=void 0,X.FTYP=void 0,X.DINF=void 0;var Zr=9e4;function Qr(e,t,n=1,r=!1){let i=e*t*n;return r?Math.round(i):i}function $r(e,t,n=1,r=!1){return Qr(e,t,1/n,r)}function ei(e,t=!1){return Qr(e,1e3,1/Zr,t)}function ti(e,t=1){return Qr(e,Zr,1/t)}var ni=1e4,ri=1024,ii=1152,ai=null,oi=null,si=class{constructor(e,t,n,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=n,this.ISGenerated=!1,ai===null){let e=(navigator.userAgent||``).match(/Chrome\/(\d+)/i);ai=e?parseInt(e[1]):0}if(oi===null){let e=navigator.userAgent.match(/Safari\/(\d+)/i);oi=e?parseInt(e[1]):0}}destroy(){}resetTimeStamp(e){y.log(`[mp4-remuxer]: initPTS & initDTS reset`),this._initPTS=this._initDTS=e}resetNextTimestamp(){y.log(`[mp4-remuxer]: reset next timestamp`),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){y.log(`[mp4-remuxer]: ISGenerated flag reset`),this.ISGenerated=!1}getVideoStartPts(e){let t=!1,n=e.reduce((e,n)=>{let r=n.pts-e;return r<-4294967296?(t=!0,Z(e,n.pts)):r>0?e:n.pts},e[0].pts);return t&&y.debug(`PTS rollover detected`),n}remux(e,t,n,r,i,a,o,s){let c,l,u,d,f,p,m=i,h=i,g=e.pid>-1,_=t.pid>-1,v=t.samples.length,b=e.samples.length>0,x=o&&v>0||v>1;if((!g||b)&&(!_||x)||this.ISGenerated||o){this.ISGenerated||(u=this.generateIS(e,t,i,a));let n=this.isVideoContiguous,r=-1,o;if(x&&(r=ci(t.samples),!n&&this.config.forceKeyFrameOnDiscontinuity)){if(p=!0,r>0){y.warn(`[mp4-remuxer]: Dropped ${r} out of ${v} video samples due to a missing keyframe`);let e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(r),t.dropped+=r,h+=(t.samples[0].pts-e)/t.inputTimeScale,o=h}else r===-1&&(y.warn(`[mp4-remuxer]: No keyframe found out of ${v} video samples`),p=!1)}if(this.ISGenerated){if(b&&x){let n=this.getVideoStartPts(t.samples),r=(Z(e.samples[0].pts,n)-n)/t.inputTimeScale;m+=Math.max(0,r),h+=Math.max(0,-r)}if(b){if(e.samplerate||(y.warn(`[mp4-remuxer]: regenerate InitSegment as audio detected`),u=this.generateIS(e,t,i,a)),l=this.remuxAudio(e,m,this.isAudioContiguous,a,_||x||s===B.AUDIO?h:void 0),x){let r=l?l.endPTS-l.startPTS:0;t.inputTimeScale||(y.warn(`[mp4-remuxer]: regenerate InitSegment as video detected`),u=this.generateIS(e,t,i,a)),c=this.remuxVideo(t,h,n,r)}}else x&&(c=this.remuxVideo(t,h,n,0));c&&(c.firstKeyFrame=r,c.independent=r!==-1,c.firstKeyFramePTS=o)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(f=li(n,i,this._initPTS,this._initDTS)),r.samples.length&&(d=ui(r,i,this._initPTS))),{audio:l,video:c,initSegment:u,independent:p,text:d,id3:f}}generateIS(e,t,n,r){let i=e.samples,a=t.samples,o=this.typeSupported,s={},c=this._initPTS,l=!c||r,u=`audio/mp4`,d,f,p;if(l&&(d=f=1/0),e.config&&i.length&&(e.timescale=e.samplerate,e.segmentCodec===`mp3`&&(o.mpeg?(u=`audio/mpeg`,e.codec=``):o.mp3&&(e.codec=`mp3`)),s.audio={id:`audio`,container:u,codec:e.codec,initSegment:e.segmentCodec===`mp3`&&o.mpeg?new Uint8Array:X.initSegment([e]),metadata:{channelCount:e.channelCount}},l&&(p=e.inputTimeScale,!c||p!==c.timescale?d=f=i[0].pts-Math.round(p*n):l=!1)),t.sps&&t.pps&&a.length&&(t.timescale=t.inputTimeScale,s.video={id:`main`,container:`video/mp4`,codec:t.codec,initSegment:X.initSegment([t]),metadata:{width:t.width,height:t.height}},l)){if(p=t.inputTimeScale,!c||p!==c.timescale){let e=this.getVideoStartPts(a),t=Math.round(p*n);f=Math.min(f,Z(a[0].dts,e)-t),d=Math.min(d,e-t)}else l=!1}if(Object.keys(s).length)return this.ISGenerated=!0,l?(this._initPTS={baseTime:d,timescale:p},this._initDTS={baseTime:f,timescale:p}):d=p=void 0,{tracks:s,initPTS:d,timescale:p}}remuxVideo(e,t,n,r){let i=e.inputTimeScale,a=e.samples,s=[],c=a.length,l=this._initPTS,p=this.nextAvcDts,m=8,h=this.videoSampleDuration,g,_,v=1/0,b=-1/0,x=!1;(!n||p===null)&&(p=t*i-(a[0].pts-Z(a[0].dts,a[0].pts)));let S=l.baseTime*i/l.timescale;for(let e=0;e<c;e++){let t=a[e];t.pts=Z(t.pts-S,p),t.dts=Z(t.dts-S,p),t.dts<a[e>0?e-1:e].dts&&(x=!0)}x&&a.sort(function(e,t){let n=e.dts-t.dts,r=e.pts-t.pts;return n||r}),g=a[0].dts,_=a[a.length-1].dts;let C=_-g,w=C?Math.round(C/(c-1)):h||e.inputTimeScale/30;if(n){let e=g-p,t=e>w,n=e<-1;if((t||n)&&(t?y.warn(`AVC: ${ei(e,!0)} ms (${e}dts) hole between fragments detected, filling it`):y.warn(`AVC: ${ei(-e,!0)} ms (${e}dts) overlapping between fragments detected`),!n||p>=a[0].pts)){g=p;let t=a[0].pts-e;a[0].dts=g,a[0].pts=t,y.log(`Video: First PTS/DTS adjusted: ${ei(t,!0)}/${ei(g,!0)}, delta: ${ei(e,!0)} ms`)}}g=Math.max(0,g);let T=0,E=0;for(let e=0;e<c;e++){let t=a[e],n=t.units,r=n.length,i=0;for(let e=0;e<r;e++)i+=n[e].data.length;E+=i,T+=r,t.length=i,t.dts=Math.max(t.dts,g),v=Math.min(t.pts,v),b=Math.max(t.pts,b)}_=a[c-1].dts;let D=E+4*T+8,O;try{O=new Uint8Array(D)}catch(e){this.observer.emit(u.ERROR,u.ERROR,{type:d.MUX_ERROR,details:f.REMUX_ALLOC_ER
1ROR,fatal:!1,error:e,bytes:D,reason:`fail allocating video mdat ${D}`});return}let ee=new DataView(O.buffer);ee.setUint32(0,D),O.set(X.types.mdat,4);let k=!1,te=1/0,A=1/0,ne=-1/0,re=-1/0;for(let e=0;e<c;e++){let t=a[e],n=t.units,o=0;for(let e=0,t=n.length;e<t;e++){let t=n[e],r=t.data,i=t.data.byteLength;ee.setUint32(m,i),m+=4,O.set(r,m),m+=i,o+=4+i}let l;if(e<c-1)h=a[e+1].dts-t.dts,l=a[e+1].pts-t.pts;else{let n=this.config,o=e>0?t.dts-a[e-1].dts:w;if(l=e>0?t.pts-a[e-1].pts:w,n.stretchShortVideoTrack&&this.nextAudioPts!==null){let e=Math.floor(n.maxBufferHole*i),a=(r?v+r*i:this.nextAudioPts)-t.pts;a>e?(h=a-o,h<0?h=o:k=!0,y.log(`[mp4-remuxer]: It is approximately ${a/90} ms to the next segment; using duration ${h/90} ms for the last video frame.`)):h=o}else h=o}let u=Math.round(t.pts-t.dts);te=Math.min(te,h),ne=Math.max(ne,h),A=Math.min(A,l),re=Math.max(re,l),s.push(new di(t.key,h,o,u))}if(s.length){if(ai){if(ai<70){let e=s[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(oi&&re-A<ne-te&&w/ne<.025&&s[0].cts===0){y.warn(`Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.`);let e=g;for(let t=0,n=s.length;t<n;t++){let r=e+s[t].duration,i=e+s[t].cts;if(t<n-1){let e=r+s[t+1].cts;s[t].duration=e-i}else s[t].duration=t?s[t-1].duration:w;s[t].cts=0,e=r}}}h=k||!h?w:h,this.nextAvcDts=p=_+h,this.videoSampleDuration=h,this.isVideoContiguous=!0;let ie={data1:X.moof(e.sequenceNumber++,g,o({},e,{samples:s})),data2:O,startPTS:v/i,endPTS:(b+h)/i,startDTS:g/i,endDTS:p/i,type:`video`,hasAudio:!1,hasVideo:!0,nb:s.length,dropped:e.dropped};return e.samples=[],e.dropped=0,ie}remuxAudio(e,t,n,r,i){let a=e.inputTimeScale,s=a/(e.samplerate?e.samplerate:a),c=e.segmentCodec===`aac`?ri:ii,l=c*s,p=this._initPTS,m=e.segmentCodec===`mp3`&&this.typeSupported.mpeg,h=[],g=i!==void 0,_=e.samples,v=m?0:8,b=this.nextAudioPts||-1,x=t*a,S=p.baseTime*a/p.timescale;if(this.isAudioContiguous=n||=_.length&&b>0&&(r&&Math.abs(x-b)<9e3||Math.abs(Z(_[0].pts-S,x)-b)<20*l),_.forEach(function(e){e.pts=Z(e.pts-S,x)}),!n||b<0){if(_=_.filter(e=>e.pts>=0),!_.length)return;b=i===0?0:r&&!g?Math.max(0,x):_[0].pts}if(e.segmentCodec===`aac`){let t=this.config.maxAudioFramesDrift;for(let n=0,r=b;n<_.length;n++){let i=_[n],o=i.pts,s=o-r,c=Math.abs(1e3*s/a);if(s<=-t*l&&g)n===0&&(y.warn(`Audio frame @ ${(o/a).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*s/a)} ms.`),this.nextAudioPts=b=r=o);else if(s>=t*l&&c<ni&&g){let t=Math.round(s/l);r=o-t*l,r<0&&(t--,r+=l),n===0&&(this.nextAudioPts=b=r),y.warn(`[mp4-remuxer]: Injecting ${t} audio frame @ ${(r/a).toFixed(3)}s due to ${Math.round(1e3*s/a)} ms gap.`);for(let a=0;a<t;a++){let t=Math.max(r,0),a=Yr.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);a||=(y.log(`[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.`),i.unit.subarray()),_.splice(n,0,{unit:a,pts:t}),r+=l,n++}}i.pts=r,r+=l}}let C=null,w=null,T,E=0,D=_.length;for(;D--;)E+=_[D].unit.byteLength;for(let t=0,r=_.length;t<r;t++){let r=_[t],i=r.unit,a=r.pts;if(w!==null){let e=h[t-1];e.duration=Math.round((a-w)/s)}else if(n&&e.segmentCodec===`aac`&&(a=b),C=a,E>0){E+=v;try{T=new Uint8Array(E)}catch(e){this.observer.emit(u.ERROR,u.ERROR,{type:d.MUX_ERROR,details:f.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:E,reason:`fail allocating audio mdat ${E}`});return}m||(new DataView(T.buffer).setUint32(0,E),T.set(X.types.mdat,4))}else return;T.set(i,v);let o=i.byteLength;v+=o,h.push(new di(!0,c,o,0)),w=a}let O=h.length;if(!O)return;let ee=h[h.length-1];this.nextAudioPts=b=w+s*ee.duration;let k=m?new Uint8Array:X.moof(e.sequenceNumber++,C/s,o({},e,{samples:h}));e.samples=[];let te=C/a,A=b/a,ne={data1:k,data2:T,startPTS:te,endPTS:A,startDTS:te,endDTS:A,type:`audio`,hasAudio:!0,hasVideo:!1,nb:O};return this.isAudioContiguous=!0,ne}remuxEmptyAudio(e,t,n,r){let i=e.inputTimeScale,a=i/(e.samplerate?e.samplerate:i),o=this.nextAudioPts,s=this._initDTS,c=s.baseTime*9e4/s.timescale,l=(o===null?r.startDTS*i:o)+c,u=r.endDTS*i+c,d=a*ri,f=Math.ceil((u-l)/d),p=Yr.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(y.warn(`[mp4-remuxer]: remux empty Audio`),!p){y.trace(`[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec`);return}let m=[];for(let e=0;e<f;e++){let t=l+e*d;m.push({unit:p,pts:t,dts:t})}return e.samples=m,this.remuxAudio(e,t,n,!1)}};function Z(e,t){let n;if(t===null)return e;for(n=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=n;return e}function ci(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function li(e,t,n,r){let i=e.samples.length;if(!i)return;let a=e.inputTimeScale;for(let o=0;o<i;o++){let i=e.samples[o];i.pts=Z(i.pts-n.baseTime*a/n.timescale,t*a)/a,i.dts=Z(i.dts-r.baseTime*a/r.timescale,t*a)/a}let o=e.samples;return e.samples=[],{samples:o}}
1function ui(e,t,n){let r=e.samples.length;if(!r)return;let i=e.inputTimeScale;for(let a=0;a<r;a++){let r=e.samples[a];r.pts=Z(r.pts-n.baseTime*i/n.timescale,t*i)/i}e.samples.sort((e,t)=>e.pts-t.pts);let a=e.samples;return e.samples=[],{samples:a}}var di=class{constructor(e,t,n,r){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=n,this.cts=r,this.flags=new fi(e)}},fi=class{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}},pi=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,n,r){this.audioCodec=t,this.videoCodec=n,this.generateInitSegment(Be(e,r)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let r=this.initData=ze(e);t||=hi(r.audio,D.AUDIO),n||=hi(r.video,D.VIDEO);let i={};r.audio&&r.video?i.audiovideo={container:`video/mp4`,codec:t+`,`+n,initSegment:e,id:`main`}:r.audio?i.audio={container:`audio/mp4`,codec:t,initSegment:e,id:`audio`}:r.video?i.video={container:`video/mp4`,codec:n,initSegment:e,id:`main`}:y.warn(`[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.`),this.initTracks=i}remux(e,t,n,r,i,a){var o,s;let{initPTS:c,lastEndTime:u}=this,d={audio:void 0,video:void 0,text:r,id3:n,initSegment:void 0};l(u)||(u=this.lastEndTime=i||0);let f=t.samples;if(!(f!=null&&f.length))return d;let p={initPTS:void 0,timescale:1},m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(f),m=this.initData),!((s=m)!=null&&s.length))return y.warn(`[passthrough-remuxer.ts]: Failed to generate initSegment.`),d;this.emitInitSegment&&=(p.tracks=this.initTracks,!1);let h=Ue(f,m),g=He(m,f),_=g===null?i:g;(mi(c,_,i,h)||p.timescale!==c.timescale&&a)&&(p.initPTS=_-i,c&&c.timescale===1&&y.warn(`Adjusting initPTS by ${p.initPTS-c.baseTime}`),this.initPTS=c={baseTime:p.initPTS,timescale:1});let v=e?_-c.baseTime/c.timescale:u,b=v+h;Ge(m,f,c.baseTime/c.timescale),h>0?this.lastEndTime=b:(y.warn(`Duration parsed from mp4 should be greater than zero`),this.resetNextTimestamp());let x=!!m.audio,S=!!m.video,C=``;x&&(C+=`audio`),S&&(C+=`video`);let w={data1:f,startPTS:v,startDTS:v,endPTS:b,endDTS:b,type:C,hasAudio:x,hasVideo:S,nb:1,dropped:0};return d.audio=w.type===`audio`?w:void 0,d.video=w.type===`audio`?void 0:w,d.initSegment=p,d.id3=li(n,i,c,c),r.samples.length&&(d.text=ui(r,i,c)),d}};function mi(e,t,n,r){if(e===null)return!0;let i=Math.max(r,1),a=t-e.baseTime/e.timescale;return Math.abs(a-n)>i}function hi(e,t){let n=e?.codec;return n&&n.length>4?n:n===`hvc1`||n===`hev1`?`hvc1.1.6.L120.90`:n===`av01`?`av01.0.04M.08`:n===`avc1`||t===D.VIDEO?`avc1.42e01e`:`mp4a.40.5`}var gi;try{gi=self.performance.now.bind(self.performance)}catch{y.debug(`Unable to use Performance API on this environment`),gi=typeof self<`u`&&self.Date.now}var _i=[{demux:Dr,remux:pi},{demux:Vr,remux:si},{demux:Tr,remux:si},{demux:Jr,remux:si}],vi=class{constructor(e,t,n,r,i){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=n,this.vendor=r,this.id=i}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,n,r){let i=n.transmuxing;i.executeStart=gi();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:s}=this;r&&(this.currentTransmuxState=r);let{contiguous:c,discontinuity:l,trackSwitch:p,accurateTimeOffset:m,timeOffset:h,initSegmentChange:g}=r||o,{audioCodec:_,videoCodec:v,defaultInitPts:b,duration:x,initSegmentData:S}=s,C=yi(a,t);
1if(C&&C.method===`AES-128`){let e=this.getDecrypter();if(e.isSync()){let t=e.softwareDecrypt(a,C.key.buffer,C.iv.buffer);if(n.part>-1&&(t=e.flush()),!t)return i.executeEnd=gi(),bi(n);a=new Uint8Array(t)}else return this.decryptionPromise=e.webCryptoDecrypt(a,C.key.buffer,C.iv.buffer).then(e=>{let t=this.push(e,null,n);return this.decryptionPromise=null,t}),this.decryptionPromise}let w=this.needsProbing(l,p);if(w){let e=this.configureTransmuxer(a);if(e)return y.warn(`[transmuxer] ${e.message}`),this.observer.emit(u.ERROR,u.ERROR,{type:d.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),i.executeEnd=gi(),bi(n)}(l||p||g||w)&&this.resetInitSegment(S,_,v,x,t),(l||g||w)&&this.resetInitialTimestamp(b),c||this.resetContiguity();let T=this.transmux(a,C,h,m,n),E=this.currentTransmuxState;return E.contiguous=!0,E.discontinuity=!1,E.trackSwitch=!1,i.executeEnd=gi(),T}flush(e){let t=e.transmuxing;t.executeStart=gi();let{decrypter:n,currentTransmuxState:r,decryptionPromise:i}=this;if(i)return i.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(n){let t=n.flush();t&&a.push(this.push(t,null,e))}let{demuxer:s,remuxer:c}=this;if(!s||!c)return t.executeEnd=gi(),[bi(e)];let l=s.flush(o);return xi(l)?l.then(t=>(this.flushRemux(a,t,e),a)):(this.flushRemux(a,l,e),a)}flushRemux(e,t,n){let{audioTrack:r,videoTrack:i,id3Track:a,textTrack:o}=t,{accurateTimeOffset:s,timeOffset:c}=this.currentTransmuxState;y.log(`[transmuxer.ts]: Flushed fragment ${n.sn}${n.part>-1?` p: `+n.part:``} of level ${n.level}`);let l=this.remuxer.remux(r,i,a,o,c,s,!0,this.id);e.push({remuxResult:l,chunkMeta:n}),n.transmuxing.executeEnd=gi()}resetInitialTimestamp(e){let{demuxer:t,remuxer:n}=this;!t||!n||(t.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,n,r,i){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,n,r),o.resetInitSegment(e,t,n,i))}destroy(){this.demuxer&&=(this.demuxer.destroy(),void 0),this.remuxer&&=(this.remuxer.destroy(),void 0)}transmux(e,t,n,r,i){let a;return a=t&&t.method===`SAMPLE-AES`?this.transmuxSampleAes(e,t,n,r,i):this.transmuxUnencrypted(e,n,r,i),a}transmuxUnencrypted(e,t,n,r){let{audioTrack:i,videoTrack:a,id3Track:o,textTrack:s}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,a,o,s,t,n,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,n,r,i){return this.demuxer.demuxSampleAes(e,t,n).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,n,r,!1,this.id),chunkMeta:i}))}configureTransmuxer(e){let{config:t,observer:n,typeSupported:r,vendor:i}=this,a;for(let t=0,n=_i.length;t<n;t++)if(_i[t].demux.probe(e)){a=_i[t];break}if(!a)return Error(`Failed to find demuxer by probing fragment data`);let o=this.demuxer,s=this.remuxer,c=a.remux,l=a.demux;(!s||!(s instanceof c))&&(this.remuxer=new c(n,t,r,i)),(!o||!(o instanceof l))&&(this.demuxer=new l(n,t,r),this.probe=l.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||=this.decrypter=new nr(this.config),e}};function yi(e,t){let n=null;return e.byteLength>0&&t!=null&&t.key!=null&&t.iv!==null&&t.method!=null&&(n=t),n}var bi=e=>({remuxResult:{},chunkMeta:e});function xi(e){return`then`in e&&e.then instanceof Function}var Si=class{constructor(e,t,n,r,i){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=n,this.duration=r,this.defaultInitPts=i||null}},Ci=class{constructor(e,t,n,r,i,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=n,this.trackSwitch=r,this.timeOffset=i,this.initSegmentChange=a}},wi={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,n=`~`;function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function a(e,t,r,a,o){if(typeof r!=`function`)throw TypeError(`The listener must be a function`);var s=new i(r,a||e,o),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function o(e,t){--e._eventsCount===0?e._events=new r:delete e._events[t]}function s(){this._events=new r,this._eventsCount=0}s.prototype.eventNames=function(){var e=[],r,i;if(this._eventsCount===0)return e;for(i in r=this._events)t.call(r,i)&&e.push(n?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},s.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,a=r.length,o=Array(a);i<a;i++)o[i]=r[i].fn;return o},s.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},s.prototype.emit=function(e,t,r,i,a,o){var s=n?n+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;
1if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,r),!0;case 4:return c.fn.call(c.context,t,r,i),!0;case 5:return c.fn.call(c.context,t,r,i,a),!0;case 6:return c.fn.call(c.context,t,r,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,r);break;case 4:c[d].fn.call(c[d].context,t,r,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},s.prototype.on=function(e,t,n){return a(this,e,t,n,!1)},s.prototype.once=function(e,t,n){return a(this,e,t,n,!0)},s.prototype.removeListener=function(e,t,r,i){var a=n?n+e:e;if(!this._events[a])return this;if(!t)return o(this,a),this;var s=this._events[a];if(s.fn)s.fn===t&&(!i||s.once)&&(!r||s.context===r)&&o(this,a);else{for(var c=0,l=[],u=s.length;c<u;c++)(s[c].fn!==t||i&&!s[c].once||r&&s[c].context!==r)&&l.push(s[c]);l.length?this._events[a]=l.length===1?l[0]:l:o(this,a)}return this},s.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&o(this,t)):(this._events=new r,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=n,s.EventEmitter=s,e.exports=s})(wi);var Ti=wi.exports,Ei=e(Ti),Di=dt()||{isTypeSupported:()=>!1},Oi=class{constructor(e,t,n,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 i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=n,this.onFlush=r;let a=(e,t)=>{t||={},t.frag=this.frag,t.id=this.id,e===u.ERROR&&(this.error=t.error),this.hls.trigger(e,t)};this.observer=new Ei,this.observer.on(u.FRAG_DECRYPTED,a),this.observer.on(u.ERROR,a);let o={mp4:Di.isTypeSupported(`video/mp4`),mpeg:Di.isTypeSupported(`audio/mpeg`),mp3:Di.isTypeSupported(`audio/mp4; codecs="mp3"`)},s=navigator.vendor;if(this.useWorker&&typeof Worker<`u`&&(i.workerPath||cr())){try{i.workerPath?(y.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=ur(i.workerPath)):(y.log(`injecting Web Worker for "${t}"`),this.workerContext=lr()),this.onwmsg=e=>this.onWorkerMessage(e);let{worker:e}=this.workerContext;e.addEventListener(`message`,this.onwmsg),e.onerror=e=>{let n=Error(`${e.message}  (${e.filename}:${e.lineno})`);i.enableWorker=!1,y.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(u.ERROR,{type:d.OTHER_ERROR,details:f.INTERNAL_EXCEPTION,fatal:!1,event:`demuxerWorker`,error:n})},e.postMessage({cmd:`init`,typeSupported:o,vendor:s,id:t,config:JSON.stringify(i)})}catch(e){y.warn(`Error setting up "${t}" Web Worker, fallback to inline`,e),this.resetWorker(),this.error=null,this.transmuxer=new vi(this.observer,o,i,s,t)}return}this.transmuxer=new vi(this.observer,o,i,s,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,n,r,i,a,o,s,c,l){c.transmuxing.start=self.performance.now();let{transmuxer:u}=this,d=a?a.start:i.start,f=i.decryptdata,p=this.frag,m=!(p&&i.cc===p.cc),h=!(p&&c.level===p.level),g=p?c.sn-p.sn:-1,_=this.part?c.part-this.part.index:-1,v=g===0&&c.id>1&&c.id===p?.stats.chunkCount,b=!h&&(g===1||g===0&&(_===1||v&&_<=0)),x=self.performance.now();(h||g||i.stats.parsing.start===0)&&(i.stats.parsing.start=x),a&&(_||!b)&&(a.stats.parsing.start=x);let S=!(p&&i.initSegment?.url===p.initSegment?.url),C=new Ci(m,b,s,h,d,S);if(!b||m||S){y.log(`[transmuxer-interface, ${i.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id}
2        discontinuity: ${m}
3        trackSwitch: ${h}
4        contiguous: ${b}
5        accurateTimeOffset: ${s}
6        timeOffset: ${d}
7        initSegmentChange: ${S}`);let e=new Si(n,r,t,o,l);this.configureTransmuxer(e)}if(this.frag=i,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:`demux`,data:e,decryptdata:f,chunkMeta:c,state:C},e instanceof ArrayBuffer?[e]:[]);else if(u){let t=u.push(e,f,c,C);xi(t)?(u.async=!0,t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,c,`transmuxer-interface push error`)})):(u.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 n=t.flush(e);xi(n)||t.async?(xi(n)||(n=Promise.resolve(n)),n.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,`transmuxer-interface flush error`)})):this.handleFlushResult(n,e)}}transmuxerError(e,t,n){this.hls&&(this.error=e,this.hls.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}onWorkerMessage(e){let t=e.data,n=this.hls;switch(t.event){case`init`:{let e=this.workerContext?.objectURL;e&&self.URL.revokeObjectURL(e);break}case`transmuxComplete`:this.handleTransmuxComplete(t.data);break;case`flush`:this.onFlush(t.data);break;case`workerLog`:y[t.data.logType]&&y[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,n.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)}},ki=250,Ai=2,ji=.1,Mi=.05,Ni=class{constructor(e,t,n,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=n,this.hls=r}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){let{config:n,media:r,stalled:i}=this;if(r===null)return;let{currentTime:a,seeking:o}=r,s=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,i!==null){if(this.stallReported){let e=self.performance.now()-i;y.warn(`playback not stuck anymore @${a}, after ${Math.round(e)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(c||s){this.stalled=null;return}if(r.paused&&!o||r.ended||r.playbackRate===0||!K.getBuffered(r).length)return;let l=K.bufferInfo(r,a,0),u=l.len>0,d=l.nextStart||0;if(!u&&!d)return;if(o){let e=l.len>Ai,n=!d||t&&t.start<=a||d-a>Ai&&!this.fragmentTracker.getPartialFragment(a);if(e||n)return;this.moved=!1}if(!this.moved&&this.stalled!==null){let e=Math.max(d,l.start||0)-a,t=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,n=t!=null&&t.details?.live?t.details.targetduration*2:Ai,r=this.fragmentTracker.getPartialFragment(a);if(e>0&&(e<=n||r)){this._trySkipBufferHole(r);return}}let f=self.performance.now();if(i===null){this.stalled=f;return}let p=f-i;if(!o&&p>=ki&&(this._reportStall(l),!this.media))return;let m=K.bufferInfo(r,a,n.maxBufferHole);this._tryFixBufferStall(m,p)}_tryFixBufferStall(e,t){let{config:n,fragmentTracker:r,media:i}=this;if(i===null)return;let a=i.currentTime,o=r.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>n.maxBufferHole||e.nextStart&&e.nextStart-a<n.maxBufferHole)&&t>n.highBufferWatchdogPeriod*1e3&&(y.warn(`Trying to nudge playhead over buffer-hole`),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){let{hls:t,media:n,stallReported:r}=this;if(!r&&n){this.stallReported=!0;let r=Error(`Playback stalling at @${n.currentTime} due to low buffer (${JSON.stringify(e)})`);y.warn(r.message),t.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}
7_trySkipBufferHole(e){let{config:t,hls:n,media:r}=this;if(r===null)return 0;let i=r.currentTime,a=K.bufferInfo(r,i,0),o=i<a.start?a.start:a.nextStart;if(o){let s=a.len<=t.maxBufferHole,c=a.len>0&&a.len<1&&r.readyState<3,l=o-i;if(l>0&&(s||c)){if(l>t.maxBufferHole){let{fragmentTracker:t}=this,n=!1;if(i===0){let e=t.getAppendedFrag(0,B.MAIN);e&&o<e.end&&(n=!0)}if(!n){let n=e||t.getAppendedFrag(i,B.MAIN);if(n){let e=!1,r=n.end;for(;r<o;){let n=t.getPartialFragment(r);if(n)r+=n.duration;else{e=!0;break}}if(e)return 0}}}let a=Math.max(o+Mi,i+ji);if(y.warn(`skipping hole, adjusting currentTime from ${i} to ${a}`),this.moved=!0,this.stalled=null,r.currentTime=a,e&&!e.gap){let t=Error(`fragment loaded with buffer holes, seeking from ${i} to ${a}`);n.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:t,reason:t.message,frag:e})}return a}}return 0}_tryNudgeBuffer(){let{config:e,hls:t,media:n,nudgeRetry:r}=this;if(n===null)return;let i=n.currentTime;if(this.nudgeRetry++,r<e.nudgeMaxRetry){let a=i+(r+1)*e.nudgeOffset,o=Error(`Nudging 'currentTime' from ${i} to ${a}`);y.warn(o.message),n.currentTime=a,t.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{let n=Error(`Playhead still not moving while enough data buffered @${i} after ${e.nudgeMaxRetry} nudges`);y.error(n.message),t.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.BUFFER_STALLED_ERROR,error:n,fatal:!0})}}},Pi=100,Fi=class extends ir{constructor(e,t,n){super(e,t,n,`[stream-controller]`,B.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(u.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(u.MANIFEST_LOADING,this.onManifestLoading,this),e.on(u.MANIFEST_PARSED,this.onManifestParsed,this),e.on(u.LEVEL_LOADING,this.onLevelLoading,this),e.on(u.LEVEL_LOADED,this.onLevelLoaded,this),e.on(u.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(u.ERROR,this.onError,this),e.on(u.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(u.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(u.BUFFER_CREATED,this.onBufferCreated,this),e.on(u.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(u.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(u.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(u.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(u.MANIFEST_LOADING,this.onManifestLoading,this),e.off(u.MANIFEST_PARSED,this.onManifestParsed,this),e.off(u.LEVEL_LOADED,this.onLevelLoaded,this),e.off(u.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(u.ERROR,this.onError,this),e.off(u.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(u.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(u.BUFFER_CREATED,this.onBufferCreated,this),e.off(u.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(u.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(u.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),this.onMediaDetaching()}startLoad(e){if(this.levels){let{lastCurrentTime:t,hls:n}=this;if(this.stopLoad(),this.setInterval(Pi),this.level=-1,!this.startFragRequested){let e=n.startLevel;e===-1&&(n.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=n.nextAutoLevel),this.level=n.nextLoadLevel=e,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=q.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=q.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case q.WAITING_LEVEL:{let{levels:e,level:t}=this,n=e?.[t]?.details;if(n&&(!n.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(n))break;this.state=q.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=q.IDLE;break}break}case q.FRAG_LOADING_WAITING_RETRY:{var e;let t=self.performance.now(),n=this.retryDate;(!n||t>=n||(e=this.media)!=null&&e.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=q.IDLE)}}this.state===q.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:n,media:r}=this,{config:i,nextLoadLevel:a}=e;if(t===null||!r&&(this.startFragRequested||!i.startFragPrefetch)||this.altAudio&&this.audioOnly||!(n!=null&&n[a]))return;let o=n[a],s=this.getMainFwdBufferInfo();if(s===null)return;let c=this.getLevelDetails();if(c&&this._streamEnded(s,c)){let e={};this.altAudio&&(e.type=`video`),this.hls.trigger(u.BUFFER_EOS,e),this.state=q.ENDED;return}e.loadLevel!==a&&e.manualLevel===-1&&this.log(`Adapting to level ${a} from level ${this.level}`),this.level=e.nextLoadLevel=a;let l=o.details;if(!l||this.state===q.WAITING_LEVEL||l.live&&this.levelLastLoaded!==a){this.level=a,this.state=q.WAITING_LEVEL;return}let d=s.len,f=this.getMaxBufferLength(o.maxBitrate);if(d>=f)return;this.backtrackFragment&&this.backtrackFragment.start>s.end&&(this.backtrackFragment=null);let p=this.backtrackFragment?this.backtrackFragment.start:s.end,m=this.getNextFragment(p,l);if(this.couldBacktrack&&!this.fragPrevious&&m&&m.sn!==`initSegment`&&this.fragmentTracker.getState(m)!==W.OK){let e=(this.backtrackFragment??m).sn-l.startSN,t=l.fragments[e-1];t&&m.cc===t.cc&&(m=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=null);if(m&&this.isLoopLoading(m,p)){if(!m.gap){let e=this.audioOnly&&!this.altAudio?D.AUDIO:D.VIDEO,t=(e===D.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,B.MAIN)}m=this.getNextFragmentLoopLoading(m,l,s,B.MAIN,f)}m&&(m.initSegment&&!m.initSegment.data&&!this.bitrateTest&&(m=m.initSegment),this.loadFragment(m,o,p))}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);this.fragCurrent=e,r===W.NOT_LOADED||r===W.PARTIAL?e.sn===`initSegment`?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,n)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,B.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,1/0)}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let n,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let i=this.getLevelDetails();if(i!=null&&i.live){let e=this.getMainFwdBufferInfo();if(!e||e.len<i.targetduration*2)return}if(!t.paused&&e){let t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;n=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else n=0;let a=this.getBufferedFrag(t.currentTime+n);if(a){let e=this.followingBufferedFrag(a);if(e){this.abortCurrentFrag();let t=e.maxStartPTS?e.maxStartPTS:e.start,n=e.duration,r=Math.max(a.end,t+Math.min(Math.max(n-this.config.maxFragLookUpTolerance,n*.5),n*.75));this.flushMainBuffer(r,1/0)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case q.KEY_LOADING:case q.FRAG_LOADING:case q.FRAG_LOADING_WAITING_RETRY:case q.PARSING:case q.PARSED:this.state=q.IDLE}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?`video`:null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let n=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),n.addEventListener(`playing`,this.onvplaying),n.addEventListener(`seeked`,this.onvseeked),this.gapController=new Ni(this.config,n,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(),null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){let e=this.media,t=e?e.currentTime:null;l(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);let n=this.getMainFwdBufferInfo();if(n===null||n.len===0){this.warn(`Main forward buffer length on "seeked" event ${n?n.len:`empty`})`);return}this.tick()}onManifestLoading(){this.log(`Trigger BUFFER_RESET`),this.hls.trigger(u.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 n=!1,r=!1,i;
7t.levels.forEach(e=>{i=e.audioCodec,i&&(i.indexOf(`mp4a.40.2`)!==-1&&(n=!0),i.indexOf(`mp4a.40.5`)!==-1&&(r=!0))}),this.audioCodecSwitch=n&&r&&!sr(),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:n}=this;if(!n||this.state!==q.IDLE)return;let r=n[t.level];(!r.details||r.details.live&&this.levelLastLoaded!==t.level||this.waitForCdnTuneIn(r.details))&&(this.state=q.WAITING_LEVEL)}onLevelLoaded(e,t){var n;let{levels:r}=this,i=t.level,a=t.details,o=a.totalduration;if(!r){this.warn(`Levels were reset while loading level ${i}`);return}this.log(`Level ${i} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:``}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);let s=r[i],c=this.fragCurrent;c&&(this.state===q.FRAG_LOADING||this.state===q.FRAG_LOADING_WAITING_RETRY)&&(c.level!==t.level||c.urlId!==s.urlId)&&c.loader&&this.abortCurrentFrag();let l=0;if(a.live||(n=s.details)!=null&&n.live){if(a.fragments[0]||(a.deltaUpdateFailed=!0),a.deltaUpdateFailed)return;l=this.alignPlaylists(a,s.details)}if(s.details=a,this.levelLastLoaded=i,this.hls.trigger(u.LEVEL_UPDATED,{details:a,level:i}),this.state===q.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=q.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,l),this.tick()}_handleFragmentLoadProgress(e){let{frag:t,part:n,payload:r}=e,{levels:i}=this;if(!i){this.warn(`Levels were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);return}let a=i[t.level],o=a.details;if(!o){this.warn(`Dropping fragment ${t.sn} of level ${t.level} after level details were reset`),this.fragmentTracker.removeFragment(t);return}let s=a.videoCodec,c=o.PTSKnown||!o.live,l=t.initSegment?.data,u=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new Oi(this.hls,B.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=f!==-1,m=new Bn(t.level,t.sn,t.stats.chunkCount,r.byteLength,f,p),h=this.initPTS[t.cc];d.push(r,l,u,s,t,n,o.totalduration,c,m,h)}onAudioTrackSwitching(e,t){let n=this.altAudio;if(!t.url){if(this.mediaBuffer!==this.media){this.log(`Switching on main audio, use media.buffered to schedule main fragment loading`),this.mediaBuffer=this.media;let e=this.fragCurrent;e&&(this.log(`Switching to main audio track, cancel main fragment load`),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();let e=this.hls;n&&(e.trigger(u.BUFFER_FLUSHING,{startOffset:0,endOffset:1/0,type:null}),this.fragmentTracker.removeAllFragments()),e.trigger(u.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let n=t.id,r=!!this.hls.audioTracks[n].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 n=t.tracks,r,i,a=!1;for(let e in n){let t=n[e];if(t.id===`main`){if(i=e,r=t,e===`video`){let t=n[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:n,part:r}=t;if(n&&n.type!==B.MAIN)return;if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===q.PARSED&&(this.state=q.IDLE);return}let i=r?r.stats:n.stats;this.fragLastKbps=Math.round(8*i.total/(i.buffering.end-i.loading.first)),n.sn!==`initSegment`&&(this.fragPrevious=n),this.fragBufferedComplete(n,r)}onError(e,t){if(t.fatal){this.state=q.ERROR;return}switch(t.details){case f.FRAG_GAP:case f.FRAG_PARSING_ERROR:case f.FRAG_DECRYPT_ERROR:case f.FRAG_LOAD_ERROR:case f.FRAG_LOAD_TIMEOUT:case f.KEY_LOAD_ERROR:case f.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(B.MAIN,t);break;case f.LEVEL_LOAD_ERROR:case f.LEVEL_LOAD_TIMEOUT:case f.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===q.WAITING_LEVEL&&t.context?.type===z.LEVEL&&(this.state=q.IDLE);break;case f.BUFFER_FULL_ERROR:if(!t.parent||t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,1/0);break;case f.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}
7checkBuffer(){let{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!K.getBuffered(e).length){let e=this.state===q.IDLE?null:this.fragCurrent;t.poll(this.lastCurrentTime,e)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=q.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==D.AUDIO||this.audioOnly&&!this.altAudio){let e=(t===D.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(e,t,B.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,n=this.startPosition;if(n>=0&&t<n){if(e.seeking){this.log(`could not seek to ${n}, already seeking at ${t}`);return}let r=K.getBuffered(e),i=(r.length?r.start(0):0)-n;i>0&&(i<this.config.maxBufferHole||i<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${i} to match buffer start`),n+=i,this.startPosition=n),this.log(`seek to target start position ${n} from current time ${t}`),e.currentTime=n}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log(`Swapping audio codec`),t=t.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(n=>{let{hls:r}=this;if(!n||this.fragContextChanged(e))return;t.fragmentError=0,this.state=q.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let i=e.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),r.trigger(u.FRAG_LOADED,n),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;let n=`main`,{hls:r}=this,{remuxResult:i,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:s,part:c,level:d}=o,{video:f,text:p,id3:m,initSegment:h}=i,{details:g}=d,_=this.altAudio?void 0:i.audio;if(this.fragContextChanged(s)){this.fragmentTracker.removeFragment(s);return}if(this.state=q.PARSING,h){if(h!=null&&h.tracks){let e=s.initSegment||s;this._bufferInitSegment(d,h.tracks,e,a),r.trigger(u.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:h.tracks})}let e=h.initPTS,t=h.timescale;l(e)&&(this.initPTS[s.cc]={baseTime:e,timescale:t},r.trigger(u.INIT_PTS_FOUND,{frag:s,id:n,initPTS:e,timescale:t}))}if(f&&g&&s.sn!==`initSegment`){let e=g.fragments[s.sn-1-g.startSN],t=s.sn===g.startSN,n=!e||s.cc>e.cc;if(i.independent!==!1){let{startPTS:e,endPTS:r,startDTS:i,endDTS:o}=f;if(c)c.elementaryStreams[f.type]={startPTS:e,endPTS:r,startDTS:i,endDTS:o};else if(f.firstKeyFrame&&f.independent&&a.id===1&&!n&&(this.couldBacktrack=!0),f.dropped&&f.independent){let i=this.getMainFwdBufferInfo(),a=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,c=f.firstKeyFramePTS?f.firstKeyFramePTS:e;if(!t&&a<c-this.config.maxBufferHole&&!n){this.backtrack(s);return}n&&(s.gap=!0),s.setElementaryStreamInfo(f.type,s.start,r,s.start,o,!0)}s.setElementaryStreamInfo(f.type,e,r,i,o),this.backtrackFragment&&=s,this.bufferFragmentData(f,s,c,a,t||n)}else if(t||n)s.gap=!0;else{this.backtrack(s);return}}if(_){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=_;c&&(c.elementaryStreams[D.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),s.setElementaryStreamInfo(D.AUDIO,e,t,n,r),this.bufferFragmentData(_,s,c,a)}if(g&&m!=null&&(t=m.samples)!=null&&t.length){let e={id:n,frag:s,details:g,samples:m.samples};r.trigger(u.FRAG_PARSING_METADATA,e)}if(g&&p){let e={id:n,frag:s,details:g,samples:p.samples};r.trigger(u.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,n,r){if(this.state!==q.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;let{audio:i,video:a,audiovideo:o}=t;if(i){let t=e.audioCodec,n=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(t&&=t.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`,i.metadata.channelCount!==1&&n.indexOf(`firefox`)===-1&&(t=`mp4a.40.5`)),n.indexOf(`android`)!==-1&&i.container!==`audio/mpeg`&&(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}"`),i.levelCodec=t,i.id=`main`,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${t||``}/${e.audioCodec||``}
7/${i.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id=`main`,this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||``}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.attrs.CODECS||``}/${o.codec}]`),this.hls.trigger(u.BUFFER_CODECS,t),Object.keys(t).forEach(e=>{let i=t[e].initSegment;i!=null&&i.byteLength&&this.hls.trigger(u.BUFFER_APPENDING,{type:e,data:i,frag:n,part:null,chunkMeta:r,parent:n.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,B.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=q.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let n=e.currentTime;if(K.isBuffered(e,n)?t=this.getAppendedFrag(n):K.isBuffered(e,n+.1)&&(t=this.getAppendedFrag(n+.1)),t){this.backtrackFragment=null;let e=this.fragPlaying,n=t.level;(!e||t.sn!==e.sn||e.level!==n||t.urlId!==e.urlId)&&(this.fragPlaying=t,this.hls.trigger(u.FRAG_CHANGED,{frag:t}),(!e||e.level!==n)&&this.hls.trigger(u.LEVEL_SWITCHED,{level:n}))}}}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,n=this.currentFrag;if(n&&l(t)&&l(n.programDateTime)){let e=n.programDateTime+(t-n.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}},Ii=class{constructor(e,t=0,n=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_=n}sample(e,t){let n=this.alpha_**+e;this.estimate_=t*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-this.alpha_**+this.totalWeight_;if(e)return this.estimate_/e}return this.estimate_}},Li=class{constructor(e,t,n,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_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_
7=new Ii(e),this.fast_=new Ii(t),this.defaultTTFB_=r,this.ttfb_=new Ii(e)}update(e,t){let{slow_:n,fast_:r,ttfb_:i}=this;n.halfLife!==e&&(this.slow_=new Ii(e,n.getEstimate(),n.getTotalWeight())),r.halfLife!==t&&(this.fast_=new Ii(t,r.getEstimate(),r.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new Ii(e,i.getEstimate(),i.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);let n=8*t,r=e/1e3,i=n/r;this.fast_.sample(r,i),this.slow_.sample(r,i)}sampleTTFB(e){let t=e/1e3,n=Math.sqrt(2)*Math.exp(-(t**2)/2);this.ttfb_.sample(n,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(){}},Ri=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 Li(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(u.FRAG_LOADING,this.onFragLoading,this),e.on(u.FRAG_LOADED,this.onFragLoaded,this),e.on(u.FRAG_BUFFERED,this.onFragBuffered,this),e.on(u.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(u.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){let{hls:e}=this;e.off(u.FRAG_LOADING,this.onFragLoading,this),e.off(u.FRAG_LOADED,this.onFragLoaded,this),e.off(u.FRAG_BUFFERED,this.onFragBuffered,this),e.off(u.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(u.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(e,t){let n=t.frag;this.ignoreFragment(n)||(this.fragCurrent=n,this.partCurrent=t.part??null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(e,t){this.clearTimer()}getTimeToLoadFrag(e,t,n,r){return e+n/t+(r?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){let n=this.hls.config,{total:r,bwEstimate:i}=t.stats;l(r)&&l(i)&&(this.lastLevelLoadSec=8*r/i),t.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD)}_abandonRulesCheck(){let{fragCurrent:e,partCurrent:t,hls:n}=this,{autoLevelEnabled:r,media:i}=n;if(!e||!i)return;let a=performance.now(),o=t?t.stats:e.stats,s=t?t.duration:e.duration,c=a-o.loading.start;if(o.aborted||o.loaded&&o.loaded===o.total||e.level===0){this.clearTimer(),this._nextAutoLevel=-1;return}if(!r||i.paused||!i.playbackRate||!i.readyState)return;let d=n.mainForwardBufferInfo;if(d===null)return;let f=this.bwEstimator.getEstimateTTFB(),p=Math.abs(i.playbackRate);if(c<=Math.max(f,1e3*(s/(p*2))))return;let m=d.len/p;if(m>=2*s/p)return;let h=o.loading.first?o.loading.first-o.loading.start:-1,g=o.loaded&&h>-1,_=this.bwEstimator.getEstimate(),{levels:v,minAutoLevel:b}=n,x=v[e.level],S=o.total||Math.max(o.loaded,Math.round(s*x.maxBitrate/8)),C=c-h;C<1&&g&&(C=Math.min(c,o.loaded*8/_));let w=g?o.loaded*1e3/C:0,T=w?(S-o.loaded)/w:S*8/_+f/1e3;if(T<=m)return;let E=w?w*8:_,D=1/0,O;for(O=e.level-1;O>b;O--){let e=v[O].maxBitrate;if(D=this.getTimeToLoadFrag(f/1e3,E,s*e,!v[O].details),D<m)break}D>=T||D>s*10||(n.nextLoadLevel=O,g?this.bwEstimator.sample(c-Math.min(f,h),o.loaded):this.bwEstimator.sampleTTFB(c),this.clearTimer(),y.warn(`[abr] Fragment ${e.sn}${t?` part `+t.index:``} of level ${e.level} is loading too slowly;
8      Time to underbuffer: ${m.toFixed(3)} s
9      Estimated load time for current fragment: ${T.toFixed(3)} s
10      Estimated load time for down switch fragment: ${D.toFixed(3)} s
11      TTFB estimate: ${h}
12      Current BW estimate: ${l(_)?(_/1024).toFixed(3):`Unknown`} Kb/s
13      New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s
14      Aborting and switching to level ${O}`),e.loader&&(this.fragCurrent=this.partCurrent=null,e.abortRequests()),n.trigger(u.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:t,stats:o}))}onFragLoaded(e,{frag:t,part:n}){let r=n?n.stats:t.stats;if(t.type===B.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=n?n.duration:t.duration,i=this.hls.levels[t.level],a=(i.loaded?i.loaded.bytes:0)+r.loaded,o=(i.loaded?i.loaded.duration:0)+e;i.loaded={bytes:a,duration:o},i.realBitrate=Math.round(8*a/o)}if(t.bitrateTest){let e={stats:r,frag:t,part:n,id:t.type};this.onFragBuffered(u.FRAG_BUFFERED,e),t.bitrateTest=!1}}}onFragBuffered(e,t){let{frag:n,part:r}=t,i=r!=null&&r.stats.loaded?r.stats:n.stats;if(i.aborted||this.ignoreFragment(n))return;let a=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,i.loaded),i.bwEstimate=this.bwEstimator.getEstimate(),this.bitrateTestDelay=n.bitrateTest?a/1e3:0}ignoreFragment(e){return e.type!==B.MAIN||e.sn===`initSegment`}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){let e=this._nextAutoLevel,t=this.bwEstimator;if(e!==-1&&!t.canEstimate())return e;let n=this.getNextABRAutoLevel();if(e!==-1){let t=this.hls.levels;if(t.length>Math.max(e,n)&&t[e].loadError<=t[n].loadError)return e}return e!==-1&&(n=Math.min(e,n)),n}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:n}=this,{maxAutoLevel:r,config:i,minAutoLevel:a,media:o}
14=n,s=t?t.duration:e?e.duration:0,c=o&&o.playbackRate!==0?Math.abs(o.playbackRate):1,l=this.bwEstimator?this.bwEstimator.getEstimate():i.abrEwmaDefaultEstimate,u=n.mainForwardBufferInfo,d=(u?u.len:0)/c,f=this.findBestLevel(l,a,r,d,i.abrBandWidthFactor,i.abrBandWidthUpFactor);if(f>=0)return f;y.trace(`[abr] ${d?`rebuffering expected`:`buffer is empty`}, finding optimal quality level`);let p=s?Math.min(s,i.maxStarvationDelay):i.maxStarvationDelay,m=i.abrBandWidthFactor,h=i.abrBandWidthUpFactor;if(!d){let e=this.bitrateTestDelay;e&&(p=(s?Math.min(s,i.maxLoadingDelay):i.maxLoadingDelay)-e,y.trace(`[abr] bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*p)} ms`),m=h=1)}return f=this.findBestLevel(l,a,r,d+p,m,h),Math.max(f,0)}findBestLevel(e,t,n,r,i,a){var o;let{fragCurrent:s,partCurrent:c,lastLoadedFragLevel:u}=this,{levels:d}=this.hls,f=d[u],p=!!(f!=null&&(o=f.details)!=null&&o.live),m=f?.codecSet,h=c?c.duration:s?s.duration:0,g=this.bwEstimator.getEstimateTTFB()/1e3,_=t,v=-1;for(let o=n;o>=t;o--){let t=d[o];if(!t||m&&t.codecSet!==m){t&&(_=Math.min(o,_),v=Math.max(o,v));continue}v!==-1&&y.trace(`[abr] Skipped level(s) ${_}-${v} with CODECS:"${d[v].attrs.CODECS}"; not compatible with "${f.attrs.CODECS}"`);let n=t.details,s=(c?n?.partTarget:n?.averagetargetduration)||h,b;b=o<=u?i*e:a*e;let x=d[o].maxBitrate,S=this.getTimeToLoadFrag(g,b,x*s,n===void 0);if(y.trace(`[abr] level:${o} adjustedbw-bitrate:${Math.round(b-x)} avgDuration:${s.toFixed(1)} maxFetchDuration:${r.toFixed(1)} fetchDuration:${S.toFixed(1)}`),b>x&&(S===0||!l(S)||p&&!this.bitrateTestDelay||S<r))return o}return-1}set nextAutoLevel(e){this._nextAutoLevel=e}},zi=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,n;if(e.length)n=e.length===1?e[0]:Bi(e,t);else return new Uint8Array;return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}};function Bi(e,t){let n=new Uint8Array(t),r=0;for(let t=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}var Vi=100,Hi=class extends ir{constructor(e,t,n){super(e,t,n,`[audio-stream-controller]`,B.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;
14e.on(u.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(u.MANIFEST_LOADING,this.onManifestLoading,this),e.on(u.LEVEL_LOADED,this.onLevelLoaded,this),e.on(u.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(u.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(u.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(u.ERROR,this.onError,this),e.on(u.BUFFER_RESET,this.onBufferReset,this),e.on(u.BUFFER_CREATED,this.onBufferCreated,this),e.on(u.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(u.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(u.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(u.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(u.MANIFEST_LOADING,this.onManifestLoading,this),e.off(u.LEVEL_LOADED,this.onLevelLoaded,this),e.off(u.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(u.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(u.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(u.ERROR,this.onError,this),e.off(u.BUFFER_RESET,this.onBufferReset,this),e.off(u.BUFFER_CREATED,this.onBufferCreated,this),e.off(u.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(u.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(u.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:i}){if(n===`main`){let e=t.cc;this.initPTS[t.cc]={baseTime:r,timescale:i},this.log(`InitPTS for cc: ${e} found from main: ${r}`),this.videoTrackCC=e,this.state===q.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=q.STOPPED;return}let t=this.lastCurrentTime;this.stopLoad(),this.setInterval(Vi),t>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=q.IDLE):(this.loadedmetadata=!1,this.state=q.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case q.IDLE:this.doTickIdle();break;case q.WAITING_TRACK:{let{levels:e,trackId:t}=this,n=e?.[t]?.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=q.WAITING_INIT_PTS}break}case q.FRAG_LOADING_WAITING_RETRY:{var e;let t=performance.now(),n=this.retryDate;(!n||t>=n||(e=this.media)!=null&&e.seeking)&&(this.log(`RetryDate reached, switch back to IDLE state`),this.resetStartWhenNotLoaded(this.trackId),this.state=q.IDLE);break}case q.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:n,cache:r,complete:i}=e;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=q.FRAG_LOADING;let e={frag:t,part:n,payload:r.flush(),networkDetails:null};this._handleFragmentLoadProgress(e),i&&super._handleFragmentLoadComplete(e)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${t.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{let e=this.getLoadPosition(),n=K.bufferInfo(this.mediaBuffer,e,this.config.maxBufferHole);yn(n.end,this.config.maxFragLookUpTolerance,t)<0&&(this.log(`Waiting fragment cc (${t.cc}) @ ${t.start} cancelled because another fragment at ${n.end} is needed`),this.clearWaitingFragment())}}else this.state=q.IDLE}}this.onTickEnd()}clearWaitingFragment(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=q.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){let{hls:e,levels:t,media:n,trackId:r}=this,i=e.config;if(!(t!=null&&t[r])||!n&&(this.startFragRequested||!i.startFragPrefetch))return;let a=t[r],o=a.details;if(!o||o.live&&this.levelLastLoaded!==r||this.waitForCdnTuneIn(o)){this.state=q.WAITING_TRACK;return}let s=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&s&&(this.bufferFlushed=!1,this.afterBufferFlushed(s,D.AUDIO,B.AUDIO));let c=this.getFwdBufferInfo(s,B.AUDIO);if(c===null)return;let{bufferedTrack:l,switchingTrack:d}=this;if(!d&&this._streamEnded(c,o)){e.trigger(u.BUFFER_EOS,{type:`audio`}),this.state=q.ENDED;return}let f=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,B.MAIN),p=c.len,m=this.getMaxBufferLength(f?.len);if(p>=m&&!d)return;let h=o.fragments[0].start,g=c.end;if(d&&n){let e=this.getLoadPosition();l&&d.attrs!==l.attrs&&(g=e),o.PTSKnown&&e<h&&(c.end>h||c.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track`),n.currentTime=h+.
1405)}let _=this.getNextFragment(g,o),v=!1;if(_&&this.isLoopLoading(_,g)&&(v=!!_.gap,_=this.getNextFragmentLoopLoading(_,o,c,B.MAIN,m)),!_){this.bufferFlushed=!0;return}let y=f&&_.start>f.end+o.targetduration;if(y||!(f!=null&&f.len)&&c.len){let e=this.getAppendedFrag(_.start,B.MAIN);if(e===null||(v||=!!e.gap||!!y&&f.len===0,y&&!v||v&&c.nextStart&&c.nextStart<e.end))return}this.loadFragment(_,a,g)}getMaxBufferLength(e){let t=super.getMaxBufferLength();return 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 Xt(e))}onAudioTrackSwitching(e,t){let n=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),n?this.setInterval(Vi):this.resetTransmuxer(),n?(this.switchingTrack=t,this.state=q.IDLE):(this.switchingTrack=null,this.bufferedTrack=t,this.state=q.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,this.cachedTrackLoadedData!==null&&(this.hls.trigger(u.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var n;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}let{levels:r}=this,{details:i,id:a}=t;if(!r){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Track ${a} loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:``},duration:${i.totalduration}`);let o=r[a],s=0;if(i.live||(n=o.details)!=null&&n.live){let e=this.mainDetails;if(i.fragments[0]||(i.deltaUpdateFailed=!0),i.deltaUpdateFailed||!e)return;!o.details&&i.hasProgramDateTime&&e.hasProgramDateTime?(Xn(i,e),s=i.fragments[0].start):s=this.alignPlaylists(i,o.details)}o.details=i,this.levelLastLoaded=a,!this.startFragRequested&&(this.mainDetails||!i.live)&&this.setStartPosition(o.details,s),this.state===q.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=q.IDLE),this.tick()}_handleFragmentLoadProgress(e){let{frag:t,part:n,payload:r}
14=e,{config:i,trackId:a,levels:o}=this;if(!o){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);return}let s=o[a];if(!s){this.warn(`Audio track is undefined on fragment load progress`);return}let c=s.details;if(!c){this.warn(`Audio track details undefined on fragment load progress`),this.removeUnbufferedFrags(t.start);return}let l=i.defaultAudioCodec||s.audioCodec||`mp4a.40.2`,u=this.transmuxer;u||=this.transmuxer=new Oi(this.hls,B.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this));let d=this.initPTS[t.cc],f=t.initSegment?.data;if(d!==void 0){let e=n?n.index:-1,i=e!==-1,a=new Bn(t.level,t.sn,t.stats.chunkCount,r.byteLength,e,i);u.push(r,f,l,``,t,n,c.totalduration,!1,a,d)}else{this.log(`Unknown video PTS for cc ${t.cc}, waiting for video PTS before demuxing audio frag ${t.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);let{cache:e}=this.waitingData=this.waitingData||{frag:t,part:n,cache:new zi,complete:!1};e.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=q.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 n=t.tracks.audio;n&&(this.mediaBuffer=n.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){let{frag:n,part:r}=t;if(n.type!==B.AUDIO){if(!this.loadedmetadata&&n.type===B.MAIN){let e=this.videoBuffer||this.media;e&&K.getBuffered(e).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:`false`}`);return}if(n.sn!==`initSegment`){this.fragPrevious=n;let e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(u.AUDIO_TRACK_SWITCHED,i({},e)))}this.fragBufferedComplete(n,r)}onError(e,t){if(t.fatal){this.state=q.ERROR;return}switch(t.details){case f.FRAG_GAP:case f.FRAG_PARSING_ERROR:case f.FRAG_DECRYPT_ERROR:case f.FRAG_LOAD_ERROR:case f.FRAG_LOAD_TIMEOUT:case f.KEY_LOAD_ERROR:case f.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(B.AUDIO,t);break;case f.AUDIO_TRACK_LOAD_ERROR:case f.AUDIO_TRACK_LOAD_TIMEOUT:case f.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===q.WAITING_TRACK&&t.context?.type===z.AUDIO_TRACK&&(this.state=q.IDLE);break;case f.BUFFER_FULL_ERROR:if(!t.parent||t.parent!==`audio`)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,1/0,`audio`));break;case f.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushed(e,{type:t}){t===D.AUDIO&&(this.bufferFlushed=!0,this.state===q.ENDED&&(this.state=q.IDLE))}_handleTransmuxComplete(e){var t;let n=`audio`,{hls:r}=this,{remuxResult:i,chunkMeta:a}=e,s=this.getCurrentContext(a);if(!s){this.resetWhenMissingContext(a);return}let{frag:c,part:l,level:d}=s,{details:f}=d,{audio:p,text:m,id3:h,initSegment:g}=i;if(this.fragContextChanged(c)||!f){this.fragmentTracker.removeFragment(c);return}if(this.state=q.PARSING,this.switchingTrack&&p&&this.completeAudioSwitch(this.switchingTrack),g!=null&&g.tracks){let e=c.initSegment||c;this._bufferInitSegment(g.tracks,e,a),r.trigger(u.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:g.tracks})}if(p){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=p;l&&(l.elementaryStreams[D.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),c.setElementaryStreamInfo(D.AUDIO,e,t,n,r),this.bufferFragmentData(p,c,l,a)}if(h!=null&&(t=h.samples)!=null&&t.length){let e=o({id:n,frag:c,details:f},h);r.trigger(u.FRAG_PARSING_METADATA,e)}if(m){let e=o({id:n,frag:c,details:f},m);r.trigger(u.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,n){if(this.state!==q.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(u.BUFFER_CODECS,e);let i=r.initSegment;if(i!=null&&i.byteLength){let e={type:`audio`,frag:t,part:null,chunkMeta:n,parent:t.type,data:i};this.hls.trigger(u.BUFFER_APPENDING,e)}this.tick()}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||r===W.NOT_LOADED||r===W.PARTIAL){var i;e.sn===`initSegment`?this._loadInitSegment(e,t):(i=t.details)!=null&&i.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=q.WAITING_INIT_PTS):(this.startFragRequested=!0,super.loadFragment(e,t,n))}else this.clearTrackerIfNeeded(e)}completeAudioSwitch(e){let{hls:t,media:n,bufferedTrack:r}=this,a=r?.attrs,o=e.attrs;
14n&&a&&(a.CHANNELS!==o.CHANNELS||a.NAME!==o.NAME||a.LANGUAGE!==o.LANGUAGE)&&(this.log(`Switching audio track : flushing all audio`),super.flushMainBuffer(0,1/0,`audio`)),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(u.AUDIO_TRACK_SWITCHED,i({},e))}},Ui=class extends Tn{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(u.MANIFEST_LOADING,this.onManifestLoading,this),e.on(u.MANIFEST_PARSED,this.onManifestParsed,this),e.on(u.LEVEL_LOADING,this.onLevelLoading,this),e.on(u.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(u.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(u.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(u.MANIFEST_LOADING,this.onManifestLoading,this),e.off(u.MANIFEST_PARSED,this.onManifestParsed,this),e.off(u.LEVEL_LOADING,this.onLevelLoading,this),e.off(u.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(u.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(u.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:n,groupId:r,details:i}=t,a=this.tracksInGroup[n];if(!a||a.groupId!==r){this.warn(`Track with id:${n} and group:${r} not found in active group ${a.groupId}`);return}let o=a.details;a.details=t.details,this.log(`audio-track ${n} "${a.name}" lang:${a.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!(t!=null&&t.audioGroupIds))return;let n=t.audioGroupIds[t.urlId];if(this.groupId!==n){this.groupId=n||null;let e=this.tracks.filter(e=>!n||e.groupId===n);this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=e;let t={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group:${n}`),this.hls.trigger(u.AUDIO_TRACKS_UPDATED,t),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||t.context.type===z.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 n=this.currentTrack;t[this.trackId];let r=t[e],{groupId:a,name:o}=r;if(this.log(`Switching to audio-track ${e} "${o}" lang:${r.lang} group:${a}`),this.trackId=e,this.currentTrack=r,this.selectDefaultTrack=!1,this.hls.trigger(u.AUDIO_TRACK_SWITCHING,i({},r)),r.details&&!r.details.live)return;let s=this.switchParams(r.url,n?.details);this.loadPlaylist(s)}selectInitialTrack(){let e=this.tracksInGroup,t=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(t!==-1)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(u.ERROR,{type:d.MEDIA_ERROR,details:f.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}findTrackId(e){let t=this.tracksInGroup;for(let n=0;n<t.length;n++){let r=t[n];if((!this.selectDefaultTrack||r.default)&&(!e||e.attrs[`STABLE-RENDITION-ID`]!==void 0&&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 n=t.id,r=t.groupId,i=t.url;if(e)try{i=e.addDirectives(i)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`loading audio-track playlist ${n} "${t.name}" lang:${t.lang} group:${r}`),this.clearTimer(),this.hls.trigger(u.AUDIO_TRACK_LOADING,{url:i,id:n,groupId:r,deliveryDirectives:e||null})}}};function Wi(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Gi(e[n].attrs,t[n].attrs))return!1;return!0}function Gi(e,t){let n=e[`STABLE-RENDITION-ID`];return n?n===t[`STABLE-RENDITION-ID`]:![`LANGUAGE`,`NAME`,`CHARACTERISTICS`,`AUTOSELECT`,`DEFAULT`,`FORCED`].some(n=>e[n]!==t[n])}var Ki=500,qi=class extends ir{constructor(e,t,n){super(e,t,n,`[subtitle-stream-controller]`,B.SUBTITLE),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){let{hls:e}=this;
14e.on(u.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(u.MANIFEST_LOADING,this.onManifestLoading,this),e.on(u.LEVEL_LOADED,this.onLevelLoaded,this),e.on(u.ERROR,this.onError,this),e.on(u.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(u.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(u.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(u.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(u.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(u.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){let{hls:e}=this;e.off(u.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(u.MANIFEST_LOADING,this.onManifestLoading,this),e.off(u.LEVEL_LOADED,this.onLevelLoaded,this),e.off(u.ERROR,this.onError,this),e.off(u.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(u.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(u.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(u.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(u.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(u.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=q.IDLE,this.setInterval(Ki),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{frag:n,success:r}=t;if(this.fragPrevious=n,this.state=q.IDLE,!r)return;let i=this.tracksBuffered[this.currentTrackId];if(!i)return;let a,o=n.start;for(let e=0;e<i.length;e++)if(o>=i[e].start&&o<=i[e].end){a=i[e];break}let s=n.start+n.duration;a?a.end=s:(a={start:o,end:s},i.push(a)),this.fragmentTracker.fragBuffered(n)}onBufferFlushing(e,t){let{startOffset:n,endOffset:r}=t;if(n===0&&r!==1/0){let e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let n=0;n<t.length;){if(t[n].end<=e){t.shift();continue}if(t[n].start<e)t[n].start=e;else break;n++}}),this.fragmentTracker.removeFragmentsInRange(n,e,B.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===B.MAIN){var n;(n=this.media)!=null&&n.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){t.frag?.type===B.SUBTITLE&&(this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==q.STOPPED&&(this.state=q.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(Wi(this.levels,t)){this.levels=t.map(e=>new Xt(e));return}this.tracksBuffered=[],this.levels=t.map(e=>{let t=new Xt(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,1/0,B.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){if(this.currentTrackId=t.id,!this.levels.length||this.currentTrackId===-1){this.clearInterval();return}let n=this.levels[this.currentTrackId];this.mediaBuffer=n!=null&&n.details?this.mediaBufferTimeRanges:null,n&&this.setInterval(Ki)}onSubtitleTrackLoaded(e,t){var n;let{details:r,id:i}=t,{currentTrackId:a,levels:o}=this;if(!o.length)return;let s=o[a];if(i>=o.length||i!==a||!s)return;this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(r.live||(n=s.details)!=null&&n.live){let e=this.mainDetails;if(r.deltaUpdateFailed||!e)return;let t=e.fragments[0];s.details?(c=this.alignPlaylists(r,s.details),c===0&&t&&(c=t.start,an(r,c))):r.hasProgramDateTime&&e.hasProgramDateTime?(Xn(r,e),c=r.fragments[0].start):t&&(c=t.start,an(r,c))}s.details=r,this.levelLastLoaded=i,!this.startFragRequested&&(this.mainDetails||!r.live)&&this.setStartPosition(s.details,c),this.tick(),r.live&&!this.fragCurrent&&this.media&&this.state===q.IDLE&&(vn(null,r.fragments,this.media.currentTime,0)||(this.warn(`Subtitle playlist not aligned with playback`),s.details=void 0))}_handleFragmentLoadComplete(e){let{frag:t,payload:n}=e,r=t.decryptdata,i=this.hls;if(!this.fragContextChanged(t)&&n&&n.byteLength>0&&r&&r.key&&r.iv&&r.method===`AES-128`){let e=performance.now();
14this.decrypter.decrypt(new Uint8Array(n),r.key.buffer,r.iv.buffer).catch(e=>{throw i.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(n=>{let r=performance.now();i.trigger(u.FRAG_DECRYPTED,{frag:t,payload:n,stats:{tstart:e,tdecrypt:r}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=q.IDLE})}}doTick(){if(!this.media){this.state=q.IDLE;return}if(this.state===q.IDLE){let{currentTrackId:e,levels:t}=this,n=t[e];if(!t.length||!n||!n.details)return;let{config:r}=this,i=this.getLoadPosition(),{end:a,len:o}=K.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,r.maxBufferHole),s=this.getFwdBufferInfo(this.media,B.MAIN),c=n.details;if(o>this.getMaxBufferLength(s?.len)+c.levelTargetDuration)return;let l=c.fragments,u=l.length,d=c.edge,f=null,p=this.fragPrevious;if(a<d){let e=r.maxFragLookUpTolerance,t=a>d-e?0:e;f=vn(p,l,Math.max(l[0].start,a),t),!f&&p&&p.start<l[0].start&&(f=l[0])}else f=l[u-1];if(!f)return;if(f=this.mapToInitFragWhenRequired(f),f.sn!==`initSegment`){let e=l[f.sn-c.startSN-1];e&&e.cc===f.cc&&this.fragmentTracker.getState(e)===W.NOT_LOADED&&(f=e)}this.fragmentTracker.getState(f)===W.NOT_LOADED&&this.loadFragment(f,n,a)}}getMaxBufferLength(e){let t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,n){this.fragCurrent=e,e.sn===`initSegment`?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,n))}get mediaBufferTimeRanges(){return new Ji(this.tracksBuffered[this.currentTrackId]||[])}},Ji=class{constructor(e){this.buffered=void 0;let t=(t,n,r)=>{if(n>>>=0,n>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][t]};this.buffered={get length(){return e.length},end(n){return t(`end`,n,e.length)},start(n){return t(`start`,n,e.length)}}}},Yi=class extends Tn{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;
14e.on(u.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(u.MANIFEST_LOADING,this.onManifestLoading,this),e.on(u.MANIFEST_PARSED,this.onManifestParsed,this),e.on(u.LEVEL_LOADING,this.onLevelLoading,this),e.on(u.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(u.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(u.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(u.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(u.MANIFEST_LOADING,this.onManifestLoading,this),e.off(u.MANIFEST_PARSED,this.onManifestParsed,this),e.off(u.LEVEL_LOADING,this.onLevelLoading,this),e.off(u.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(u.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(u.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&`onchange`in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener(`change`,this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,e)}onMediaDetaching(){this.media&&=(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener(`change`,this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Xi(this.media.textTracks).forEac
14h(e=>{Ft(e)}),this.subtitleTrack=-1,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:n,details:r}=t,{trackId:i}=this,a=this.tracksInGroup[i];if(!a){this.warn(`Invalid subtitle track id ${n}`);return}let o=a.details;a.details=t.details,this.log(`subtitle track ${n} loaded [${r.startSN}-${r.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!(t!=null&&t.textGroupIds))return;let n=t.textGroupIds[t.urlId],r=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==n){let e=this.tracks.filter(e=>!n||e.groupId===n);this.tracksInGroup=e;let t=this.findTrackId(r?.name)||this.findTrackId();this.groupId=n||null;let i={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${n}" group-id`),this.hls.trigger(u.SUBTITLE_TRACKS_UPDATED,i),t!==-1&&this.setSubtitleTrack(t,r)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId,r)}findTrackId(e){let t=this.tracksInGroup;for(let n=0;n<t.length;n++){let r=t[n];if((!this.selectDefaultTrack||r.default)&&(!e||e===r.name))return r.id}return-1}onError(e,t){t.fatal||!t.context||t.context.type===z.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 n=t.id,r=t.groupId,i=t.url;if(e)try{i=e.addDirectives(i)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}this.log(`Loading subtitle playlist for id ${n}`),this.hls.trigger(u.SUBTITLE_TRACK_LOADING,{url:i,id:n,groupId:r,deliveryDirectives:e||null})}}toggleTrackModes(e){let{media:t,trackId:n}=this;if(!t)return;let r=Xi(t.textTracks),i=r.filter(e=>e.groupId===this.groupId);if(e===-1)[].slice.call(r).forEach(e=>{e.mode=`disabled`});else{let e=i[n];e&&(e.mode=`disabled`)}let a=i[e];a&&(a.mode=this.subtitleDisplay?`showing`:`hidden`)}setSubtitleTrack(e,t){var n;let r=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(this.trackId!==e&&this.toggleTrackModes(e),this.trackId===e&&(e===-1||(n=r[e])!=null&&n.details)||e<-1||e>=r.length)return;this.clearTimer();let i=r[e];if(this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:``)),this.trackId=e,i){let{id:e,groupId:n=``,name:r,type:a,url:o}=i;this.hls.trigger(u.SUBTITLE_TRACK_SWITCH,{id:e,groupId:n,name:r,type:a,url:o});let s=this.switchParams(i.url,t?.details);this.loadPlaylist(s)}else this.hls.trigger(u.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1,t=Xi(this.media.textTracks);for(let n=0;n<t.length;n++)if(t[n].mode===`hidden`)e=n;else if(t[n].mode===`showing`){e=n;break}this.subtitleTrack!==e&&(this.subtitleTrack=e)}};function Xi(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];(r.kind===`subtitles`||r.kind===`captions`)&&r.label&&t.push(e[n])}return t}var Zi=class{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t){let n=this.queues[t];n.push(e),n.length===1&&this.buffers[t]&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t,n=new Promise(e=>{t=e}),r={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(r,e),n}executeNext(e){let{buffers:t,queues:n}=this,r=t[e],i=n[e];if(i.length){let t=i[0];try{t.execute()}catch(n){y.warn(`[buffer-operation-queue]: Unhandled exception executing the current operation`),t.onError(n),r!=null&&r.updating||(i.shift(),this.executeNext(e))}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}},Qi=dt(),$i=/([ha]vc.)(?:\.[^.,]+)+/,ea=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;y.log(`[buffer-controller]: Media source opened`),e&&(e.removeEventListener(`emptied`,this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(u.MEDIA_ATTA
14CHED,{media:e})),t&&t.removeEventListener(`sourceopen`,this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{y.log(`[buffer-controller]: Media source closed`)},this._onMediaSourceEnded=()=>{y.log(`[buffer-controller]: Media source ended`)},this._onMediaEmptied=()=>{let{media:e,_objectUrl:t}=this;e&&e.src!==t&&y.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(u.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(u.MANIFEST_LOADING,this.onManifestLoading,this),e.on(u.MANIFEST_PARSED,this.onManifestParsed,this),e.on(u.BUFFER_RESET,this.onBufferReset,this),e.on(u.BUFFER_APPENDING,this.onBufferAppending,this),e.on(u.BUFFER_CODECS,this.onBufferCodecs,this),e.on(u.BUFFER_EOS,this.onBufferEos,this),e.on(u.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(u.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(u.FRAG_PARSED,this.onFragParsed,this),e.on(u.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){let{hls:e}=this;
14e.off(u.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(u.MANIFEST_LOADING,this.onManifestLoading,this),e.off(u.MANIFEST_PARSED,this.onManifestParsed,this),e.off(u.BUFFER_RESET,this.onBufferReset,this),e.off(u.BUFFER_APPENDING,this.onBufferAppending,this),e.off(u.BUFFER_CODECS,this.onBufferCodecs,this),e.off(u.BUFFER_EOS,this.onBufferEos,this),e.off(u.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(u.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(u.FRAG_PARSED,this.onFragParsed,this),e.off(u.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Zi(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=n,y.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){let n=this.media=t.media;if(n&&Qi){let e=this.mediaSource=new Qi;e.addEventListener(`sourceopen`,this._onMediaSourceOpen),e.addEventListener(`sourceended`,this._onMediaSourceEnded),e.addEventListener(`sourceclose`,this._onMediaSourceClose),n.src=self.URL.createObjectURL(e),this._objectUrl=n.src,n.addEventListener(`emptied`,this._onMediaEmptied)}}onMediaDetaching(){let{media:e,mediaSource:t,_objectUrl:n}=this;if(t){if(y.log(`[buffer-controller]: media source detaching`),t.readyState===`open`)try{t.endOfStream()}catch(e){y.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),n&&self.URL.revokeObjectURL(n),e.src===n?(e.removeAttribute(`src`),e.load()):y.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(u.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){y.warn(`[buffer-controller]: Failed to reset the ${e} buffer`,t)}}),this._initSourceBuffer()}onBufferCodecs(e,t){let n=this.getSourceBufferTypes().length;Object.keys(t).forEach(e=>{if(n){let n=this.tracks[e];if(n&&typeof n.buffer.changeType==`function`){let{id:r,codec:i,levelCodec:a,container:o,metadata:s}=t[e],c=(n.levelCodec||n.codec).replace($i,`$1`),l=(a||i).replace($i,`$1`);if(c!==l){let t=`${o};codecs=${a||i}`;this.appendChangeType(e,t),y.log(`[buffer-controller]: switching codec ${c} to ${l}`),this.tracks[e]={buffer:n.buffer,codec:i,container:o,levelCodec:a,metadata:s,id:r}}}}else this.pendingTracks[e]=t[e]}),!n&&(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&this.mediaSource.readyState===`open`&&this.checkPendingTracks())}appendChangeType(e,t){let{operationQueue:n}=this;n.append({execute:()=>{let r=this.sourceBuffer[e];r&&(y.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),n.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{y.warn(`[buffer-controller]: Failed to change ${e} SourceBuffer type`,t)}},e)}onBufferAppending(e,t){let{hls:n,operationQueue:r,tracks:i}=this,{data:a,type:o,frag:s,part:c,chunkMeta:l}=t,p=l.buffering[o],m=self.performance.now();p.start=m;let h=s.stats.buffering,g=c?c.stats.buffering:null;h.start===0&&(h.start=m),g&&g.start===0&&(g.start=m);let _=i.audio,v=!1;o===`audio`&&_?.container===`audio/mpeg`&&(v=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);let b=s.start;r.append({execute:()=>{if(p.executeStart=self.performance.now(),v){let e=this.sourceBuffer[o];if(e){let t=b-e.timestampOffset;Math.abs(t)>=.1&&(y.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${b} (delta: ${t}) sn: ${s.sn})`),e.timestampOffset=b)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{let e=self.performance.now();p.executeEnd=p.end=e,h.first===0&&(h.first=e),g&&g.first===0&&(g.first=e);let{sourceBuffer:t}=this,n={};for(let e in t)n[e]=K.getBuffered(t[e]);this.appendError=0,this.hls.trigger(u.BUFFER_APPENDED,{type:o,frag:s,part:c,chunkMeta:l,parent:s.type,timeRanges:n})},onError:e=>{y.error(`[buffer-controller]: Error encountered while trying to append to the ${o} SourceBuffer`,e);let t={type:d.MEDIA_ERROR,parent:s.type,details:f.BUFFER_APPEND_ERROR,frag:s,part:c,chunkMeta:l,error:e,err:e,fatal:!1};e.code===DOMException.QUOTA_EXCEEDED_ERR?t.details=f.BUFFER_FULL_ERROR:(this.appendError++,t.details=f.BUFFER_APPEND_ERROR,this.appendError>
14n.config.appendErrorMaxRetry&&(y.error(`[buffer-controller]: Failed ${n.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),t.fatal=!0)),n.trigger(u.ERROR,t)}},o)}onBufferFlushing(e,t){let{operationQueue:n}=this,r=e=>({execute:this.removeExecutor.bind(this,e,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(u.BUFFER_FLUSHED,{type:e})},onError:t=>{y.warn(`[buffer-controller]: Failed to remove from ${e} SourceBuffer`,t)}});t.type?n.append(r(t.type),t.type):this.getSourceBufferTypes().forEach(e=>{n.append(r(e),e)})}onFragParsed(e,t){let{frag:n,part:r}=t,i=[],a=r?r.elementaryStreams:n.elementaryStreams;a[D.AUDIOVIDEO]?i.push(`audiovideo`):(a[D.AUDIO]&&i.push(`audio`),a[D.VIDEO]&&i.push(`video`)),i.length===0&&y.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(()=>{let e=self.performance.now();n.stats.buffering.end=e,r&&(r.stats.buffering.end=e);let t=r?r.stats:n.stats;this.hls.trigger(u.FRAG_BUFFERED,{frag:n,part:r,stats:t,id:n.type})},i)}onFragChanged(e,t){this.flushBackBuffer()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((e,n)=>{let r=this.sourceBuffer[n];return r&&(!t.type||t.type===n)&&(r.ending=!0,r.ended||(r.ended=!0,y.log(`[buffer-controller]: ${n} sourceBuffer now EOS`))),e&&!!(!r||r.ended)},!0)&&(y.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||e.readyState!==`open`){e&&y.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`);return}y.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:n,sourceBuffer:r}=this;if(!n||t===null)return;let i=this.getSourceBufferTypes();if(!i.length)return;let a=t.live&&e.config.liveBackBufferLength!==null?e.config.liveBackBufferLength:e.config.backBufferLength;if(!l(a)||a<0)return;let o=n.currentTime,s=t.levelTargetDuration,c=Math.max(a,s),d=Math.floor(o/s)*s-c;i.forEach(n=>{let i=r[n];if(i){let r=K.getBuffered(i);if(r.length>0&&d>r.start(0)){if(e.trigger(u.BACK_BUFFER_REACHED,{bufferEnd:d}),t.live)e.trigger(u.LIVE_BACK_BUFFER_REACHED,{bufferEnd:d});else if(i.ended&&r.end(r.length-1)-o<s*2){y.info(`[buffer-controller]: Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}e.trigger(u.BUFFER_FLUSHING,{startOffset:0,endOffset:d,type:n})}}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!==`open`)return;let{details:e,hls:t,media:n,mediaSource:r}=this,i=e.fragments[0].start+e.totalduration,a=n.duration,o=l(r.duration)?r.duration:0;e.live&&t.config.liveDurationInfinity?(y.log(`[buffer-controller]: Media Source duration is set to Infinity`),r.duration=1/0,this.updateSeekableRange(e)):(i>o&&i>a||!l(a))&&(y.log(`[buffer-controller]: Updating Media Source duration to ${i.toFixed(3)}`),r.duration=i)}updateSeekableRange(e){let t=this.mediaSource,n=e.fragments;if(n.length&&e.live&&t!=null&&t.setLiveSeekableRange){let r=Math.max(0,n[0].start),i=Math.max(r,r+e.totalduration);t.setLiveSeekableRange(r,i)}}checkPendingTracks(){let{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:n}=this,r=Object.keys(n).length;if(r&&!e||r===2){this.createSourceBuffers(n),this.pendingTracks={};let e=this.getSourceBufferTypes();if(e.length)this.hls.trigger(u.BUFFER_CREATED,{tracks:this.tracks}),e.forEach(e=>{t.executeNext(e)});else{let e=Error(`could not create source buffer for media codec(s)`);this.hls.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}}createSourceBuffers(e){let{sourceBuffer:t,mediaSource:n}=this;if(!n)throw Error(`createSourceBuffers called when mediaSource was null`);for(let r in e)if(!t[r]){let i=e[r];if(!i)throw Error(`source buffer exists for track ${r}, however track does not`);let a=i.levelCodec||i.codec,o=`${i.container};codecs=${a}`;y.log(`[buffer-controller]: creating sourceBuffer(${o})`);try{let e=t[r]=n.addSourceBuffer(o),s=r;this.addBufferListener(s,`updatestart`,this._onSBUpdateStart),this.addBufferListener(s,`updateend`,this._onSBUpdateEnd),this.addBufferListener(s,`error`,this._onSBUpdateError),this.tracks[r]={buffer:e,codec:a,container:i.container,levelCodec:i.levelCodec,metadata:i.metadata,id:i.id}}catch(e){y.error(`[buffer-controller]: error while trying to add sourceBuffer: ${e.message}`),this.hls.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,mimeType:o})}}}_onSBUpdateStart(e){let{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){let{operationQueue:t}=this;t.current(e).onComplete(),t.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){let n=Error(`${e} SourceBuffer error`);y.error(`[buffer-controller]: ${n}`,t),this.hls.trigger(u.ERROR,{type:d.MEDIA_ERROR,details:f.BUFFER_APPENDING_ERROR,error:n,fatal:!1});let r=this.operationQueue.current(e);r&&r.onError(t)}removeExecutor(e,t,n){let{media:r,mediaSource:i,operationQueue:a,sourceBuffer:o}=this,s=o[e];if(!r||!i||!s){y.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(e);return}let c=l(r.duration)?r.duration:1/0,u=l(i.duration)?i.duration:1/0,d=Math.max(0,t),f=Math.min(n,c,u);f>d&&!s.ending?(s.ended=!1,y.log(`[buffer-controller]: Removing [${d},${f}] from the ${e} SourceBuffer`),s.remove(d,f)):a.shiftAndExecuteNext(e)}appendExecutor(e,t){let{operationQueue:n,sourceBuffer:r}=this,i=r[t];if(!i){y.warn(`[buffer-controller]: Attempting to append to the ${t} SourceBuffer, but it does not exist`),n.shiftAndExecuteNext(t);return}i.ended=!1,i.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){y.log(`[buffer-controller]: Blocking operation requested, but no SourceBuffers exist`),Promise.resolve().then(e);return}let{operationQueue:n}=this,r=t.map(e=>n.appendBlocker(e));Promise.all(r).then(()=>
vendor: 9,540 bytes, lines 14-15
14{e(),t.forEach(e=>{let t=this.sourceBuffer[e];t!=null&&t.updating||n.shiftAndExecuteNext(e)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,n){let r=this.sourceBuffer[e];if(!r)return;let i=n.bind(this,e);this.listeners[e].push({event:t,listener:i}),r.addEventListener(t,i)}removeBufferListeners(e){let t=this.sourceBuffer[e];t&&this.listeners[e].forEach(e=>{t.removeEventListener(e.event,e.listener)})}},ta={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},na=function(e){let t=e;return ta.hasOwnProperty(e)&&(t=ta[e]),String.fromCharCode(t)},ra=15,ia=100,aa={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},oa={17:2,18:4,21:6,22:8,23:10,19:13,20:15},sa={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},ca={25:2,26:4,29:6,30:8,31:10,27:13,28:15},la=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`black`,`transparent`],ua=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let n=typeof t==`function`?t():t;y.log(`${this.time} [${e}] ${n}`)}}},da=function(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].toString(16));return t},fa=class{constructor(e,t,n,r,i){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=n||!1,this.background=r||`black`,this.flash=i||!1}reset(){this.foreground=`white`,this.underline=!1,this.italics=!1,this.background=`black`,this.flash=!1}setStyles(e){let t=[`foreground`,`underline`,`italics`,`background`,`flash`];for(let n=0;n<t.length;n++){let r=t[n];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return this.foreground===`white`&&!this.underline&&!this.italics&&this.background===`black`&&!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}},pa=class{constructor(e,t,n,r,i,a){this.uchar=void 0,this.penState=void 0,this.uchar=e||` `,this.penState=new fa(t,n,r,i,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()}},ma=class{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<ia;e++)this.chars.push(new pa);this.logger=e,this.pos=0,this.currPenState=new fa}equals(e){let t=!0;for(let n=0;n<ia;n++)if(!this.chars[n].equals(e.chars[n])){t=!1;break}return t}copy(e){for(let t=0;t<ia;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<ia;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,`Negative cursor position `+this.pos),this.pos=0):this.pos>ia&&(this.logger.log(3,`Too large cursor position `+this.pos),this.pos=ia)}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=na(e);if(this.pos>=ia){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<ia;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 n=0;n<ia;n++){let r=this.chars[n].uchar;r!==` `&&(t=!1),e.push(r)}return t?``:e.join(``)}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},ha=class{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<ra;t++)this.rows.push(new ma(e));this.logger=e,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}reset(){for(let e=0;e<ra;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let n=0;n<ra;n++)if(!this.rows[n].equals(e.rows[n])){t=!1;break}return t}copy(e){for(let t=0;t<ra;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<ra;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,`setCursor: `+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>`pacData = `+JSON.stringify(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<ra;e++)this.rows[e].clear();let e=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){let r=n.rows[e].cueStartTime,i=this.logger.time;if(r&&i!==null&&r<i)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(n.rows[e+r])}}this.currRow=t;let n=this.rows[this.currRow];if(e.indent!==null){let t=e.indent,r=Math.max(t-1,0);n.setCursor(e.indent),e.color=n.chars[r].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(this.nrRollUpRows===null){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||=!1;let t=[],n=``,r=-1;for(let n=0;n<ra;n++){let i=this.rows[n].getTextString();i&&(r=n+1,e?t.push(`Row `+r+`: '`+i+`'`):t.push(i.trim()))}return t.length>0&&(n=e?`[`+t.join(` | `)+`]`:t.join(`
15`)),n}getTextAndFormat(){return this.rows}},ga=class{constructor(e,t,n){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 ha(n),this.nonDisplayedMemory=new ha(n),this.lastOutputScreen=new ha(n),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}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),this.mode===`MODE_POP-ON`?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!==`MODE_ROLL-UP`&&(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)),(this.mode===`MODE_PAINT-ON`||this.mode===`MODE_ROLL-UP`)&&(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`),this.mode!==`MODE_TEXT`&&(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})}
15ccRDC(){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`),this.mode===`MODE_POP-ON`){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.foreground=t.italics?`white`:[`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;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t: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.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))}},_a=class{constructor(e,t,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;let r=new ua;this.channels=[null,new ga(e,t,r),new ga(e+1,n,r)],this.cmdHistory=ba(),this.logger=r}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){let n,r,i,a=!1;this.logger.time=e;for(let e=0;e<t.length;e+=2)if(r=t[e]&127,i=t[e+1]&127,r!==0||i!==0){if(this.logger.log(3,`[`+da([t[e],t[e+1]])+`] -> (`+da([r,i])+`)`),n=this.parseCmd(r,i),n||=this.parseMidrow(r,i),n||=this.parsePAC(r,i),n||=this.parseBackgroundAttributes(r,i),!n&&(a=this.parseChars(r,i),a)){let e=this.currentChannel;e&&e>0?this.channels[e].insertChars(a):this.logger.log(2,`No channel found yet. TEXT-MODE?`)}!n&&!a&&this.logger.log(2,`Couldn't parse cleaned data `+da([r,i])+` orig: `+da([t[e],t[e+1]]))}}parseCmd(e,t){let{cmdHistory:n}=this;if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;if(ya(e,t,n))return va(null,null,n),this.logger.log(3,`Repeated command (`+da([e,t])+`) is dropped`),!0;let r=e===20||e===21||e===23?1:2,i=this.channels[r];return e===20||e===21||e===28||e===29?t===32?i.ccRCL():t===33?i.ccBS():t===34?i.ccAOF():t===35?i.ccAON():t===36?i.ccDER():t===37?i.ccRU(2):t===38?i.ccRU(3):t===39?i.ccRU(4):t===40?i.ccFON():t===41?i.ccRDC():t===42?i.ccTR():t===43?i.ccRTD():t===44?i.ccEDM():t===45?i.ccCR():t===46?i.ccENM():t===47&&i.ccEOC():i.ccTO(t-32),va(e,t,n),this.currentChannel=r,!0}parseMidrow(e,t){let n=0;if((e===17||e===25)&&t>=32&&t<=47){if(n=e===17?1:2,n!==this.currentChannel)return this.logger.log(0,`Mismatch channel in midrow parsing`),!1;let r=this.channels[n];return r?(r.ccMIDROW(t),this.logger.log(3,`MIDROW (`+da([e,t])+`)`),!0):!1}return!1}parsePAC(e,t){let n,r=this.cmdHistory;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;if(ya(e,t,r))return va(null,null,r),!0;let i=e<=23?1:2;n=t>=64&&t<=95?i===1?aa[e]:sa[e]:i===1?oa[e]:ca[e];let a=this.channels[i];return a?(a.setPAC(this.interpretPAC(n,t)),va(e,t,r),this.currentChannel=i,!0):!1}interpretPAC(e,t){let n,r={color:null,italics:!1,indent:null,underline:!1,row:e};return n=t>95?t-96:t-64,r.underline=(n&1)==1,n<=13?r.color=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`white`][Math.floor(n/2)]:n<=15?(r.italics=!0,r.color=`white`):r.indent=Math.floor((n-16)/2)*4,r}parseChars(e,t){let n,r=null,i=null;if(e>=25?(n=2,i=e-8):(n=1,i=e),i>=17&&i<=19){let e;e=i===17?t+80:i===18?t+112:t+144,this.logger.log(2,`Special char '`+na(e)+`' in channel `+n),r=[e]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);if(r){let n=da(r);this.logger.log(3,`Char codes =  `+n.join(`,`)),va(e,t,this.cmdHistory)}return r}
vendor: 5,791 bytes, line 15
15parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let n,r={};e===16||e===24?(n=Math.floor((t-32)/2),r.background=la[n],t%2==1&&(r.background+=`_semi`)):t===45?r.background=`transparent`:(r.foreground=`black`,t===47&&(r.underline=!0));let i=e<=23?1:2;return this.channels[i].setBkgData(r),va(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=ba()}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let n=this.channels[t];n&&n.cueSplitAtTime(e)}}};function va(e,t,n){n.a=e,n.b=t}function ya(e,t,n){return n.a===e&&n.b===t}function ba(){return{a:null,b:null}}var xa=class{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(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,n){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Sa=(function(){if(typeof self<`u`&&self.VTTCue)return self.VTTCue;let e=[``,`lr`,`rl`],t=[`start`,`middle`,`end`,`left`,`right`];function n(e,t){if(typeof t!=`string`||!Array.isArray(e))return!1;let n=t.toLowerCase();return~e.indexOf(n)?n:!1}function r(t){return n(e,t)}function i(e){return n(t,e)}function a(e,...t){let n=1;for(;n<arguments.length;n++){let t=arguments[n];for(let n in t)e[n]=t[n]}return e}function o(e,t,n){let o=this,s={enumerable:!0};o.hasBeenReset=!1;let c=``,l=!1,u=e,d=t,f=n,p=null,m=``,h=!0,g=`auto`,_=`start`,v=50,y=`middle`,b=50,x=`middle`;Object.defineProperty(o,"id",a({},s,{get:function(){return c},set:function(e){c=``+e}})),Object.defineProperty(o,"pauseOnExit",a({},s,{get:function(){return l},set:function(e){l=!!e}})),Object.defineProperty(o,"startTime",a({},s,{get:function(){return u},set:function(e){if(typeof e!=`number`)throw TypeError(`Start time must be set to a number.`);u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",a({},s,{get:function(){return d},set:function(e){if(typeof e!=`number`)throw TypeError(`End time must be set to a number.`);d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",a({},s,{get:function(){return f},set:function(e){f=``+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",a({},s,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",a({},s,{get:function(){return m},set:function(e){let t=r(e);if(t===!1)throw SyntaxError(`An invalid or illegal string was specified.`);m=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",a({},s,{get:function(){return h},set:function(e){h=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",a({},s,{get:function(){return g},set:function(e){if(typeof e!=`number`&&e!==`auto`)throw SyntaxError(`An invalid number or illegal string was specified.`);g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",a({},s,{get:function(){return _},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);_=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",a({},s,{get:function(){return v},set:function(e){if(e<0||e>100)throw Error(`Position must be between 0 and 100.`);v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",a({},s,{get:function(){return y},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",a({},s,{get:function(){return b},set:function(e){if(e<0||e>100)throw Error(`Size must be between 0 and 100.`);b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",a({},s,{get:function(){return x},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);x=t,this.hasBeenReset=!0}})),o.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o})(),Ca=class{decode(e,t){if(!e)return``;if(typeof e!=`string`)throw Error(`Error - expected string data.`);return decodeURIComponent(encodeURIComponent(e))}};function wa(e){function t(e,t,n,r){return(e|0)*3600+(t|0)*60+(n|0)+parseFloat(r||0)}let n=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return n?parseFloat(n[2])>59?t(n[2],n[3],0,n[4]):t(n[1],n[2],n[3],n[4]):null}var Ta=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==``&&(this.values[e]=t)}get(e,t,n){return n?this.has(e)?this.values[e]:t[n]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,n){for(let r=0;r<n.length;++r)if(t===n[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 n=parseFloat(t);if(n>=0&&n<=100)return this.set(e,n),!0}return!1}};function Ea(e,t,n,r){let i=r?e.split(r):[e];for(let e in i){if(typeof i[e]!=`string`)continue;let r=i[e].split(n);if(r.length!==2)continue;let a=r[0],o=r[1];t(a,o)}}var Da=new Sa(0,0,``),Oa=Da.align===`middle`?`middle`:`center`;function ka(e,t,n){let r=e;function i(){let t=wa(e);if(t===null)throw Error(`Malformed timestamp: `+r);return e=e.replace(/^[^\sa-zA-Z-]+/,``),t}function a(e,t){let r=new Ta;Ea(e,function(e,t){let i;switch(e){case`region`:for(let i=n.length-1;i>=0;i--)if(n[i].id===t){r.set(e,n[i].region);break}break;case`vertical`:r.alt(e,t,[`rl`,`lr`]);break;case`line`:i=t.split(`,`),r.integer(e,i[0]),r.percent(e,i[0])&&r.set(`snapToLines`,!1),r.alt(e,i[0],[`auto`]),i.length===2&&r.alt(`lineAlign`,i[
vendor: 8,159 bytes, lines 15-25
151],[`start`,Oa,`end`]);break;case`position`:i=t.split(`,`),r.percent(e,i[0]),i.length===2&&r.alt(`positionAlign`,i[1],[`start`,Oa,`end`,`line-left`,`line-right`,`auto`]);break;case`size`:r.percent(e,t);break;case`align`:r.alt(e,t,[`start`,Oa,`end`,`left`,`right`])}},/:/,/\s/),t.region=r.get(`region`,null),t.vertical=r.get(`vertical`,``);let i=r.get(`line`,`auto`);i===`auto`&&Da.line===-1&&(i=-1),t.line=i,t.lineAlign=r.get(`lineAlign`,`start`),t.snapToLines=r.get(`snapToLines`,!0),t.size=r.get(`size`,100),t.align=r.get(`align`,Oa);let a=r.get(`position`,`auto`);a===`auto`&&Da.position===50&&(a=t.align===`start`||t.align===`left`?0:t.align===`end`||t.align===`right`?100:50),t.position=a}function o(){e=e.replace(/^\s+/,``)}if(o(),t.startTime=i(),o(),e.slice(0,3)!==`-->`)throw Error(`Malformed time stamp (time stamps must be separated by '-->'): `+r);e=e.slice(3),o(),t.endTime=i(),o(),a(e,t)}function Aa(e){return e.replace(/<br(?: \/)?>/gi,`
16`)}var ja=class{constructor(){this.state=`INITIAL`,this.buffer=``,this.decoder=new Ca,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function n(){let e=t.buffer,n=0;for(e=Aa(e);n<e.length&&e[n]!==`\r`&&e[n]!==`
17`;)++n;let r=e.slice(0,n);return e[n]===`\r`&&++n,e[n]===`
18`&&++n,t.buffer=e.slice(n),r}function r(e){Ea(e,function(e,t){},/:/)}try{let e=``;if(t.state===`INITIAL`){if(!/\r\n|\n/.test(t.buffer))return this;e=n();let r=e.match(/^()?WEBVTT([ \t].*)?$/);if(!(r!=null&&r[0]))throw Error(`Malformed WebVTT signature.`);t.state=`HEADER`}let i=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(i?i=!1:e=n(),t.state){case`HEADER`:/:/.test(e)?r(e):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 Sa(0,0,``),t.state=`CUE`,e.indexOf(`-->`)===-1){t.cue.id=e;continue}case`CUE`:if(!t.cue){t.state=`BADCUE`;continue}try{ka(e,t.cue,t.regionList)}catch{t.cue=null,t.state=`BADCUE`;continue}t.state=`CUETEXT`;continue;case`CUETEXT`:{let n=e.indexOf(`-->`)!==-1;if(!e||n&&(i=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state=`ID`;continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
19`),t.cue.text+=e}continue;case`BADCUE`:e||(t.state=`ID`)}}}catch{t.state===`CUETEXT`&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state===`INITIAL`?`BADWEBVTT`:`BADCUE`}return this}flush(){let e=this;try{if((e.cue||e.state===`HEADER`)&&(e.buffer+=`
20
21`,e.parse()),e.state===`INITIAL`||e.state===`BADWEBVTT`)throw Error(`Malformed WebVTT signature.`)}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},Ma=/\r\n|\n\r|\n|\r/g,Na=function(e,t,n=0){return e.slice(n,n+t.length)===t},Pa=function(e){let t=parseInt(e.slice(-3)),n=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(`:`))):0;if(!l(t)||!l(n)||!l(r)||!l(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*n,t+=6e4*r,t+=36e5*i,t},Fa=function(e){let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return(t>>>0).toString()};function Ia(e,t,n){return Fa(e.toString())+Fa(t.toString())+Fa(n)}var La=function(e,t,n){let r=e[t],i=e[r.prevCC];if(!i||!i.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=!1;return}for(;(a=i)!=null&&a.new;){var a;e.ccOffset+=r.start-i.start,r.new=!1,r=i,i=e[r.prevCC]}e.presentationOffset=n};function Ra(e,t,n,r,i,a,o){let s=new ja,c=N(new Uint8Array(e)).trim().replace(Ma,`
22`).split(`
23`),l=[],u=t?ti(t.baseTime,t.timescale):0,d=`00:00.000`,f=0,p=0,m,h=!0;s.oncue=function(e){let a=n[r],o=n.ccOffset,s=(f-u)/9e4;if(a!=null&&a.new&&(p===void 0?La(n,r,s):o=n.ccOffset=a.start),s){if(!t){m=Error(`Missing initPTS for VTT MPEGTS`);return}o=s-n.presentationOffset}let c=e.endTime-e.startTime,d=Z((e.startTime+o-p)*9e4,i*9e4)/9e4;e.startTime=Math.max(d,0),e.endTime=Math.max(d+c,0);let h=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(h)),e.id||=Ia(e.startTime,e.endTime,h),e.endTime>0&&l.push(e)},s.onparsingerror=function(e){m=e},s.onflush=function(){if(m){o(m);return}a(l)},c.forEach(e=>{if(h){if(Na(e,`X-TIMESTAMP-MAP=`)){h=!1,e.slice(16).split(`,`).forEach(e=>{Na(e,`LOCAL:`)?d=e.slice(6):Na(e,`MPEGTS:`)&&(f=parseInt(e.slice(7)))});try{p=Pa(d)/1e3}catch(e){m=e}return}e===``&&(h=!1)}s.parse(e+`
24`)}),s.flush()}var za=`stpp.ttml.im1t`,Ba=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Va=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Ha={left:`start`,center:`center`,right:`end`,start:`start`,end:`end`};function Ua(e,t,n,r){let i=L(new Uint8Array(e),[`mdat`]);if(i.length===0){r(Error(`Could not parse IMSC1 mdat`));return}let a=i.map(e=>N(e)),o=$r(t.baseTime,1,t.timescale);try{a.forEach(e=>n(Wa(e,o)))}catch(e){r(e)}}function Wa(e,t){let n=new DOMParser().parseFromString(e,`text/xml`).getElementsByTagName(`tt`)[0];if(!n)throw Error(`Invalid ttml`);let r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},i=Object.keys(r).reduce((e,t)=>(e[t]=n.getAttribute(`ttp:${t}`)||r[t],e),{}),a=n.getAttribute(`xml:space`)!==`preserve`,s=Ka(Ga(n,`styling`,`style`)),c=Ka(Ga(n,`layout`,`region`)),l=Ga(n,`body`,`[begin]`);return[].map.call(l,e=>{let n=qa(e,a);if(!n||!e.hasAttribute(`begin`))return null;let r=Za(e.getAttribute(`begin`),i),l=Za(e.getAttribute(`dur`),i),u=Za(e.getAttribute(`end`),i);if(r===null)throw Xa(e);if(u===null){if(l===null)throw Xa(e);u=r+l}let d=new Sa(r-t,u-t,n);d.id=Ia(d.startTime,d.endTime,d.text);let f=c[e.getAttribute(`region`)],p=s[e.getAttribute(`style`)],m=Ja(f,p,s),{textAlign:h}=m;if(h){let e=Ha[h];e&&(d.lineAlign=e),d.align=h}return o(d,m),d}).filter(e=>e!==null)}function Ga(e,t,n){let r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function Ka(e){return e.reduce((e,t)=>{let n=t.getAttribute(`xml:id`);return n&&(e[n]=t),e},{})}function qa(e,t){return[].slice.call(e.childNodes).reduce((e,n,r)=>{var i;return n.nodeName===`br`&&r?e+`
25`:(i=n.childNodes)!=null&&i.length?qa(n,t):t?e+n.textContent.trim().replace(/\s+/g,` `):e+n.textContent},``)}function Ja(e,t,n){let r=`http://www.w3.org/ns/ttml#styling`,i=null,a=[`displayAlign`,`textAlign`,`color`,`backgroundColor`,`fontSize`,`fontFamily`],o=e!=null&&e.hasAttribute(`style`)?e.getAttribute(`style`):null;return o&&n.hasOwnProperty(o)&&(i=n[o]),a.reduce((n,a)=>{let o=Ya(t,r,a)||Ya(e,r,a)||Ya(i,r,a);return o&&(n[a]=o),n},{})}function Ya(e,t,n){return e&&e.hasAttributeNS(t,n)?e.getAttributeNS(t,n):null}function Xa(e){return Error(`Could not parse ttml timestamp ${e}`)}function Za(e,t){if(!e)return null;let n=wa(e);return n===null&&(Ba.test(e)?n=Qa(e,t):Va.test(e)&&(n=$a(e,t))),n}function Qa(e,t){let n=Ba.exec(e),r=(n[4]|0)+(n[5]|0)/t.subFrameRate;return(n[1]|0)*3600+(n[2]|0)*60+(n[3]|0)+r/t.frameRate}function $a(e,t){let n=Va.exec(e),r=Number(n[1]);switch(n[2]){case`h`:return r*3600;case`m`:return r*60;case`ms`:return r*1e3;case`f`:return r/t.frameRate;case`t`:return r/t.tickRate}return r}var eo=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=ro(),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 xa(this,`textTrack1`),t=new xa(this,`textTrack2`),n=new xa(this,`textTrack3`),r=new xa(this,`textTrack4`);this.cea608Parser1=new _a(1,e,t),this.cea608Parser2=new _a(3,n,r)}
25e.on(u.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(u.MANIFEST_LOADING,this.onManifestLoading,this),e.on(u.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(u.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(u.FRAG_LOADING,this.onFragLoading,this),e.on(u.FRAG_LOADED,this.onFragLoaded,this),e.on(u.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(u.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(u.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(u.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(u.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(u.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(u.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(u.MANIFEST_LOADING,this.onManifestLoading,this),e.off(u.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(u.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(u.FRAG_LOADING,this.onFragLoading,this),e.off(u.FRAG_LOADED,this.onFragLoaded,this),e.off(u.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(u.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(u.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(u.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(u.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(e,t,n,r,i){let a=!1;for(let e=i.length;e--;){let r=i[e],o=no(r[0],r[1],t,n);if(o>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],n),a=!0,o/(n-t)>.5))return}if(a||i.push([t,n]),this.config.renderTextTracksNatively){let i=this.captionsTracks[e];this.Cues.newCue(i,t,n,r)}else{let i=this.Cues.newCue(null,t,n,r);this.hls.trigger(u.CUES_PARSED,{type:`captions`,cues:i,track:e})}}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:i}){let{unparsedVttFrags:a}=this;n===`main`&&(this.initPTS[t.cc]={baseTime:r,timescale:i}),a.length&&(this.unparsedVttFrags=[],a.forEach(e=>{this.onFragLoaded(u.FRAG_LOADED,e)}))}getExistingTrack(e){let{media:t}=this;if(t)for(let n=0;n<t.textTracks.length;n++){let r=t.textTracks[n];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:n,media:r}=this,{label:i,languageCode:a}=t[e],o=this.getExistingTrack(e);if(o)n[e]=o,Ft(n[e]),Nt(n[e],r);else{let t=this.createTextTrack(`captions`,i,a);t&&(t[e]=!0,n[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let n={_id:e,label:t.label,kind:`captions`,default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(u.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,n){let r=this.media;if(r)return r.addTextTrack(e,t,n)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){let{captionsTracks:e}=this;Object.keys(e).forEach(t=>{Ft(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ro(),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++)Ft(t[e])}onSubtitleTracksUpdated(e,t){let n=t.subtitleTracks||[],r=n.some(e=>e.textCodec===za);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(Wi(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){let e=this.media?this.media.textTracks:null;this.tracks.forEach((t,n)=>{let r;if(e&&n<e.length){let n=null;for(let r=0;r<e.length;r++)if(to(e[r],t)){n=e[r];break}n&&(r=n)}if(r)Ft(r);else{let e=this._captionsOrSubtitlesFromCharacteristics(t);r=this.createTextTrack(e,t.name,t.lang),r&&(r.mode=`disabled`)}r&&(r.groupId=t.groupId,this.textTracks.push(r))})}else if(this.tracks.length){let e=this.tracks.map(e=>
25({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(u.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){let t=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),n=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(t&&n)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 n=`textTrack${t[1]}`,r=this.captionsProperties[n];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)})}closedCaptionsForLevel(e){return this.hls.levels[e.level]?.attrs[`CLOSED-CAPTIONS`]}onFragLoading(e,t){let{cea608Parser1:n,cea608Parser2:r,lastSn:i,lastPartIndex:a}=this;if(!(!this.enabled||!(n&&r))&&t.frag.type===B.MAIN){let e=t.frag.sn,o=t?.part?.index??-1;e===i+1||e===i&&o===a+1||(n.reset(),r.reset()),this.lastSn=e,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:n,payload:r}=t;if(n.type===B.SUBTITLE){if(r.byteLength){let e=n.decryptdata,i=`stats`in t;if(e==null||!e.encrypted||i){let e=this.tracks[n.level],i=this.vttCCs;i[n.cc]||(i[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),e&&e.textCodec===za?this._parseIMSC1(n,r):this._parseVTTs(t)}}else this.hls.trigger(u.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:Error(`Empty subtitle payload`)})}}_parseIMSC1(e,t){let n=this.hls;Ua(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),n.trigger(u.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{y.log(`Failed to parse IMSC1: ${t}`),n.trigger(u.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;let{frag:n,payload:r}=e,{initPTS:i,unparsedVttFrags:a}=this,o=i.length-1;if(!i[n.cc]&&o===-1){a.push(e);return}let s=this.hls;Ra((t=n.initSegment)!=null&&t.data?qe(n.initSegment.data,new Uint8Array(r)):r,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,e=>{this._appendCues(e,n.level),s.trigger(u.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},t=>{let i=t.message===`Missing initPTS for VTT MPEGTS`;i?a.push(e):this._fallbackToIMSC1(n,r),y.log(`Failed to parse VTT cue: ${t}`),!(i&&o>n.cc)&&s.trigger(u.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:t})})}_fallbackToIMSC1(e,t){let n=this.tracks[e.level];n.textCodec||Ua(t,this.initPTS[e.cc],()=>{n.textCodec=za,this._parseIMSC1(e,t)},()=>{n.textCodec=`wvtt`})}_appendCues(e,t){let n=this.hls;if(this.config.renderTextTracksNatively){let n=this.textTracks[t];if(!n||n.mode===`disabled`)return;e.forEach(e=>Pt(n,e))}else{let r=this.tracks[t];if(!r)return;let i=r.default?`default`:`subtitles`+t;n.trigger(u.CUES_PARSED,{type:`subtitles`,cues:e,track:i})}}onFragDecrypted(e,t){let{frag:n}=t;n.type===B.SUBTITLE&&this.onFragLoaded(u.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){let{cea608Parser1:n,cea608Parser2:r}=this;if(!this.enabled||!(n&&r))return;let{frag:i,samples:a}=t;if(i.type!==B.MAIN||this.closedCaptionsForLevel(i)!==`NONE`)for(let e=0;e<a.length;e++){let t=a[e].bytes;if(t){let i=this.extractCea608Data(t);n.addData(a[e].pts,i[0]),r.addData(a[e].pts,i[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:n,endOffsetSubtitles:r,type:i}){let{media:a}=this;if(!(!a||a.currentTime<n)){if(!i||i===`video`){let{captionsTracks:e}=this;Object.keys(e).forEach(r=>It(e[r],t,n))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:e}=this;Object.keys(e).forEach(n=>It(e[n],t,r))}}}extractCea608Data(e){let t=[[],[]],n=e[0]&31,r=2;for(let i=0;i<n;i++){let n=e[r++],i=127&e[r++],a=127&e[r++];if((i!==0||a!==0)&&4&n){let e=3&n;(e===0||e===1)&&(t[e].push(i),t[e].push(a))}}return t}};function to(e,t){return!!e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}function no(e,t,n,r){return Math.min(t,r)-Math.max(e,n)}function ro(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var io=class e{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=1/0,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.unregisterListener(),this.hls.config.capLevelToPlayerSize&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){let{hls:e}=this;e.on(u.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(u.MEDIA_ATTA
25CHING,this.onMediaAttaching,this),e.on(u.MANIFEST_PARSED,this.onManifestParsed,this),e.on(u.BUFFER_CODECS,this.onBufferCodecs,this),e.on(u.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(u.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(u.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(u.MANIFEST_PARSED,this.onManifestParsed,this),e.off(u.BUFFER_CODECS,this.onBufferCodecs,this),e.off(u.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let n=this.hls.levels[t.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null}onManifestParsed(e,t){let n=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,n.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media&&this.mediaHeight>0&&this.mediaWidth>0){let e=this.hls.levels;if(e.length){let t=this.hls;t.autoLevelCapping=this.getMaxLevel(e.length-1),t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(t){let n=this.hls.levels;if(!n.length)return-1;let r=n.filter((e,n)=>this.isLevelAllowed(e)&&n<=t);return this.clientRect=null,e.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=1/0,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=1/0,this.timer&&=(self.clearInterval(this.timer),void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let n=e.getBoundingClientRect();t.width=n.width,t.height=n.height,!t.width&&!t.height&&(t.width=n.right-n.left||e.width||0,t.height=n.bottom-n.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{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,n){if(!(e!=null&&e.length))return-1;let r=(e,t)=>!t||e.width!==t.width||e.height!==t.height,i=e.length-1;for(let a=0;a<e.length;a+=1){let o=e[a];if((o.width>=t||o.height>=n)&&r(o,e[a+1])){i=a;break}}return i}},ao=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}
25registerListeners(){this.hls.on(u.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(u.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let n=this.hls.config;if(n.capLevelOnFPSDrop){let e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&typeof e.getVideoPlaybackQuality==`function`&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,n){let r=performance.now();if(t){if(this.lastTime){let e=r-this.lastTime,i=n-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*i/e,s=this.hls;if(s.trigger(u.FPS_DROP,{currentDropped:i,currentDecoded:a,totalDroppedFrames:n}),o>0&&i>s.config.fpsDroppedMonitoringThreshold*a){let e=s.currentLevel;y.warn(`drop FPS ratio greater than max allowed value for currentLevel: `+e),e>0&&(s.autoLevelCapping===-1||s.autoLevelCapping>=e)&&(--e,s.trigger(u.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:s.currentLevel}),s.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=n,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)}}},oo=`[eme]`,so=class e{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=e.CDMCleanupPromise?[e.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=y.debug.bind(y,oo),this.log=y.log.bind(y,oo),this.warn=y.warn.bind(y,oo),this.error=y.error.bind(y,oo),this.hls=t,this.config=t.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}
25registerListeners(){this.hls.on(u.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(u.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(u.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(u.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(u.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(u.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(u.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(u.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:n}=this.config,r=t[e];if(r)return r.licenseUrl;if(e===j.WIDEVINE&&n)return n;throw Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){let{drmSystems:t}=this.config,n=t[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,n=(e,t,n)=>!!e&&n.indexOf(e)===t,r=t.map(e=>e.audioCodec).filter(n),i=t.map(e=>e.videoCodec).filter(n);return r.length+i.length===0&&i.push(`avc1.42e01e`),new Promise((t,n)=>{let a=e=>{let o=e.shift();this.getMediaKeysPromise(o,r,i).then(e=>t({keySystem:o,mediaKeys:e})).catch(t=>{e.length?a(e):t instanceof Q?n(t):n(new Q({type:d.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};a(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!=`function`){let e=`Configured requestMediaKeySystemAccess is not a function ${n}`;return fe===null&&self.location.protocol===`http:`&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(Error(e))}return n(e,t)}getMediaKeysPromise(e,t,n){let r=pe(e,t,n,this.config.drmSystemOptions),i=this.keySystemAccessPromises[e],a=i?.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(n=>{this.log(`Access for key-system "${n.keySystem}" obtained`);let r=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),t.mediaKeys=n.createMediaKeys().then(t=>(this.log(`Media-keys created for "${e}"`),r.then(n=>n?this.setMediaKeysServerCertificate(t,e,n):t))),t.mediaKeys.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),t.mediaKeys})}return a.then(()=>i.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:n}){this.log(`Creating key-system session "${t}" keyId: ${P.hexDump(e.keyId||[])}`);let r={decryptdata:e,keySystem:t,mediaKeys:n,mediaKeysSession:n.createSession(),keyStatus:`status-pending`};return this.mediaKeySessions.push(r),r}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let n=this.createMediaKeySessionContext(e),r=this.getKeyIdString(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(n,`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(e.keyId===null)throw Error(`keyId is null`);return P.hexDump(e.keyId)}updateKeySession(e,t){let n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyID ${P.hexDump(e.decryptdata?.keyId||[])}
26      } (data length: ${t&&t.byteLength})`),n.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.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,n)=>{let r=de(this.config),i=e.map(se).filter(e=>!!e&&r.indexOf(e)!==-1);return this.getKeySystemSelectionPromise(i).then(({keySystem:e})=>{let r=ue(e);r?t(r):n(Error(`Unable to find format for key-system "${e}"`))}).catch(n)})}loadKey(e){let t=e.keyInfo.decryptdata,n=this.getKeyIdString(t),r=`(keyId: ${n} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);let i=this.keyIdToKeySessionPromise[n];
26return i||(i=this.keyIdToKeySessionPromise[n]=this.getKeySystemForKeyPromise(t).then(({keySystem:n,mediaKeys:i})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(n,i).then(()=>{this.throwIfDestroyed();let e=this.createMediaKeySessionContext({keySystem:n,mediaKeys:i,decryptdata:t});return this.generateRequestWithPreferredKeySession(e,`cenc`,t.pssh,`playlist-key`)}))),i.catch(e=>this.handleError(e))),i}throwIfDestroyed(e=`Invalid state`){if(!this.hls)throw Error(`invalid state`)}handleError(e){this.hls&&(this.error(e.message),e instanceof Q?this.hls.trigger(u.ERROR,e.data):this.hls.trigger(u.ERROR,{type:d.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){let t=this.getKeyIdString(e),n=this.keyIdToKeySessionPromise[t];if(!n){let t=se(e.keyFormat),n=t?[t]:de(this.config);return this.attemptKeySystemAccess(n)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=de(this.config)),e.length===0)throw new Q({type:d.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){let{initDataType:t,initData:n}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),n===null)return;let r,i;if(t===`sinf`&&this.config.drmSystems[j.FAIRPLAY]){let e=F(new Uint8Array(n));try{let t=ne(JSON.parse(e).sinf),n=Ve(new Uint8Array(t));if(!n)return;r=n.subarray(8,24),i=j.FAIRPLAY}catch{this.warn(`Failed to parse sinf "encrypted" event message initData`);return}}else{let e=nt(n);if(e===null)return;e.version===0&&e.systemId===ce.WIDEVINE&&e.data&&(r=e.data.subarray(8,24)),i=le(e.systemId)}if(!i||!r)return;let a=P.hexDump(r),{keyIdToKeySessionPromise:o,mediaKeySessions:s}=this,c=o[a];for(let e=0;e<s.length;e++){let i=s[e],l=i.decryptdata;if(l.pssh||!l.keyId)continue;let u=P.hexDump(l.keyId);if(a===u||l.uri.replace(/-/g,``).indexOf(a)!==-1){c=o[u],delete o[u],l.pssh=new Uint8Array(n),l.keyId=r,c=o[a]=c.then(()=>this.generateRequestWithPreferredKeySession(i,t,n,`encrypted-event-key-match`));break}}c||=o[a]=this.getKeySystemSelectionPromise([i]).then(({keySystem:e,mediaKeys:i})=>{this.throwIfDestroyed();let o=new it(`ISO-23001-7`,a,ue(e)??``);return o.pssh=new Uint8Array(n),o.keyId=r,this.attemptSetMediaKeys(e,i).then(()=>{this.throwIfDestroyed();let r=this.createMediaKeySessionContext({decryptdata:o,keySystem:e,mediaKeys:i});return this.generateRequestWithPreferredKeySession(r,t,n,`encrypted-event-no-match`)})}),c.catch(e=>this.handleError(e))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){let n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(n).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}"`),n.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>n.indexOf(e)===-1)})}generateRequestWithPreferredKeySession(e,t,n,r){let i=this.config.drmSystems?.[e.keySystem]?.generateRequest;if(i)try{let r=i.call(this.hls,t,n,e);if(!r)throw Error(`Invalid response from configured generateRequest filter`);t=r.initDataType,n=e.decryptdata.pssh=r.initData?new Uint8Array(r.initData):null}catch(e){var a;if(this.warn(e.message),(a=this.hls)!=null&&a.config.debug)throw e}if(n===null)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: ${n?n.byteLength:null})`);let s=new Ei;e.mediaKeysSession.onmessage=t=>{let n=e.mediaKeysSession;if(!n){s.emit(`error`,Error(`invalid state`));return}let{messageType:r,message:i}=t;this.log(`"${r}" message event for session "${n.sessionId}" message size: ${i.byteLength}`),r===`license-request`||r===`license-renewal`?this.renewLicense(e,i
26).catch(e=>{this.handleError(e),s.emit(`error`,e)}):r===`license-release`?e.keySystem===j.FAIRPLAY&&(this.updateKeySession(e,oe(`acknowledged`)),this.removeSession(e)):this.warn(`unhandled media key message type "${r}"`)},e.mediaKeysSession.onkeystatuseschange=t=>{if(!e.mediaKeysSession){s.emit(`error`,Error(`invalid state`));return}this.onKeyStatusChange(e);let n=e.keyStatus;s.emit(`keyStatus`,n),n===`expired`&&(this.warn(`${e.keySystem} expired for key ${o}`),this.renewKeySession(e))};let c=new Promise((e,t)=>{s.on(`error`,t),s.on(`keyStatus`,n=>{n.startsWith(`usable`)?e():n===`output-restricted`?t(new Q({type:d.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},`HDCP level output restricted`)):n===`internal-error`?t(new Q({type:d.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${n}"`)):n===`expired`?t(Error(`key expired while generating request`)):this.warn(`unhandled key status change "${n}"`)})});return e.mediaKeysSession.generateRequest(t,n).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession?.sessionId}" keyId: ${o}`)}).catch(e=>{throw new Q({type:d.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_NO_SESSION,error:e,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>c).catch(t=>{throw s.removeAllListeners(),this.removeSession(e),t}).then(()=>(s.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,n)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${P.hexDump(`buffer`in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n))} session keyId: ${P.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){let t=this.config,n=t.loader,r=new n(t),a=this.getServerCertificateUrl(e);return a?(this.log(`Fetching serverCertificate for "${e}"`),new Promise((n,o)=>{let s={responseType:`arraybuffer`,url:a},c=t.certLoadPolicy.default,l={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(s,l,{onSuccess:(e,t,r,i)=>{n(e.data)},onError:(t,n,r,c)=>{o(new Q({type:d.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:i({url:s.url,data:void 0},t)},`"${e}" certificate request failed (${a}). Status: ${t.code} (${t.text})`))},onTimeout:(t,n,r)=>{o(new Q({type:d.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:s.url,data:void 0}},`"${e}" certificate request timed out (${a})`))},onAbort:(e,t,n)=>{o(Error(`aborted`))}})})):Promise.resolve()}setMediaKeysServerCertificate(e,t,n){return new Promise((r,i)=>{e.setServerCertificate(n).then(i=>{this.log(`setServerCertificate ${i?`success`:`not supported by CDM`} (${n?.byteLength}) on "${t}"`),r(e)}).catch(e=>{i(new Q({type:d.KEY_SYSTEM_ERROR,details:f.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 Q({type:d.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:e,fatal:!0},e.message)}))}setupLicenseXHR(e,t,n,r){let i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!n.decryptdata)throw Error(`Key removed`);return i.call(this.hls,e,t,n,r)}).catch(a=>{if(!n.decryptdata)throw a;return e.open(`POST`,t,!0),i.call(this.hls,e,t,n,r)}).then(n=>(e.readyState||e.open(`POST`,t,!0),{xhr:e,licenseChallenge:n||r})):(e.open(`POST`,t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let n=this.config.keyLoadPolicy.default;return new Promise((r,i)=>{let a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType=`arraybuffer`,o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(Error(`invalid state`));if(o.readyState===4){if(o.status===200){this._requestLicenseFailureCount=0;
26let t=o.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);let n=this.config.licenseResponseCallback;if(n)try{t=n.call(this.hls,o,a,e)}catch(e){this.error(e)}r(t)}else{let s=n.errorRetry,c=s?s.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)i(new Q({type:d.KEY_SYSTEM_ERROR,details:f.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{let n=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${n} attempts left`),this.requestLicense(e,t).then(r,i)}}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:e,licenseChallenge:t})=>{e.send(t)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let n=t.media;this.media=n,n.addEventListener(`encrypted`,this.onMediaEncrypted),n.addEventListener(`waitingforkey`,this.onWaitingForKey)}onMediaDetached(){let t=this.media,n=this.mediaKeySessions;t&&(t.removeEventListener(`encrypted`,this.onMediaEncrypted),t.removeEventListener(`waitingforkey`,this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},it.clearKeyUriToKeyIdMap();let r=n.length;e.CDMCleanupPromise=Promise.all(n.map(e=>this.removeSession(e)).concat(t?.setMediaKeys(null).catch(e=>{this.log(`Could not clear media keys: ${e}. media.src: ${t?.src}`)}))).then(()=>{r&&(this.log(`finished closing key sessions and clearing media keys`),n.length=0)}).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}. media.src: ${t?.src}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let e=t.reduce((e,t)=>(e.indexOf(t.keyFormat)===-1&&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:n}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),t.onmessage=null,t.onkeystatuseschange=null,n&&n.readyState!==XMLHttpRequest.DONE&&n.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}`)})}}};so.CDMCleanupPromise=void 0;var Q=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||=Error(t),this.data=e,e.err=e.error}},co=1,$={MANIFEST:`m`,AUDIO:`a`,VIDEO:`v`,MUXED:`av`,INIT:`i`,CAPTION:`c`,TIMED_TEXT:`tt`,KEY:`k`,OTHER:`o`},lo=`h`,uo=class e{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||=!0,this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:$.MANIFEST,su:!this.initialized})}catch(e){y.warn(`Could not generate manifest CMCD data.`,e)}},this.applyFragmentData=e=>{try{let t=e.frag,n=this.hls.levels[t.level],r=this.getObjectType(t),i={d:t.duration*1e3,ot:r};(r===$.VIDEO||r===$.AUDIO||r==$.MUXED)&&(i.br=n.bitrate/1e3,i.tb=this.getTopBandwidth(r)/1e3,i.bl=this.getBufferLength(r)),this.apply(e,i)}catch(e){y.warn(`Could not generate segment CMCD data.`,e)}},this.hls=t;let n=this.config=t.config,{cmcd:r}=n;r!=null&&(n.pLoader=this.createPlaylistLoader(),n.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.uuid(),this.cid=r.contentId,this.useHeaders=r.useHeaders===!0,this.registerListeners())}registerListeners(){let e=this.hls;
26e.on(u.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(u.MEDIA_DETACHED,this.onMediaDetached,this),e.on(u.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(u.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(u.MEDIA_DETACHED,this.onMediaDetached,this),e.off(u.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),null)}onBufferCreated(e,t){this.audioBuffer=t.tracks.audio?.buffer,this.videoBuffer=t.tracks.video?.buffer}createData(){return{v:co,sf:lo,sid:this.sid,cid:this.cid,pr:this.media?.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,n={}){o(n,this.createData());let r=n.ot===$.INIT||n.ot===$.VIDEO||n.ot===$.MUXED;if(this.starved&&r&&(n.bs=!0,n.su=!0,this.starved=!1),n.su??=this.buffering,this.useHeaders){let r=e.toHeaders(n);if(!Object.keys(r).length)return;t.headers||={},o(t.headers,r)}else{let r=e.toQuery(n);if(!r)return;t.url=e.appendQueryToUri(t.url,r)}}getObjectType(e){let{type:t}=e;if(t===`subtitle`)return $.TIMED_TEXT;if(e.sn===`initSegment`)return $.INIT;if(t===`audio`)return $.AUDIO;if(t===`main`)return this.hls.audioTracks.length?$.VIDEO:$.MUXED}getTopBandwidth(e){let t=0,n,r=this.hls;if(e===$.AUDIO)n=r.audioTracks;else{let e=r.maxAutoLevel,t=e>-1?e+1:r.levels.length;n=r.levels.slice(0,t)}for(let e of n)e.bitrate>t&&(t=e.bitrate);return t>0?t:NaN}getBufferLength(e){let t=this.hls.media,n=e===$.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!t?NaN:K.bufferInfo(n,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,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=[],n=e=>!Number.isNaN(e)&&e!=null&&e!==``&&e!==!1,r=e=>Math.round(e),i=e=>r(e/100)*100,a={br:r,d:r,bl:i,dl:i,mtp:i,nor:e=>encodeURIComponent(e),rtp:i,tb:r},o=Object.keys(e||{}).sort();for(let r of o){let i=e[r];if(!n(i)||r===`v`&&i===1||r==`pr`&&i===1)continue;let o=a[r];o&&(i=o(i));let s=typeof i,c;c=r===`ot`||r===`sf`||r===`st`?`${r}=${i}`:s===`boolean`?r:s===`number`?`${r}=${i}`:`${r}=${JSON.stringify(i)}`,t.push(c)}return t.join(`,`)}static toHeaders(t){let n=Object.keys(t),r={},i=[`Object`,`Request`,`Session`,`Status`],a=[{},{},{},{}],o={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 e of n){let n=o[e]==null?1:o[e];a[n][e]=t[e]}for(let t=0;t<a.length;t++){let n=e.serialize(a[t]);n&&(r[`CMCD-${i[t]}`]=n)}return r}static toQuery(t){return`CMCD=${encodeURIComponent(e.serialize(t))}`}static appendQueryToUri(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}${t}`:e}},fo=3e5,po=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=y.log.bind(y,`[content-steering]:`),this.registerListeners()}registerListeners(){let e=this.hls;e.on(u.MANIFEST_LOADING,this.onManifestLoading,this),e.on(u.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(u.MANIFEST_PARSED,this.onManifestParsed,this),e.on(u.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(u.MANIFEST_LOADING,this.onManifestLoading,this),e.off(u.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(u.MANIFEST_PARSED,this.onManifestParsed,this),e.off(u.ERROR,this.onError,this))}
26startLoad(){if(this.started=!0,self.clearTimeout(this.reloadTimer),this.enabled&&this.uri){if(this.updated){let e=Math.max(this.timeToLoad*1e3-(performance.now()-this.updated),0);this.scheduleRefresh(this.uri,e)}else this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&=(this.loader.destroy(),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:n}=t;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:n}=t;if(n?.action===H.SendAlternateToPenaltyBox&&n.flags===U.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)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])),e&&e.length>1&&(this.updatePathwayPriority(e),n.resolved=this.pathwayId!==t)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),t=this.getLevelsForPathway(n),this.pathwayId=n}return t.length===e.length?e:(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t)}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t,n=this.penalizedPathways,r=performance.now();Object.keys(n).forEach(e=>{r-n[e]>fo&&delete n[e]});for(let r=0;r<e.length;r++){let i=e[r];if(n[i])continue;if(i===this.pathwayId)return;let a=this.hls.nextLoadLevel,o=this.hls.levels[a];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,this.hls.trigger(u.LEVELS_UPDATED,{levels:t});let e=this.hls.levels[a];o&&e&&this.levels&&(e.attrs[`STABLE-VARIANT-ID`]!==o.attrs[`STABLE-VARIANT-ID`]&&e.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=a);break}}}clonePathways(e){let t=this.levels;if(!t)return;let n={},r={};e.forEach(e=>{let{ID:i,"BASE-ID":a,"URI-REPLACEMENT":s}=e;if(t.some(e=>e.pathwayId===i))return;let c=this.getLevelsForPathway(a).map(e=>{let t=o({},e);t.details=void 0,t.url=ho(e.uri,e.attrs[`STABLE-VARIANT-ID`],`PER-VARIANT-URIS`,s);let a=new S(e.attrs);a[`PATHWAY-ID`]=i;let c=a.AUDIO&&`${a.AUDIO}_clone_${i}`,l=a.SUBTITLES&&`${a.SUBTITLES}_clone_${i}`;c&&(n[a.AUDIO]=c,a.AUDIO=c),l&&(r[a.SUBTITLES]=l,a.SUBTITLES=l),t.attrs=a;let u=new Xt(t);return On(u,`audio`,c),On(u,`text`,l),u});t.push(...c),mo(this.audioTracks,n,s,i),mo(this.subtitleTracks,r,s,i)})}loadSteeringManifest(e){let t=this.hls.config,n=t.loader;this.loader&&this.loader.destroy(),this.loader=new n(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!==`data:`){let e=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set(`_HLS_pathway`,this.pathwayId),r.searchParams.set(`_HLS_throughput`,``+e)}let i={responseType:`json`,url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},s={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0};this.log(`Requesting steering manifest: ${r}`),this.loader.load(i,s,{onSuccess:(e,t,n,i)=>{this.log(`Loaded steering manifest: "${r}"`);let a=e.data;if(a.VERSION!==1){this.log(`Steering VERSION ${a.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=a.TTL;let{"RELOAD-URI":o,"PATHWAY-CLONES":s,"PATHWAY-PRIORITY":c}=a;if(o)try{this.uri=new self.URL(o,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`);return}this.scheduleRefresh(this.uri||n.url),s&&this.clonePathways(s),c&&this.updatePathwayPriority(c)},onError:(e,t,n,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),e.code===410){this.enabled=!1,this.log(`Steering manifest ${t.url} no longer available`);return}let i=this.timeToLoad*1e3;if(e.code===429){let e=this.loader;if(typeof e?.getResponseHeader==`function`){let t=e.getResponseHeader(`Retry-After`);t&&(i=parseFloat(t)*1e3)}this.log(`Steering manifest ${t.url} rate limited`);return}this.scheduleRefresh(this.uri||t.url,i)},onTimeout:(e,t,n)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}})}scheduleRefresh(e,t=this.timeToLoad*1e3){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(e)},t)}};function mo(e,t,n,r){e&&Object.keys(t).forEach(i=>
26{let a=e.filter(e=>e.groupId===i).map(e=>{let a=o({},e);return a.details=void 0,a.attrs=new S(a.attrs),a.url=a.attrs.URI=ho(e.url,e.attrs[`STABLE-RENDITION-ID`],`PER-RENDITION-URIS`,n),a.groupId=a.attrs[`GROUP-ID`]=t[i],a.attrs[`PATHWAY-ID`]=r,a});e.push(...a)})}function ho(e,t,n,r){let{HOST:i,PARAMS:a,[n]:o}=r,s;t&&(s=o?.[t],s&&(e=s));let c=new self.URL(e);return i&&!s&&(c.host=i),a&&Object.keys(a).sort().forEach(e=>{e&&c.searchParams.set(e,a[e])}),c.href}var go=/^age:\s*[\d.]+\s*$/im,_o=class{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 E,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,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,n){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=n,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e)return;let n=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!this.stats.aborted)return i(n,t.url)}).catch(e=>(n.open(`GET`,t.url,!0),i(n,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(n,t,e)}).catch(e=>{this.callbacks.onError({code:n.status,text:e.message},t,n,r)}):this.openAndSendXhr(n,t,e)}openAndSendXhr(e,t,n){e.readyState||e.open(`GET`,t.url,!0);let r=this.context.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:a}=n.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),n.timeout=i&&l(i)?i:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:n}=this;if(!e||!t)return;let r=t.readyState,i=this.config;if(!n.aborted&&r>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let r=t.status,a=t.responseType!==`text`;if(r>=200&&r<300&&(a&&t.response||t.responseText!==null)){n.loading.end=Math.max(self.performance.now(),n.loading.first);let i=a?t.response:t.responseText;if(n.loaded=n.total=t.responseType===`arraybuffer`?i.byteLength:i.length,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first),!this.callbacks)return;let o=this.callbacks.onProgress;if(o&&o(n,e,i,t),!this.callbacks)return;let s={url:t.responseURL,data:i,code:r};this.callbacks.onSuccess(s,n,e,t)}else{let a=i.loadPolicy.errorRetry,o=n.retry;mn(a,o,!1,r)?this.retry(a):(y.error(`${r} while loading ${e.url}`),this.callbacks.onError({code:r,text:t.statusText},e,t,n))}}}loadtimeout(){let e=this.config?.loadPolicy.timeoutRetry,t=this.stats.retry;if(mn(e,t,!0))this.retry(e);else{y.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:n}=this;this.retryDelay=fn(e,n.retry),n.retry++,y.warn(`${status?`HTTP Status `+status:`Timeout`} while loading ${t.url}, retrying ${n.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&&go.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}};function vo(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var yo=/(\d+)-(\d+)\/(\d+)/,bo=class{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||wo,this.controller=new self.AbortController,this.stats=new E}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){let e=this.response;e!=null&&e.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,n){let r=this.stats;if(r.loading.start)throw Error(`Loader can only be used once.`);r.loading.start=self.performance.now();let i=xo(e,this.controller.signal),a=n.onProgress,o=e.responseType===`arraybuffer`,s=o?`byteLength`:`length`,{maxTimeToFirstByteMs:c,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=n,this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=c&&l(c)?c:u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),n.onTimeout(r,e,this.response)},t.timeout),self.fetch(this.request).then(i=>{this.response=this.loader=i;let s=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),n.onTimeout(r,e,this.response)},u-(s-r.loading.start)),!i.ok){let{status:e,statusText:t}=i;throw new To(t||`fetch, bad network response`,e,i)}return r.loading.first=s,r.total=Co(i.headers)||r.total,a&&l(t.highWaterMark)?this.loadProgressively(i,r,e,t.highWaterMark,a):o?i.arrayBuffer():e.responseType===`json`?i.json():i.text()}).then(i=>{let{response:o}=this;self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let c=i[s];c&&(r.loaded=r.total=c);let u={url:o.url,data:i,code:o.status};a&&!l(t.highWaterMark)&&a(r,e,i,o),n.onSuccess(u,r,e,o)}).catch(t=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;let i=t&&t.code||0,a=t?t.message:null;n.onError({code:i,text:a},e,t?t.details:null,r)}
vendor: 6,154 bytes, line 26
26)}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,n,r=0,i){let a=new zi,o=e.body.getReader(),s=()=>o.read().then(o=>{if(o.done)return a.dataLength&&i(t,n,a.flush(),e),Promise.resolve(new ArrayBuffer(0));let c=o.value,l=c.length;return t.loaded+=l,l<r||a.dataLength?(a.push(c),a.dataLength>=r&&i(t,n,a.flush(),e)):i(t,n,c,e),s()}).catch(()=>Promise.reject());return s()}};function xo(e,t){let n={method:`GET`,mode:`cors`,credentials:`same-origin`,signal:t,headers:new self.Headers(o({},e.headers))};return e.rangeEnd&&n.headers.set(`Range`,`bytes=`+e.rangeStart+`-`+String(e.rangeEnd-1)),n}function So(e){let t=yo.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function Co(e){let t=e.get(`Content-Range`);if(t){let e=So(t);if(l(e))return e}let n=e.get(`Content-Length`);if(n)return parseInt(n)}function wo(e,t){return new self.Request(e.url,t)}var To=class extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}},Eo=/\s/,Do={newCue(e,t,n,r){let i=[],a,o,s,c,l,u=self.VTTCue||self.TextTrackCue;for(let f=0;f<r.rows.length;f++)if(a=r.rows[f],s=!0,c=0,l=``,!a.isEmpty()){var d;for(let e=0;e<a.chars.length;e++)Eo.test(a.chars[e].uchar)&&s?c++:(l+=a.chars[e].uchar,s=!1);a.cueStartTime=t,t===n&&(n+=1e-4),c>=16?c--:c++;let r=Aa(l.trim()),p=Ia(t,n,r);e!=null&&(d=e.cues)!=null&&d.getCueById(p)||(o=new u(t,n,r),o.id=p,o.line=f+1,o.align=`left`,o.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(o))}return e&&i.length&&(i.sort((e,t)=>e.line===`auto`||t.line===`auto`?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),i.forEach(t=>Pt(e,t))),i}},Oo=i(i({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:_o,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Ri,bufferController:ea,capLevelController:io,errorController:Cn,fpsController:ao,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:fe,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},ko()),{},{subtitleStreamController:qi,subtitleTrackController:Yi,timelineController:eo,audioStreamController:Hi,audioTrackController:Ui,emeController:so,cmcdController:uo,contentSteeringController:po});function ko(){return{cueHandler:Do,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:`English`,captionsTextTrack1LanguageCode:`en`,captionsTextTrack2Label:`Spanish`,captionsTextTrack2LanguageCode:`es`,captionsTextTrack3Label:`Unknown CC`,captionsTextTrack3LanguageCode:``,captionsTextTrack4Label:`Unknown CC`,captionsTextTrack4LanguageCode:``,renderTextTracksNatively:!0}}function Ao(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(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error(`Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"`);if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error(`Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"`);let n=jo(e),r=[`manifest`,`level`,`frag`],a=[`TimeOut`,`MaxRetry`,`RetryDelay`,`MaxRetryTimeout`];
26return r.forEach(e=>{let r=`${e===`level`?`playlist`:e}LoadPolicy`,i=t[r]===void 0,o=[];a.forEach(a=>{let s=`${e}Loading${a}`,c=t[s];if(c!==void 0&&i){o.push(s);let e=n[r].default;switch(t[r]={default:e},a){case`TimeOut`:e.maxLoadTimeMs=c,e.maxTimeToFirstByteMs=c;break;case`MaxRetry`:e.errorRetry.maxNumRetry=c,e.timeoutRetry.maxNumRetry=c;break;case`RetryDelay`:e.errorRetry.retryDelayMs=c,e.timeoutRetry.retryDelayMs=c;break;case`MaxRetryTimeout`:e.errorRetry.maxRetryDelayMs=c,e.timeoutRetry.maxRetryDelayMs=c}}}),o.length&&y.warn(`hls.js config: "${o.join(`", "`)}" setting(s) are deprecated, use "${r}": ${JSON.stringify(t[r])}`)}),i(i({},n),t)}function jo(e){return e&&typeof e==`object`?Array.isArray(e)?e.map(jo):Object.keys(e).reduce((t,n)=>(t[n]=jo(e[n]),t),{}):e}function Mo(e){let t=e.loader;t!==bo&&t!==_o?(y.log(`[config]: Custom loader detected, cannot enable progressive streaming`),e.progressive=!1):vo()&&(e.loader=bo,e.progressive=!0,e.enableSoftwareAES=!0,y.log(`[config]: Progressive streaming enabled, using FetchLoader`))}var No=class e{static get version(){return`1.4.10`}static isSupported(){return or()}static get Events(){return u}static get ErrorTypes(){return d}static get ErrorDetails(){return f}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:Oo}static set DefaultConfig(t){e.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Ei,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,v(t.debug||!1,`Hls instance`);let n=this.config=Ao(e.DefaultConfig,t);this.userConfig=t,this._autoLevelCapping=-1,n.progressive&&Mo(n);let{abrController:r,bufferController:i,capLevelController:a,errorController:o,fpsController:s}=n,c=new o(this),l=this.abrController=new r(this),d=this.bufferController=new i(this),f=this.capLevelController=new a(this),p=new s(this),m=new Mt(this),h=new Wt(this),g=n.contentSteeringController,_=g?new g(this):null,y=this.levelController=new Dn(this,_),b=new An(this),x=new Ln(this.config),S=this.streamController=new Fi(this,b,x);f.setStreamController(S),p.setStreamController(S);let C=[m,y,S];_&&C.splice(1,0,_),this.networkControllers=C;let w=[l,d,f,p,h,b];this.audioTrackController=this.createController(n.audioTrackController,C);let T=n.audioStreamController;T&&C.push(new T(this,b,x)),this.subtitleTrackController=this.createController(n.subtitleTrackController,C);let E=n.subtitleStreamController;E&&C.push(new E(this,b,x)),this.createController(n.timelineController,w),x.emeController=this.emeController=this.createController(n.emeController,w),this.cmcdController=this.createController(n.cmcdController,w),this.latencyController=this.createController(Gt,w),this.coreComponents=w,C.push(c);let D=c.onErrorOut;typeof D==`function`&&this.on(u.ERROR,D,c)}createController(e,t){if(e){let n=new e(this);return t&&t.push(n),n}return null}on(e,t,n=this){this._emitter.on(e,t,n)}once(e,t,n=this){this._emitter.once(e,t,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,n=this,r){this._emitter.off(e,t,n,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,n){return this._emitter.emit(e,t,n)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){y.error(`An internal error happened while handling event `+e+`. Error message: "`+t.message+`". Here is a stacktrace:`,t),this.trigger(u.ERROR,{type:d.OTHER_ERROR,details:f.INTERNAL_EXCEPTION,fatal:!1,event:e,error:t})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){y.log(`destroy`),this.trigger(u.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEac
26h(e=>e.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){y.log(`attachMedia`),this._media=e,this.trigger(u.MEDIA_ATTACHING,{media:e})}detachMedia(){y.log(`detachMedia`),this.trigger(u.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();let t=this.media,r=this.url,i=this.url=n.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});y.log(`loadSource:${i}`),t&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(u.MANIFEST_LOADING,{url:e})}startLoad(e=-1){y.log(`startLoad(${e})`),this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){y.log(`stopLoad`),this.networkControllers.forEach(e=>{e.stopLoad()})}swapAudioCodec(){y.log(`swapAudioCodec`),this.streamController.swapAudioCodec()}recoverMediaError(){y.log(`recoverMediaError`);let e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,t=0){this.levelController.removeLevel(e,t)}get levels(){return this.levelController.levels||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){y.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){y.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){y.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){y.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){y.log(`set startLevel:${e}`),e!==-1&&(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&&(y.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Kt.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let n=e.length;for(let r=0;r<n;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:n}=this,r;if(r=t===-1&&e&&e.length?e.length-1:t,n)for(let t=r;t--;){let r=e[t].attrs[`HDCP-LEVEL`];if(r&&r<=n)return t}return r}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:!1}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}};No.defaultConfig=void 0;export{No as t};

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.