HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/pwa.sports-crowd.com/www/5813.f05820fe9d7e6b5e.js
"use strict";(self.webpackChunkapp=self.webpackChunkapp||[]).push([[5813],{85813:(Ic,$s,st)=>{st.r($s),st.d($s,{CapacitorVideoPlayerWeb:()=>Rc});var j=st(73308),Jr=st(22126);function Zr(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var s,i,r,a,o,Gs={exports:{}};s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,Gs.exports=o={buildAbsoluteURL:function(l,c,h){if(h=h||{},l=l.trim(),!(c=c.trim())){if(!h.alwaysNormalize)return l;var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(c);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):c;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&"/"!==f.path[0]){var m=i.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var g={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(g.netLoc=f.netLoc,"/"!==d.path[0]))if(d.path){var y=f.path,E=y.substring(0,y.lastIndexOf("/")+1)+d.path;g.path=o.normalizePath(E)}else g.path=f.path,d.params||(g.params=f.params,d.query||(g.query=f.query));return null===g.path&&(g.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(g)},parseURL:function(l){var c=s.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};var Nt=Gs.exports;function Ks(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,s)}return t}function re(n){for(var e=1;e<arguments.length;e++){var t=null!=arguments[e]?arguments[e]:{};e%2?Ks(Object(t),!0).forEach(function(s){sn(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):Ks(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function sn(n,e,t){return(e=function tn(n){var e=function en(n,e){if("object"!=typeof n||!n)return n;var t=n[Symbol.toPrimitive];if(void 0!==t){var s=t.call(n,e||"default");if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(n)}(n,"string");return"symbol"==typeof e?e:String(e)}(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function te(){return te=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=t[s])}return n},te.apply(this,arguments)}const F=Number.isFinite||function(n){return"number"==typeof n&&isFinite(n)},rn=Number.isSafeInteger||function(n){return"number"==typeof n&&Math.abs(n)<=nn},nn=Number.MAX_SAFE_INTEGER||9007199254740991;let p=function(n){return n.MEDIA_ATTACHING="hlsMediaAttaching",n.MEDIA_ATTACHED="hlsMediaAttached",n.MEDIA_DETACHING="hlsMediaDetaching",n.MEDIA_DETACHED="hlsMediaDetached",n.BUFFER_RESET="hlsBufferReset",n.BUFFER_CODECS="hlsBufferCodecs",n.BUFFER_CREATED="hlsBufferCreated",n.BUFFER_APPENDING="hlsBufferAppending",n.BUFFER_APPENDED="hlsBufferAppended",n.BUFFER_EOS="hlsBufferEos",n.BUFFER_FLUSHING="hlsBufferFlushing",n.BUFFER_FLUSHED="hlsBufferFlushed",n.MANIFEST_LOADING="hlsManifestLoading",n.MANIFEST_LOADED="hlsManifestLoaded",n.MANIFEST_PARSED="hlsManifestParsed",n.LEVEL_SWITCHING="hlsLevelSwitching",n.LEVEL_SWITCHED="hlsLevelSwitched",n.LEVEL_LOADING="hlsLevelLoading",n.LEVEL_LOADED="hlsLevelLoaded",n.LEVEL_UPDATED="hlsLevelUpdated",n.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",n.LEVELS_UPDATED="hlsLevelsUpdated",n.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",n.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",n.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",n.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",n.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",n.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",n.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",n.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",n.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",n.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",n.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",n.CUES_PARSED="hlsCuesParsed",n.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",n.INIT_PTS_FOUND="hlsInitPtsFound",n.FRAG_LOADING="hlsFragLoading",n.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",n.FRAG_LOADED="hlsFragLoaded",n.FRAG_DECRYPTED="hlsFragDecrypted",n.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",n.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",n.FRAG_PARSING_METADATA="hlsFragParsingMetadata",n.FRAG_PARSED="hlsFragParsed",n.FRAG_BUFFERED="hlsFragBuffered",n.FRAG_CHANGED="hlsFragChanged",n.FPS_DROP="hlsFpsDrop",n.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",n.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",n.ERROR="hlsError",n.DESTROYING="hlsDestroying",n.KEY_LOADING="hlsKeyLoading",n.KEY_LOADED="hlsKeyLoaded",n.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",n.BACK_BUFFER_REACHED="hlsBackBufferReached",n.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",n}({}),B=function(n){return n.NETWORK_ERROR="networkError",n.MEDIA_ERROR="mediaError",n.KEY_SYSTEM_ERROR="keySystemError",n.MUX_ERROR="muxError",n.OTHER_ERROR="otherError",n}({}),A=function(n){return n.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",n.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",n.KEY_SYSTEM_NO_SESSION="keySystemNoSession",n.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",n.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",n.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",n.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",n.MANIFEST_LOAD_ERROR="manifestLoadError",n.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",n.MANIFEST_PARSING_ERROR="manifestParsingError",n.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",n.LEVEL_EMPTY_ERROR="levelEmptyError",n.LEVEL_LOAD_ERROR="levelLoadError",n.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",n.LEVEL_PARSING_ERROR="levelParsingError",n.LEVEL_SWITCH_ERROR="levelSwitchError",n.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",n.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",n.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",n.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",n.FRAG_LOAD_ERROR="fragLoadError",n.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",n.FRAG_DECRYPT_ERROR="fragDecryptError",n.FRAG_PARSING_ERROR="fragParsingError",n.FRAG_GAP="fragGap",n.REMUX_ALLOC_ERROR="remuxAllocError",n.KEY_LOAD_ERROR="keyLoadError",n.KEY_LOAD_TIMEOUT="keyLoadTimeOut",n.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",n.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",n.BUFFER_APPEND_ERROR="bufferAppendError",n.BUFFER_APPENDING_ERROR="bufferAppendingError",n.BUFFER_STALLED_ERROR="bufferStalledError",n.BUFFER_FULL_ERROR="bufferFullError",n.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",n.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",n.INTERNAL_EXCEPTION="internalException",n.INTERNAL_ABORTED="aborted",n.UNKNOWN="unknown",n}({});const ke=function(){},Ut={trace:ke,debug:ke,log:ke,warn:ke,info:ke,error:ke};let ze=Ut;const v=ze,cn=/^(\d+)x(\d+)$/,Vs=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ee{constructor(e){"string"==typeof e&&(e=ee.parseAttrList(e)),te(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;const s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(2*i,2*i+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}bool(e){return"YES"===this[e]}decimalResolution(e){const t=cn.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const s={};for(Vs.lastIndex=0;null!==(t=Vs.exec(e));){let r=t[2];0===r.indexOf('"')&&r.lastIndexOf('"')===r.length-1&&(r=r.slice(1,-1)),s[t[1].trim()]=r}return s}}function hn(n){return"ID"!==n&&"CLASS"!==n&&"START-DATE"!==n&&"DURATION"!==n&&"END-DATE"!==n&&"END-ON-NEXT"!==n}function un(n){return"SCTE35-OUT"===n||"SCTE35-IN"===n}class Hs{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const s=t.attr;for(const i in s)if(Object.prototype.hasOwnProperty.call(e,i)&&e[i]!==s[i]){v.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=i;break}e=te(new ee({}),s,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const s=new Date(this.attr["END-DATE"]);F(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return null!==e?new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(F(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&&F(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class it{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}}}class Ws{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={audio:null,video:null,audiovideo:null},this.baseurl=e}setByteRange(e,t){const s=e.split("@",2);let i;i=1===s.length?t?.byteRangeEndOffset||0:parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}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=Nt.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class Bt extends Ws{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 it,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const s=Object.keys(this.levelkeys);if(1===s.length)return this._decryptdata=this.levelkeys[s[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime||!F(this.programDateTime))return null;const e=F(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),s=t.length;if(s>1||1===s&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,s,i,r,a=!1){const{elementaryStreams:o}=this,l=o[e];l?(l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,i),l.endDTS=Math.max(l.endDTS,r)):o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:a}}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e.audio=null,e.video=null,e.audiovideo=null}}class dn extends Ws{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new it,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=i;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}class gn{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)return this.advanced=!0,void(this.updated=!0);const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&s>0,this.misses=this.updated||this.advanced?Math.floor(.6*e.misses):e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return!!this.fragments.length&&F(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return null!=(e=this.fragments)&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function $t(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function Gt(n){return Uint8Array.from(unescape(encodeURIComponent(n)),e=>e.charCodeAt(0))}const Be=typeof self<"u"?self:void 0;var z={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ue_FAIRPLAY="com.apple.streamingkeydelivery",ue_PLAYREADY="com.microsoft.playready",ue_WIDEVINE="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Kt(n){switch(n){case ue_FAIRPLAY:return z.FAIRPLAY;case ue_PLAYREADY:return z.PLAYREADY;case ue_WIDEVINE:return z.WIDEVINE;case"org.w3.clearkey":return z.CLEARKEY}}function Vt(n){return"edef8ba979d64acea3c827dcd51d21ed"===n?z.WIDEVINE:"9a04f07998404286ab92e65be0885f95"===n?z.PLAYREADY:"1077efecc0b24d02ace33c1e52e2fb4b"===n||"e2719d58a985b3c9781ab030af78d30e"===n?z.CLEARKEY:void 0}function Ht(n){switch(n){case z.FAIRPLAY:return ue_FAIRPLAY;case z.PLAYREADY:return ue_PLAYREADY;case z.WIDEVINE:return ue_WIDEVINE;case z.CLEARKEY:return"org.w3.clearkey"}}function nt(n){const{drmSystems:e,widevineLicenseUrl:t}=n,s=e?[z.FAIRPLAY,z.WIDEVINE,z.PLAYREADY,z.CLEARKEY].filter(i=>!!e[i]):[];return!s[z.WIDEVINE]&&t&&s.push(z.WIDEVINE),s}const Ys=null!=Be&&null!=(n=Be.navigator)&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var n;function qs(n){const e=new Uint16Array(n.buffer,n.byteOffset,n.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),a=(new DOMParser).parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const l=$t(o).subarray(0,16);return function pn(n){const e=function(s,i,r){const a=s[i];s[i]=s[r],s[r]=a};e(n,0,3),e(n,1,2),e(n,4,5),e(n,6,7)}(l),l}}return null}function Fe(n,e,t){return Uint8Array.prototype.slice?n.slice(e,t):new Uint8Array(Array.prototype.slice.call(n,e,t))}const Wt=(n,e)=>e+10<=n.length&&73===n[e]&&68===n[e+1]&&51===n[e+2]&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128,js=(n,e)=>e+10<=n.length&&51===n[e]&&68===n[e+1]&&73===n[e+2]&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128,Xe=(n,e)=>{const t=e;let s=0;for(;Wt(n,e);)s+=10,s+=at(n,e+6),js(n,e+10)&&(s+=10),e+=s;if(s>0)return n.subarray(t,t+s)},at=(n,e)=>{let t=0;return t=(127&n[e])<<21,t|=(127&n[e+1])<<14,t|=(127&n[e+2])<<7,t|=127&n[e+3],t},xn=(n,e)=>Wt(n,e)&&at(n,e+6)+10<=n.length-e,Yt=n=>{const e=Xs(n);for(let t=0;t<e.length;t++){const s=e[t];if(zs(s))return In(s)}},zs=n=>n&&"PRIV"===n.key&&"com.apple.streaming.transportStreamTimestamp"===n.info,vn=n=>{const e=String.fromCharCode(n[0],n[1],n[2],n[3]),t=at(n,4);return{type:e,size:t,data:n.subarray(10,10+t)}},Xs=n=>{let e=0;const t=[];for(;Wt(n,e);){const s=at(n,e+6);e+=10;const i=e+s;for(;e+8<i;){const r=vn(n.subarray(e)),a=Sn(r);a&&t.push(a),e+=r.size+10}js(n,e)&&(e+=10)}return t},Sn=n=>"PRIV"===n.type?An(n):"W"===n.type[0]?Rn(n):Ln(n),An=n=>{if(n.size<2)return;const e=xe(n.data,!0),t=new Uint8Array(n.data.subarray(e.length+1));return{key:n.type,info:e,data:t.buffer}},Ln=n=>{if(n.size<2)return;if("TXXX"===n.type){let t=1;const s=xe(n.data.subarray(t),!0);t+=s.length+1;const i=xe(n.data.subarray(t));return{key:n.type,info:s,data:i}}const e=xe(n.data.subarray(1));return{key:n.type,data:e}},Rn=n=>{if("WXXX"===n.type){if(n.size<2)return;let t=1;const s=xe(n.data.subarray(t),!0);t+=s.length+1;const i=xe(n.data.subarray(t));return{key:n.type,info:s,data:i}}const e=xe(n.data);return{key:n.type,data:e}},In=n=>{if(8===n.data.byteLength){const e=new Uint8Array(n.data);let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,1&e[3]&&(s+=47721858.84),Math.round(s)}},xe=(n,e=!1)=>{const t=function bn(){if(!navigator.userAgent.includes("PlayStation 4"))return!qt&&typeof self.TextDecoder<"u"&&(qt=new self.TextDecoder("utf-8")),qt}();if(t){const c=t.decode(n);if(e){const h=c.indexOf("\0");return-1!==h?c.substring(0,h):c}return c.replace(/\0/g,"")}const s=n.length;let i,r,a,o="",l=0;for(;l<s;){if(i=n[l++],0===i&&e)return o;if(0!==i&&3!==i)switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:r=n[l++],o+=String.fromCharCode((31&i)<<6|63&r);break;case 14:r=n[l++],a=n[l++],o+=String.fromCharCode((15&i)<<12|(63&r)<<6|(63&a)<<0)}}return o};let qt;const ve_hexDump=function(n){let e="";for(let t=0;t<n.length;t++){let s=n[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e},ot=Math.pow(2,32)-1,Dn=[].push,Qs={video:1,audio:2,id3:3,text:4};function ie(n){return String.fromCharCode.apply(null,n)}function Js(n,e){const t=n[e]<<8|n[e+1];return t<0?65536+t:t}function M(n,e){const t=ei(n,e);return t<0?4294967296+t:t}function Zs(n,e){let t=M(n,e);return t*=Math.pow(2,32),t+=M(n,e+4),t}function ei(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]}function jt(n,e,t){n[e]=t>>24,n[e+1]=t>>16&255,n[e+2]=t>>8&255,n[e+3]=255&t}function K(n,e){const t=[];if(!e.length)return t;const s=n.byteLength;for(let i=0;i<s;){const r=M(n,i),o=r>1?i+r:s;if(ie(n.subarray(i+4,i+8))===e[0])if(1===e.length)t.push(n.subarray(i+8,o));else{const l=K(n.subarray(i+8,o),e.slice(1));l.length&&Dn.apply(t,l)}i=o}return t}function _n(n){const e=[],t=n[0];let s=8;const i=M(n,s);s+=4;let r=0,a=0;0===t?(r=M(n,s),a=M(n,s+4),s+=8):(r=Zs(n,s),a=Zs(n,s+8),s+=16),s+=2;let o=n.length+a;const l=Js(n,s);s+=2;for(let c=0;c<l;c++){let h=s;const u=M(n,h);h+=4;const d=2147483647&u;if((2147483648&u)>>>31==1)return v.warn("SIDX has hierarchical references (not supported)"),null;const m=M(n,h);h+=4,e.push({referenceSize:d,subsegmentDuration:m,info:{duration:m/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:l,references:e}}function ti(n){const e=[],t=K(n,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],a=K(r,["tkhd"])[0];if(a){let o=a[0];const l=M(a,0===o?12:20),c=K(r,["mdia","mdhd"])[0];if(c){o=c[0];const h=M(c,0===o?12:20),u=K(r,["mdia","hdlr"])[0];if(u){const f={soun:"audio",vide:"video"}[ie(u.subarray(8,12))];if(f){const g=wn(K(r,["mdia","minf","stbl","stsd"])[0]);e[l]={timescale:h,type:f},e[f]=re({timescale:h,id:l},g)}}}}}return K(n,["moov","mvex","trex"]).forEach(i=>{const r=M(i,4),a=e[r];a&&(a.default={duration:M(i,12),flags:M(i,20)})}),e}function wn(n){const e=n.subarray(8),t=e.subarray(86),s=ie(e.subarray(4,8));let i=s;const r="enca"===s||"encv"===s;if(r){const o=K(e,[s])[0].subarray("enca"===s?28:78);K(o,["sinf"]).forEach(c=>{const h=K(c,["schm"])[0];if(h){const u=ie(h.subarray(4,8));if("cbcs"===u||"cenc"===u){const d=K(c,["frma"])[0];d&&(i=ie(d))}}})}switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const a=K(t,["avcC"])[0];i+="."+lt(a[1])+lt(a[2])+lt(a[3]);break}case"mp4a":{const a=K(e,[s])[0],o=K(a.subarray(28),["esds"])[0];if(o&&o.length>12){let l=4;if(3!==o[l++])break;l=zt(o,l),l+=2;const c=o[l++];if(128&c&&(l+=2),64&c&&(l+=o[l++]),4!==o[l++])break;l=zt(o,l);const h=o[l++];if(64!==h)break;if(i+="."+lt(h),l+=12,5!==o[l++])break;l=zt(o,l);const u=o[l++];let d=(248&u)>>3;31===d&&(d+=1+((7&u)<<3)+((224&o[l])>>5)),i+="."+d}break}case"hvc1":case"hev1":{const a=K(t,["hvcC"])[0],o=a[1],l=["","A","B","C"][o>>6],c=31&o,h=M(a,2),u=(32&o)>>5?"H":"L",d=a[12],f=a.subarray(6,12);i+="."+l+c,i+="."+h.toString(16).toUpperCase(),i+="."+u+d;let m="";for(let g=f.length;g--;){const y=f[g];(y||m)&&(m="."+y.toString(16).toUpperCase()+m)}i+=m;break}case"dvh1":case"dvhe":{const a=K(t,["dvcC"])[0],l=a[2]<<5&32|a[3]>>3&31;i+="."+Se(a[2]>>1&127)+"."+Se(l);break}case"vp09":{const a=K(t,["vpcC"])[0],l=a[5],c=a[6]>>4&15;i+="."+Se(a[4])+"."+Se(l)+"."+Se(c);break}case"av01":{const a=K(t,["av1C"])[0],o=a[1]>>>5,c=a[2]>>>7?"H":"M",h=(64&a[2])>>6,d=2===o&&h?(32&a[2])>>5?12:10:h?10:8,f=(16&a[2])>>4,m=(8&a[2])>>3,g=(4&a[2])>>2,y=3&a[2],E=1,T=1,x=1,R=0;i+="."+o+"."+Se(31&a[1])+c+"."+Se(d)+"."+f+"."+m+g+y+"."+Se(E)+"."+Se(T)+"."+Se(x)+"."+R;break}}return{codec:i,encrypted:r}}function zt(n,e){const t=e+5;for(;128&n[e++]&&e<t;);return e}function lt(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function Se(n){return(n<10?"0":"")+n}function si(n){const e=K(n,["schm"])[0];if(e){const t=ie(e.subarray(4,8));if("cbcs"===t||"cenc"===t)return K(n,["schi","tenc"])[0]}return null}function On(n){const e=M(n,0);let t=8;1&e&&(t+=4),4&e&&(t+=4);let s=0;const i=M(n,4);for(let r=0;r<i;r++)256&e&&(s+=M(n,t),t+=4),512&e&&(t+=4),1024&e&&(t+=4),2048&e&&(t+=4);return s}function fe(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function ii(n,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let a=!1;return K(s,["moof"]).map(l=>{const c=l.byteOffset-8;K(l,["traf"]).map(u=>{const d=K(u,["tfdt"]).map(f=>{const m=f[0];let g=M(f,4);return 1===m&&(g*=Math.pow(2,32),g+=M(f,8)),g/i})[0];return void 0!==d&&(n=d),K(u,["tfhd"]).map(f=>{const m=M(f,4),g=16777215&M(f,0);let x=0;const R=0!=(16&g);let S=0;const b=0!=(32&g);let L=8;m===r&&(0!=(1&g)&&(L+=8),0!=(2&g)&&(L+=4),0!=(8&g)&&(x=M(f,L),L+=4),R&&(S=M(f,L),L+=4),b&&(L+=4),"video"===e.type&&(a=function Un(n){if(!n)return!1;const e=n.indexOf("."),t=e<0?n:n.substring(0,e);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}(e.codec)),K(u,["trun"]).map(C=>{const w=C[0],I=16777215&M(C,0),_=0!=(1&I);let V=0;const P=0!=(4&I),G=0!=(256&I);let $=0;const U=0!=(512&I);let Y=0;const J=0!=(1024&I),O=0!=(2048&I);let k=0;const q=M(C,4);let H=8;_&&(V=M(C,H),H+=4),P&&(H+=4);let Q=V+c;for(let se=0;se<q;se++){if(G?($=M(C,H),H+=4):$=x,U?(Y=M(C,H),H+=4):Y=S,J&&(H+=4),O&&(k=0===w?M(C,H):ei(C,H),H+=4),"video"===e.type){let le=0;for(;le<Y;){const ce=M(s,Q);Q+=4,Bn(a,s[Q])&&ri(s.subarray(Q,Q+ce),a?2:1,n+k/i,t),Q+=ce,le+=ce+4}}n+=$/i}}))})})}),t}function Bn(n,e){if(n){const t=e>>1&63;return 39===t||40===t}return 6==(31&e)}function ri(n,e,t,s){const i=ni(n);let r=0;r+=e;let a=0,o=0,l=0;for(;r<i.length;){a=0;do{if(r>=i.length)break;l=i[r++],a+=l}while(255===l);o=0;do{if(r>=i.length)break;l=i[r++],o+=l}while(255===l);const c=i.length-r;let h=r;if(o<c)r+=o;else if(o>c){v.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(4===a){if(181===i[h++]){const d=Js(i,h);if(h+=2,49===d){const f=M(i,h);if(h+=4,1195456820===f){const m=i[h++];if(3===m){const g=i[h++],E=64&g,T=E?2+3*(31&g):0,x=new Uint8Array(T);if(E){x[0]=g;for(let R=1;R<T;R++)x[R]=i[h++]}s.push({type:m,payloadType:a,pts:t,bytes:x})}}}}}else if(5===a&&o>16){const u=[];for(let m=0;m<16;m++){const g=i[h++].toString(16);u.push(1==g.length?"0"+g:g),(3===m||5===m||7===m||9===m)&&u.push("-")}const d=o-16,f=new Uint8Array(d);for(let m=0;m<d;m++)f[m]=i[h++];s.push({payloadType:a,pts:t,uuid:u.join(""),userData:xe(f),userDataBytes:f})}}}function ni(n){const e=n.byteLength,t=[];let s=1;for(;s<e-2;)0===n[s]&&0===n[s+1]&&3===n[s+2]?(t.push(s+2),s+=2):s++;if(0===t.length)return n;const i=e-t.length,r=new Uint8Array(i);let a=0;for(s=0;s<i;a++,s++)a===t[0]&&(a++,t.shift()),r[s]=n[a];return r}function Hn(n){const e=n.getUint32(0),t=n.byteOffset,s=n.byteLength;if(s<e)return{offset:t,size:s};if(1886614376!==n.getUint32(4))return{offset:t,size:e};const r=n.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:t,size:e};const a=n.buffer,o=ve_hexDump(new Uint8Array(a,t+12,16)),l=n.getUint32(28);let c=null,h=null;if(0===r){if(e-32<l||l<22)return{offset:t,size:e};h=new Uint8Array(a,t+32,l)}else if(1===r){if(!l||s<t+32+16*l+16)return{offset:t,size:e};c=[];for(let u=0;u<l;u++)c.push(new Uint8Array(a,t+32+16*u,16))}return{version:r,systemId:o,kids:c,data:h,offset:t,size:e}}let ct={};class Qe{static clearKeyUriToKeyIdMap(){ct={}}constructor(e,t,s,i=[1],r=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&"AES-128"!==e}isSupported(){if(this.method){if("AES-128"===this.method||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case ue_FAIRPLAY:case ue_WIDEVINE:case ue_PLAYREADY:case"org.w3.clearkey":return-1!==["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if("AES-128"===this.method&&this.uri&&!this.iv){"number"!=typeof e&&("AES-128"===this.method&&!this.iv&&v.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const s=function Wn(n){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=n>>8*(15-t)&255;return e}(e);return new Qe(this.method,this.uri,"identity",this.keyFormatVersions,s)}const t=function yn(n){const e=n.split(":");let t=null;if("data"===e[0]&&2===e.length){const s=e[1].split(";"),i=s[s.length-1].split(",");if(2===i.length){const a=i[1];"base64"===i[0]?(s.splice(-1,1),t=$t(a)):t=function mn(n){const e=Gt(n).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}(a)}}return t}(this.uri);if(t)switch(this.keyFormat){case ue_WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case ue_PLAYREADY:{const s=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function Kn(n,e,t){if(16!==n.byteLength)throw new RangeError("Invalid system id");let s,i,r;if(e){s=1,i=new Uint8Array(16*e.length);for(let o=0;o<e.length;o++){const l=e[o];if(16!==l.byteLength)throw new RangeError("Invalid key");i.set(l,16*o)}}else s=0,i=new Uint8Array;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const a=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),function Gn(n,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=255&s,r.set(n,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}([112,115,115,104],new Uint8Array([s,0,0,0]),n,r,i,a,t||new Uint8Array)}(s,null,t),this.keyId=qs(t);break}default:{let s=t.subarray(0,16);if(16!==s.length){const i=new Uint8Array(16);i.set(s,16-s.length),s=i}this.keyId=s;break}}if(!this.keyId||16!==this.keyId.byteLength){let s=ct[this.uri];if(!s){const i=Object.keys(ct).length%Number.MAX_SAFE_INTEGER;s=new Uint8Array(16),new DataView(s.buffer,12,4).setUint32(0,i),ct[this.uri]=s}this.keyId=s}return this}}const ai=/\{\$([a-zA-Z0-9-_]+)\}/g;function oi(n){return ai.test(n)}function de(n,e,t){if(null!==n.variableList||n.hasVariableRefs)for(let s=t.length;s--;){const i=t[s],r=e[i];r&&(e[i]=Xt(n,r))}}function Xt(n,e){if(null!==n.variableList||n.hasVariableRefs){const t=n.variableList;return e.replace(ai,s=>{const i=s.substring(2,s.length-1),r=t?.[i];return void 0===r?(n.playlistParsingError||(n.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function li(n,e,t){let i,r,s=n.variableList;if(s||(n.variableList=s={}),"QUERYPARAM"in e){i=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(!a.has(i))throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`);r=a.get(i)}catch(a){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,r=e.VALUE;i in s?n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function Yn(n,e,t){const s=e.IMPORT;if(t&&s in t){let i=n.variableList;i||(n.variableList=i={}),i[s]=t[s]}else n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}function Oe(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}const ht={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Qt(n,e,t=!0){return!n.split(",").some(s=>!ci(s,e,t))}function ci(n,e,t=!0){var s;const i=Oe(t);return null!=(s=i?.isTypeSupported(Je(n,e)))&&s}function Je(n,e){return`${e}/mp4;codecs="${n}"`}function hi(n){if(n){const e=n.substring(0,4);return ht.video[e]}return 2}function ut(n){return n.split(",").reduce((e,t)=>{const s=ht.video[t];return s?(2*s+e)/(e?3:2):(ht.audio[t]+e)/(e?2:1)},0)}const Jt={},Xn=/flac|opus/i;function dt(n,e=!0){return n.replace(Xn,t=>function zn(n,e=!0){if(Jt[n])return Jt[n];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[n];for(let s=0;s<t.length;s++)if(ci(t[s],"audio",e))return Jt[n]=t[s],t[s];return n}(t.toLowerCase(),e))}function ui(n,e){return n&&"mp4a"!==n?n:e&&e.split(",")[0]}const di=/#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,fi=/#EXT-X-MEDIA:(.*)/g,Jn=/^#EXT(?:INF|-X-TARGETDURATION):/m,gi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Zn=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Ae{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return Nt.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Jn.test(e)}static parseMasterPlaylist(e,t){const i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:oi(e)},r=[];let a;for(di.lastIndex=0;null!=(a=di.exec(e));)if(a[1]){var o;const c=new ee(a[1]);de(i,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const h=Xt(i,a[2]),u={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:Ae.resolve(h,t)},d=c.decimalResolution("RESOLUTION");d&&(u.width=d.width,u.height=d.height),ea(c.CODECS,u),null!=(o=u.unknownCodecs)&&o.length||r.push(u),i.levels.push(u)}else if(a[3]){const h=a[4];switch(a[3]){case"SESSION-DATA":{const u=new ee(h);de(i,u,["DATA-ID","LANGUAGE","VALUE","URI"]);const d=u["DATA-ID"];d&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[d]=u);break}case"SESSION-KEY":{const u=mi(h,t,i);u.encrypted&&u.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(u)):v.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{const u=new ee(h);de(i,u,["NAME","VALUE","QUERYPARAM"]),li(i,u,t)}break;case"CONTENT-STEERING":{const u=new ee(h);de(i,u,["SERVER-URI","PATHWAY-ID"]),i.contentSteering={uri:Ae.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=pi(h)}}return i.levels=r.length>0&&r.length<i.levels.length?r:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},a=s.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(fi.lastIndex=0;null!==(i=fi.exec(e));){const c=new ee(i[1]),h=c.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d,de(s,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const f=c.LANGUAGE,m=c["ASSOC-LANGUAGE"],g=c.CHANNELS,y=c.CHARACTERISTICS,E=c["INSTREAM-ID"],T={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||f||"",type:h,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:f,url:c.URI?Ae.resolve(c.URI,t):""};if(m&&(T.assocLang=m),g&&(T.channels=g),y&&(T.characteristics=y),E&&(T.instreamId=E),null!=u&&u.length){const x=Ae.findGroup(u,T.groupId)||u[0];yi(T,x,"audioCodec"),yi(T,x,"textCodec")}d.push(T)}}return r}static parseLevelPlaylist(e,t,s,i,r,a){const o=new gn(t),l=o.fragments;let y,E,T,c=null,h=0,u=0,d=0,f=0,m=null,g=new Bt(i,t),x=-1,R=!1,S=null;for(gi.lastIndex=0,o.m3u8=e,o.hasVariableRefs=oi(e);null!==(y=gi.exec(e));){R&&(R=!1,g=new Bt(i,t),g.start=d,g.sn=h,g.cc=f,g.level=s,c&&(g.initSegment=c,g.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,S&&(g.setByteRange(S),S=null)));const w=y[1];if(w){g.duration=parseFloat(w);const I=(" "+y[2]).slice(1);g.title=I||null,g.tagList.push(I?["INF",w,I]:["INF",w])}else if(y[3]){if(F(g.duration)){g.start=d,T&&xi(g,T,o),g.sn=h,g.level=s,g.cc=f,l.push(g);const I=(" "+y[3]).slice(1);g.relurl=Xt(o,I),Ei(g,m),m=g,d+=g.duration,h++,u=0,R=!0}}else if(y[4]){const I=(" "+y[4]).slice(1);m?g.setByteRange(I,m):g.setByteRange(I)}else if(y[5])g.rawProgramDateTime=(" "+y[5]).slice(1),g.tagList.push(["PROGRAM-DATE-TIME",g.rawProgramDateTime]),-1===x&&(x=l.length);else{if(y=y[0].match(Zn),!y){v.warn("No matches on slow regex match for level playlist!");continue}for(E=1;E<y.length&&!(typeof y[E]<"u");E++);const I=(" "+y[E]).slice(1),_=(" "+y[E+1]).slice(1),V=y[E+2]?(" "+y[E+2]).slice(1):"";switch(I){case"PLAYLIST-TYPE":o.type=_.toUpperCase();break;case"MEDIA-SEQUENCE":h=o.startSN=parseInt(_);break;case"SKIP":{const P=new ee(_);de(o,P,["RECENTLY-REMOVED-DATERANGES"]);const G=P.decimalInteger("SKIPPED-SEGMENTS");if(F(G)){o.skippedSegments=G;for(let U=G;U--;)l.unshift(null);h+=G}const $=P.enumeratedString("RECENTLY-REMOVED-DATERANGES");$&&(o.recentlyRemovedDateranges=$.split("\t"));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(_),1);break;case"VERSION":o.version=parseInt(_);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":o.live=!1;break;case"#":(_||V)&&g.tagList.push(V?[_,V]:[_]);break;case"DISCONTINUITY":f++,g.tagList.push(["DIS"]);break;case"GAP":g.gap=!0,g.tagList.push([I]);break;case"BITRATE":g.tagList.push([I,_]);break;case"DATERANGE":{const P=new ee(_);de(o,P,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),de(o,P,P.clientAttrs);const G=new Hs(P,o.dateRanges[P.ID]);G.isValid||o.skippedSegments?o.dateRanges[G.id]=G:v.warn(`Ignoring invalid DATERANGE tag: "${_}"`),g.tagList.push(["EXT-X-DATERANGE",_]);break}case"DEFINE":{const P=new ee(_);de(o,P,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in P?Yn(o,P,a):li(o,P,t)}break;case"DISCONTINUITY-SEQUENCE":f=parseInt(_);break;case"KEY":{const P=mi(_,t,o);if(P.isSupported()){if("NONE"===P.method){T=void 0;break}T||(T={}),T[P.keyFormat]&&(T=te({},T)),T[P.keyFormat]=P}else v.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${_}"`);break}case"START":o.startTimeOffset=pi(_);break;case"MAP":{const P=new ee(_);if(de(o,P,["BYTERANGE","URI"]),g.duration){const G=new Bt(i,t);Ti(G,P,s,T),c=G,g.initSegment=c,c.rawProgramDateTime&&!g.rawProgramDateTime&&(g.rawProgramDateTime=c.rawProgramDateTime)}else{const G=g.byteRangeEndOffset;if(G){const $=g.byteRangeStartOffset;S=`${G-$}@${$}`}else S=null;Ti(g,P,s,T),c=g,R=!0}break}case"SERVER-CONTROL":{const P=new ee(_);o.canBlockReload=P.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=P.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&P.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=P.optionalFloat("PART-HOLD-BACK",0),o.holdBack=P.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const P=new ee(_);o.partTarget=P.decimalFloatingPoint("PART-TARGET");break}case"PART":{let P=o.partList;P||(P=o.partList=[]);const G=u>0?P[P.length-1]:void 0,$=u++,U=new ee(_);de(o,U,["BYTERANGE","URI"]);const Y=new dn(U,g,t,$,G);P.push(Y),g.duration+=Y.duration;break}case"PRELOAD-HINT":{const P=new ee(_);de(o,P,["URI"]),o.preloadHint=P;break}case"RENDITION-REPORT":{const P=new ee(_);de(o,P,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(P);break}default:v.warn(`line parsed but not handled: ${y}`)}}}m&&!m.relurl?(l.pop(),d-=m.duration,o.partList&&(o.fragmentHint=m)):o.partList&&(Ei(g,m),g.cc=f,o.fragmentHint=g,T&&xi(g,T,o));const b=l.length,L=l[0],C=l[b-1];if(d+=o.skippedSegments*o.targetduration,d>0&&b&&C){o.averagetargetduration=d/b;const w=C.sn;o.endSN="initSegment"!==w?w:0,o.live||(C.endList=!0),L&&(o.startCC=L.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(d+=o.fragmentHint.duration),o.totalduration=d,o.endCC=f,x>0&&function ta(n,e){let t=n[e];for(let s=e;s--;){const i=n[s];if(!i)return;i.programDateTime=t.programDateTime-1e3*i.duration,t=i}}(l,x),o}}function mi(n,e,t){var s,i;const r=new ee(n);de(t,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=null!=(s=r.METHOD)?s:"",o=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,h=null!=(i=r.KEYFORMAT)?i:"identity";o&&r.IV&&!l&&v.error(`Invalid IV: ${r.IV}`);const u=o?Ae.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Qe(a,u,h,d,l)}function pi(n){const t=new ee(n).decimalFloatingPoint("TIME-OFFSET");return F(t)?t:null}function ea(n,e){let t=(n||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>function jn(n,e){const t=ht[e];return!!t&&!!t[n.slice(0,4)]}(r,s));i.length&&(e[`${s}Codec`]=i.join(","),t=t.filter(r=>-1===i.indexOf(r)))}),e.unknownCodecs=t}function yi(n,e,t){const s=e[t];s&&(n[t]=s)}function Ei(n,e){n.rawProgramDateTime?n.programDateTime=Date.parse(n.rawProgramDateTime):null!=e&&e.programDateTime&&(n.programDateTime=e.endProgramDateTime),F(n.programDateTime)||(n.programDateTime=null,n.rawProgramDateTime=null)}function Ti(n,e,t,s){n.relurl=e.URI,e.BYTERANGE&&n.setByteRange(e.BYTERANGE),n.level=t,n.sn="initSegment",s&&(n.levelkeys=s),n.initSegment=null}function xi(n,e,t){n.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(n)}function vi(n){const{type:e}=n;switch(e){case"audioTrack":return"audio";case"subtitleTrack":return"subtitle";default:return"main"}}function Zt(n,e){let t=n.url;return(void 0===t||0===t.indexOf("data:"))&&(t=e.url),t}class sa{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(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,a=new(t.pLoader||t.loader)(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:"manifest",url:s,deliveryDirectives:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:a,deliveryDirectives:o}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:"level",url:a,deliveryDirectives:o})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:"audioTrack",url:r,deliveryDirectives:a})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:a}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:"subtitleTrack",url:r,deliveryDirectives:a})}load(e){var t;const s=this.hls.config;let r,i=this.getInternalLoader(e);if(i){const c=i.context;if(c&&c.url===e.url&&c.level===e.level)return void v.trace("[playlist-loader]: playlist request ongoing");v.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}if(r="manifest"===e.type?s.manifestLoadPolicy.default:te({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),F(null==(t=e.deliveryDirectives)?void 0:t.part)){let c;if("level"===e.type&&null!==e.level?c=this.hls.levels[e.level].details:"audioTrack"===e.type&&null!==e.id?c=this.hls.audioTracks[e.id].details:"subtitleTrack"===e.type&&null!==e.id&&(c=this.hls.subtitleTracks[e.id].details),c){const h=c.partTarget,u=c.targetduration;if(h&&u){const d=1e3*Math.max(3*h,.8*u);r=te({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{};i.load(e,{loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},{onSuccess:(c,h,u,d)=>{const f=this.getInternalLoader(u);this.resetInternalLoader(u.type);const m=c.data;0===m.indexOf("#EXTM3U")?(h.parsing.start=performance.now(),Ae.isMediaPlaylist(m)?this.handleTrackOrLevelPlaylist(c,h,u,d||null,f):this.handleMasterPlaylist(c,h,u,d)):this.handleManifestParsingError(c,u,new Error("no EXTM3U delimiter"),d||null,h)},onError:(c,h,u,d)=>{this.handleNetworkError(h,u,!1,c,d)},onTimeout:(c,h,u)=>{this.handleNetworkError(h,u,!0,void 0,c)}})}handleMasterPlaylist(e,t,s,i){const r=this.hls,a=e.data,o=Zt(e,s),l=Ae.parseMasterPlaylist(a,o);if(l.playlistParsingError)return void this.handleManifestParsingError(e,s,l.playlistParsingError,i,t);const{contentSteering:c,levels:h,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:m}=l;this.variableList=m;const{AUDIO:g=[],SUBTITLES:y,"CLOSED-CAPTIONS":E}=Ae.parseMasterPlaylistMedia(a,o,l);g.length&&!g.some(x=>!x.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(v.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ee({}),bitrate:0,url:""})),r.trigger(p.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:y,captions:E,contentSteering:c,url:o,stats:t,networkDetails:i,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,t,s,i,r){const a=this.hls,{id:o,level:l,type:c}=s,h=Zt(e,s),d=F(l)?l:F(o)?o:0,f=vi(s),m=Ae.parseLevelPlaylist(e.data,h,d,f,0,this.variableList);if("manifest"===c){const g={attrs:new ee({}),bitrate:0,details:m,name:"",url:h};a.trigger(p.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=m,this.handlePlaylistLoaded(m,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(p.ERROR,{type:B.NETWORK_ERROR,details:A.MANIFEST_PARSING_ERROR,fatal:"manifest"===t.type,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let a=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;"level"===e.type?a+=`: ${e.level} id: ${e.id}`:("audioTrack"===e.type||"subtitleTrack"===e.type)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);v.warn(`[playlist-loader]: ${a}`);let l=A.UNKNOWN,c=!1;const h=this.getInternalLoader(e);switch(e.type){case"manifest":l=s?A.MANIFEST_LOAD_TIMEOUT:A.MANIFEST_LOAD_ERROR,c=!0;break;case"level":l=s?A.LEVEL_LOAD_TIMEOUT:A.LEVEL_LOAD_ERROR,c=!1;break;case"audioTrack":l=s?A.AUDIO_TRACK_LOAD_TIMEOUT:A.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case"subtitleTrack":l=s?A.SUBTITLE_TRACK_LOAD_TIMEOUT:A.SUBTITLE_LOAD_ERROR,c=!1}h&&this.resetInternalLoader(e.type);const u={type:B.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};i&&(u.response=re({url:t?.url||e.url,data:void 0},i)),this.hls.trigger(p.ERROR,u)}handlePlaylistLoaded(e,t,s,i,r,a){const o=this.hls,{type:l,level:c,id:h,groupId:u,deliveryDirectives:d}=i,f=Zt(t,i),m=vi(i),g="number"==typeof i.level&&"main"===m?c:void 0;if(!e.fragments.length){const E=new Error("No Segments found in Playlist");return void o.trigger(p.ERROR,{type:B.NETWORK_ERROR,details:A.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:E,reason:E.message,response:t,context:i,level:g,parent:m,networkDetails:r,stats:s})}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const y=e.playlistParsingError;if(y)o.trigger(p.ERROR,{type:B.NETWORK_ERROR,details:A.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:y,reason:y.message,response:t,context:i,level:g,parent:m,networkDetails:r,stats:s});else switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case"manifest":case"level":o.trigger(p.LEVEL_LOADED,{details:e,level:g||0,id:h||0,stats:s,networkDetails:r,deliveryDirectives:d});break;case"audioTrack":o.trigger(p.AUDIO_TRACK_LOADED,{details:e,id:h||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:d});break;case"subtitleTrack":o.trigger(p.SUBTITLE_TRACK_LOADED,{details:e,id:h||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:d})}}}function Si(n,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=n,e.dispatchEvent(t)}function Ai(n,e){const t=n.mode;if("disabled"===t&&(n.mode="hidden"),n.cues&&!n.cues.getCueById(e.id))try{if(n.addCue(e),!n.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){v.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,n.addCue(i)}catch(i){v.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}"disabled"===t&&(n.mode=t)}function $e(n){const e=n.mode;if("disabled"===e&&(n.mode="hidden"),n.cues)for(let t=n.cues.length;t--;)n.removeCue(n.cues[t]);"disabled"===e&&(n.mode=e)}function es(n,e,t,s){const i=n.mode;if("disabled"===i&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=function ra(n,e,t){const s=[],i=function ia(n,e){if(e<n[0].startTime)return 0;const t=n.length-1;if(e>n[t].endTime)return-1;let s=0,i=t;for(;s<=i;){const r=Math.floor((i+s)/2);if(e<n[r].startTime)i=r-1;else{if(!(e>n[r].startTime&&s<t))return r;s=r+1}}return n[s].startTime-e<e-n[i].startTime?s:i}(n,e);if(i>-1)for(let r=i,a=n.length;r<a;r++){const o=n[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}(n.cues,e,t);for(let a=0;a<r.length;a++)(!s||s(r[a]))&&n.removeCue(r[a])}"disabled"===i&&(n.mode=i)}function ft(n){const e=[];for(let t=0;t<n.length;t++){const s=n[t];("subtitles"===s.kind||"captions"===s.kind)&&s.label&&e.push(n[t])}return e}var ye_emsg="https://aomedia.org/emsg/ID3";function ts(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Li(n,e,t,s,i){let r=new n(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new n(e,t,JSON.stringify(i?re({type:i},s):s))}return r}const gt=(()=>{const n=ts();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function ss(n,e){return n.getTime()/1e3-e}function aa(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class oa{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(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&($e(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if("metadata"===s.kind&&"id3"===s.label)return Si(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:i}}}=this;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=ts();if(a)for(let o=0;o<r.length;o++){const l=r[o].type;if(l===ye_emsg&&!s||!i)continue;const c=Xs(r[o].data);if(c){const h=r[o].pts;let u=h+r[o].duration;u>gt&&(u=gt),u-h<=0&&(u=h+.25);for(let f=0;f<c.length;f++){const m=c[f];if(!zs(m)){this.updateId3CueEnds(h,l);const g=Li(a,h,u,m,l);g&&this.id3Track.addCue(g)}}}}}updateId3CueEnds(e,t){var s;const i=null==(s=this.id3Track)?void 0:s.cues;if(i)for(let r=i.length;r--;){const a=i[r];a.type===t&&a.startTime<e&&a.endTime===gt&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(r&&(o||l)){let c;c="audio"===i?h=>"org.id3"===h.type&&l:"video"===i?h=>h.type===ye_emsg&&o:h=>"org.id3"===h.type&&l||h.type===ye_emsg&&o,es(r,t,s,c)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:s,id3Track:i}=this,{dateRanges:r}=t,a=Object.keys(r);if(i){const h=Object.keys(s).filter(u=>!a.includes(u));for(let u=h.length;u--;){const d=h[u];Object.keys(s[d].cues).forEach(f=>{i.removeCue(s[d].cues[f])}),delete s[d]}}const o=t.fragments[t.fragments.length-1];if(0===a.length||!F(o?.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,c=ts();for(let h=0;h<a.length;h++){const u=a[h],d=r[u],f=ss(d.startDate,l),m=s[u],g=m?.cues||{};let y=m?.durationKnown||!1,E=gt;const T=d.endDate;if(T)E=ss(T,l),y=!0;else if(d.endOnNext&&!y){const R=a.reduce((S,b)=>{if(b!==d.id){const L=r[b];if(L.class===d.class&&L.startDate>d.startDate&&(!S||d.startDate<S.startDate))return L}return S},null);R&&(E=ss(R.startDate,l),y=!0)}const x=Object.keys(d.attr);for(let R=0;R<x.length;R++){const S=x[R];if(!hn(S))continue;const b=g[S];if(b)y&&!m.durationKnown&&(b.endTime=E);else if(c){let L=d.attr[S];un(S)&&(L=aa(L));const C=Li(c,f,E,{key:S,data:L},"com.apple.quicktime.HLS");C&&(C.id=u,this.id3Track.addCue(C),g[S]=C)}}s[u]={cues:g,dateRange:d,durationKnown:y}}}}class la{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(){const{config:e,levelDetails:t}=this;return void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(null===e)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&s||t;return(l.liveSyncDuration||l.liveSyncDurationCount||0===c)&&(c=void 0!==r?r:a*i),c+Math.min(1*this.stallCount,i)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,s=this.levelDetails;if(null===e||null===t||null===s)return null;const i=s.edge,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(i-s.totalduration,e-t-this.edgeStalled),o)}get drift(){const{levelDetails:e}=this;return null===e?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;return null===e?0:Math.max(e.age-3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration),0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(p.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(p.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var s;t.details===A.BUFFER_STALLED_ERROR&&(this.stallCount++,null!=(s=this.levelDetails)&&s.live&&v.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(null===s)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||1===r||!t.live)return;const a=this.targetLatency;if(null===a)return;const o=s-a;if(o<Math.min(this.maxLatency,a+t.targetduration)&&o>.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,r)),u=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(h,Math.max(1,u))}else 1!==e.playbackRate&&0!==e.playbackRate&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return null===e?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}const is=["NONE","TYPE-0","TYPE-1",null],mt=["SDR","PQ","HLG"];function Ri(n){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=n;return e&&s<e/2?t?"v2":"YES":""}class Ii{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Ge{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[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.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return bi(this._audioGroups,e)}hasSubtitleGroup(e){return bi(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t)if("audio"===e){let s=this._audioGroups;s||(s=this._audioGroups=[]),-1===s.indexOf(t)&&s.push(t)}else if("text"===e){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),-1===s.indexOf(t)&&s.push(t)}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function bi(n,e){return!(!e||!n)&&-1!==n.indexOf(e)}function rs(n,e){const t=e.startPTS;if(F(t)){let i,s=0;e.sn>n.sn?(s=t-n.start,i=n):(s=n.start-t,i=e),i.duration!==s&&(i.duration=s)}else e.start=e.sn>n.sn?n.cc===e.cc&&n.minEndPTS?n.start+(n.minEndPTS-n.start):n.start+n.duration:Math.max(n.start-e.duration,0)}function Di(n,e,t,s,i,r){s-t<=0&&(v.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let o=t,l=s;const c=e.startPTS,h=e.endPTS;if(F(c)){const y=Math.abs(c-t);e.deltaPTS=F(e.deltaPTS)?Math.max(y,e.deltaPTS):y,o=Math.max(t,c),t=Math.min(t,c),i=Math.min(i,e.startDTS),l=Math.min(s,h),s=Math.max(s,h),r=Math.max(r,e.endDTS)}const u=t-e.start;0!==e.start&&(e.start=t),e.duration=s-e.start,e.startPTS=t,e.maxStartPTS=o,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;const d=e.sn;if(!n||d<n.startSN||d>n.endSN)return 0;let f;const m=d-n.startSN,g=n.fragments;for(g[m]=e,f=m;f>0;f--)rs(g[f],g[f-1]);for(f=m;f<g.length-1;f++)rs(g[f],g[f+1]);return n.fragmentHint&&rs(g[g.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,u}function Ci(n,e){const t=e.startSN+e.skippedSegments-n.startSN,s=n.fragments;t<0||t>=s.length||ns(e,s[t].start)}function ns(n,e){if(e){const t=n.fragments;for(let s=n.skippedSegments;s<t.length;s++)t[s].start+=e;n.fragmentHint&&(n.fragmentHint.start+=e)}}function _i(n,e,t){var s;return null!=n&&n.details?wi(null==(s=n.details)?void 0:s.partList,e,t):null}function wi(n,e,t){if(n)for(let s=n.length;s--;){const i=n[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function Pi(n){n.forEach((e,t)=>{const{details:s}=e;null!=s&&s.fragments&&s.fragments.forEach(i=>{i.level=t})})}function yt(n){switch(n.details){case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_TIMEOUT:case A.LEVEL_LOAD_TIMEOUT:case A.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function ki(n,e){const t=yt(e);return n.default[(t?"timeout":"error")+"Retry"]}function as(n,e){const t="linear"===n.backoff?1:Math.pow(2,e);return Math.min(t*n.retryDelayMs,n.maxRetryDelayMs)}function Fi(n){return re(re({},n),{errorRetry:null,timeoutRetry:null})}function Et(n,e,t,s){if(!n)return!1;const i=s?.code,r=e<n.maxNumRetry&&(function ya(n){return 0===n&&!1===navigator.onLine||!!n&&(n<400||n>499)}(i)||!!t);return n.shouldRetry?n.shouldRetry(n,e,t,s,r):r}const Oi_search=function(n,e){let t=0,s=n.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=n[i];const a=e(r);if(a>0)t=i+1;else{if(!(a<0))return r;s=i-1}}return null};function Tt(n,e,t=0,s=0,i=.005){let r=null;if(n){r=e[n.sn-e[0].sn+1]||null;const o=n.endDTS-t;o>0&&o<15e-7&&(t+=15e-7)}else 0===t&&0===e[0].start&&(r=e[0]);if(r&&((!n||n.level===r.level)&&0===os(t,s,r)||function Ta(n,e,t){if(e&&0===e.start&&e.level<n.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>("INF"===r[0]&&(i+=parseFloat(r[1])),i),t);return n.start<=s}return!1}(r,n,Math.min(i,s))))return r;const a=Oi_search(e,os.bind(null,t,s));return!a||a===n&&r?r:a}function os(n=0,e=0,t){if(t.start<=n&&t.start+t.duration>n)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=n?1:t.start-s>n&&t.start?-1:0}function xa(n,e,t){const s=1e3*Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return(t.endProgramDateTime||0)-s>n}class ls{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=v.log.bind(v,`${t}:`),this.warn=v.warn.bind(v,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=t?.renditionReports;if(i){let r=-1;for(let a=0;a<i.length;a++){const o=i[a];let l;try{l=new self.URL(o.URI,t.url).href}catch(c){v.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===e){r=a;break}l===e.substring(0,l.length)&&(r=a)}if(-1!==r){const a=i[r],o=parseInt(a["LAST-MSN"])||t?.lastPartSn;let l=parseInt(a["LAST-PART"])||t?.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&h>t.partTarget&&(l+=1)}const c=s&&Ri(s);return new Ii(o,l>=0?l:void 0,c)}}}loadPlaylist(e){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,s){const{details:i,stats:r}=t,a=self.performance.now(),o=r.loading.first?Math.max(0,a-r.loading.first):0;if(i.advancedDateTime=Date.now()-o,i.live||null!=s&&s.live){if(i.reloaded(s),s&&this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),s&&i.fragments.length>0&&function ua(n,e){let t=null;const s=n.fragments;for(let o=s.length-1;o>=0;o--){const l=s[o].initSegment;if(l){t=l;break}}let i;n.fragmentHint&&delete n.fragmentHint.endPTS,function ga(n,e,t){const s=e.skippedSegments,i=Math.max(n.startSN,e.startSN)-e.startSN,r=(n.fragmentHint?1:0)+(s?e.endSN:Math.min(n.endSN,e.endSN))-e.startSN,a=e.startSN-n.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=n.fragmentHint?n.fragments.concat(n.fragmentHint):n.fragments;for(let c=i;c<=r;c++){const h=l[a+c];let u=o[c];s&&!u&&c<s&&(u=e.fragments[c]=h),h&&u&&t(h,u,c,o)}}(n,e,(o,l,c,h)=>{if(e.skippedSegments&&l.cc!==o.cc){const u=o.cc-l.cc;for(let d=c;d<h.length;d++)h[d].cc+=u}F(o.startPTS)&&F(o.endPTS)&&(l.start=l.startPTS=o.startPTS,l.startDTS=o.startDTS,l.maxStartPTS=o.maxStartPTS,l.endPTS=o.endPTS,l.endDTS=o.endDTS,l.minEndPTS=o.minEndPTS,l.duration=o.endPTS-o.startPTS,l.duration&&(i=l),e.PTSKnown=e.alignedSliding=!0),l.elementaryStreams=o.elementaryStreams,l.loader=o.loader,l.stats=o.stats,o.initSegment&&(l.initSegment=o.initSegment,t=o.initSegment)});const r=e.fragments;if(t&&(e.fragmentHint?r.concat(e.fragmentHint):r).forEach(l=>{var c;l&&(!l.initSegment||l.initSegment.relurl===(null==(c=t)?void 0:c.relurl))&&(l.initSegment=t)}),e.skippedSegments){if(e.deltaUpdateFailed=r.some(o=>!o),e.deltaUpdateFailed){v.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let o=e.skippedSegments;o--;)r.shift();e.startSN=r[0].sn}else e.canSkipDateRanges&&(e.dateRanges=function da(n,e,t){const s=te({},n);return t&&t.forEach(i=>{delete s[i]}),Object.keys(e).forEach(i=>{const r=new Hs(e[i].attr,s[i]);r.isValid?s[i]=r:v.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[i].attr)}"`)}),s}(n.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));e.startCC=e.fragments[0].cc,e.endCC=r[r.length-1].cc}(function fa(n,e,t){if(n&&e){let s=0;for(let i=0,r=n.length;i<=r;i++){const a=n[i],o=e[i+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}})(n.partList,e.partList,(o,l)=>{l.elementaryStreams=o.elementaryStreams,l.stats=o.stats}),i?Di(e,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS):Ci(n,e),r.length&&(e.totalduration=e.edge-r[0].start),e.driftStartTime=n.driftStartTime,e.driftStart=n.driftStart;const a=e.advancedDateTime;if(e.advanced&&a){const o=e.edge;e.driftStart||(e.driftStartTime=a,e.driftStart=o),e.driftEndTime=a,e.driftEnd=o}else e.driftEndTime=n.driftEndTime,e.driftEnd=n.driftEnd,e.advancedDateTime=n.advancedDateTime}(s,i),!this.canLoad||!i.live)return;let l,c,h;if(i.canBlockReload&&i.endSN&&i.advanced){const y=this.hls.config.lowLatencyMode,E=i.lastPartSn,T=i.endSN,x=i.lastPartIndex,S=E===T;-1!==x?(c=S?T+1:E,h=S?y?0:x:x+1):c=T+1;const L=i.age;let w=Math.min(L+i.ageHeader-i.partTarget,1.5*i.targetduration);if(w>0){if(s&&w>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${w} with playlist age: ${i.age}`),w=0;else{const I=Math.floor(w/i.targetduration);c+=I,void 0!==h&&(h+=Math.round(w%i.targetduration/i.partTarget)),this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${L.toFixed(2)}s goal: ${w} skip sn ${I} to part ${h}`)}i.tuneInGoal=w}if(l=this.getDeliveryDirectives(i,t.deliveryDirectives,c,h),y||!S)return void this.loadPlaylist(l)}else(i.canBlockReload||i.canSkipUntil)&&(l=this.getDeliveryDirectives(i,t.deliveryDirectives,c,h));const u=this.hls.mainForwardBufferInfo,m=function ma(n,e=1/0){let t=1e3*n.targetduration;if(n.updated){const s=n.fragments;if(s.length&&4*t>e){const r=1e3*s[s.length-1].duration;r<t&&(t=r)}}else t/=2;return Math.round(t)}(i,1e3*(i.edge-(u?u.end-u.len:0)));i.updated&&a>this.requestScheduled+m&&(this.requestScheduled=r.loading.start),void 0!==c&&i.canBlockReload?this.requestScheduled=r.loading.first+m-(1e3*i.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+m<a?this.requestScheduled=a:this.requestScheduled-a<=0&&(this.requestScheduled+=m);let g=this.requestScheduled-a;g=Math.max(0,g),this.log(`reload live playlist ${e} in ${Math.round(g)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),g)}else this.clearTimer()}getDeliveryDirectives(e,t,s,i){let r=Ri(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=""),new Ii(s,i,r)}checkRetry(e){const t=e.details,s=yt(e),i=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=i||{},l=!!i&&!!o&&(5===r||!i.resolved&&2===r);if(l){var c;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(s&&null!=(c=e.context)&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=as(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,i.resolved=!0}return l}}class Ke{constructor(e,t=0,s=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_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Aa{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ke(e),this.fast_=new Ke(t),this.defaultTTFB_=i,this.ttfb_=new Ke(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new Ke(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new Ke(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Ke(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){const i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,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(){}}const Mi={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Ni={};function La(n,e,t,s,i,r){const a=n.audioCodec?n.audioGroups:null,o=r?.audioCodec,l=r?.channels,c=l?parseInt(l):o?1/0:2;let h=null;if(null!=a&&a.length)try{h=1===a.length&&a[0]?e.groups[a[0]].channels:a.reduce((u,d)=>{if(d){const f=e.groups[d];if(!f)throw new Error(`Audio track group ${d} not found`);Object.keys(f.channels).forEach(m=>{u[m]=(u[m]||0)+f.channels[m]})}return u},{2:0})}catch{return!0}return void 0!==n.videoCodec&&(n.width>1920&&n.height>1088||n.height>1920&&n.width>1088||n.frameRate>Math.max(s,30)||"SDR"!==n.videoRange&&n.videoRange!==t||n.bitrate>Math.max(i,8e6))||!!h&&F(c)&&Object.keys(h).some(u=>parseInt(u)>c)}function Ra(n,e,t){const s=n.videoCodec,i=n.audioCodec;if(!s||!i||!t)return Promise.resolve(Mi);const r={width:n.width,height:n.height,bitrate:Math.ceil(Math.max(.9*n.bitrate,n.averageBitrate)),framerate:n.frameRate||30},a=n.videoRange;"SDR"!==a&&(r.transferFunction=a.toLowerCase());const o=s.split(",").map(l=>({type:"media-source",video:re(re({},r),{},{contentType:Je(l,"video")})}));return i&&n.audioGroups&&n.audioGroups.forEach(l=>{var c;l&&(null==(c=e.groups[l])||c.tracks.forEach(h=>{if(h.groupId===l){const d=parseFloat(h.channels||"");F(d)&&d>2&&o.push.apply(o,i.split(",").map(f=>({type:"media-source",audio:{contentType:Je(f,"audio"),channels:""+d}})))}}))}),Promise.all(o.map(l=>{const c=function Ia(n){const{audio:e,video:t}=n,s=t||e;if(s){const i=s.contentType.split('"')[1];if(t)return`r${t.height}x${t.width}f${Math.ceil(t.framerate)}${t.transferFunction||"sd"}_${i}_${Math.ceil(t.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${i}`}return""}(l);return Ni[c]||(Ni[c]=t.decodingInfo(l))})).then(l=>({supported:!l.some(c=>!c.supported),configurations:o,decodingInfoResults:l})).catch(l=>({supported:!1,configurations:o,decodingInfoResults:[],error:l}))}function be(n,e){v.log(`[abr] start candidates with "${n}" ignored because ${e}`)}function Le(n,e,t){if("attrs"in n){const s=e.indexOf(n);if(-1!==s)return s}for(let s=0;s<e.length;s++)if(Me(n,e[s],t))return s;return-1}function Me(n,e,t){const{groupId:s,name:i,lang:r,assocLang:a,default:o}=n,l=n.forced;return(void 0===s||e.groupId===s)&&(void 0===i||e.name===i)&&(void 0===r||e.lang===r)&&(void 0===r||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in n)||function Pa(n,e=""){const t=n.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>-1===s.indexOf(i))}(n.characteristics||"",e.characteristics))&&(void 0===t||t(n,e))}function Ne(n,e){const{audioCodec:t,channels:s}=n;return!(void 0!==t&&(e.audioCodec||"").substring(0,4)!==t.substring(0,4)||void 0!==s&&s!==(e.channels||"2"))}function Ui(n,e,t){for(let s=e;s>-1;s--)if(t(n[s]))return s;for(let s=e+1;s<n.length;s++)if(t(n[s]))return s;return-1}class Oa{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Ma{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(){const{hls:e}=this;e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;const a=r.end;if(r.start<=e&&null!==a&&e<=a)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:s}=this,i=Object.keys(s);for(let r=i.length;r--;){const a=s[i[r]];if(a?.body.type===t&&a.buffered){const o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,s,i){this.timeRanges&&(this.timeRanges[e]=t);const r=i?.fragment.sn||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||r>=o.body.sn)return;if(!o.buffered&&!o.loaded)return void(o.body.type===s&&this.removeFragment(o.body));const l=o.range[e];l&&l.time.some(c=>{const h=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return h&&this.removeFragment(o.body),h})})}detectPartialFragments(e){const t=this.timeRanges,{frag:s,part:i}=e;if(!t||"initSegment"===s.sn)return;const r=Ve(s),a=this.fragments[r];if(!a||a.buffered&&s.gap)return;const o=!s.relurl;Object.keys(t).forEach(l=>{const c=s.elementaryStreams[l];c&&(a.range[l]=this.getBufferedTimes(s,i,o||!0===c.partial,t[l]))}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=s.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),xt(a)||this.removeParts(s.sn-1,s.type)):this.removeFragment(a.body)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=s.filter(i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Ve(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let h=0;h<i.length;h++){const u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(c>=u&&l<=d){r.time.push({startPTS:Math.max(a,i.start(h)),endPTS:Math.min(o,i.end(h))});break}if(a<d&&o>u){const f=Math.max(a,i.start(h)),m=Math.min(o,i.end(h));m>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:m}))}else if(o<=u)break}return r}getPartialFragment(e){let s,i,r,t=null,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const h=l[c];h&&xt(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),a<=s&&(t=h.body,a=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return void 0!==t&&(t.buffered||xt(t))}getState(e){const t=Ve(e),s=this.fragments[t];return s?s.buffered?xt(s)?"PARTIAL":"OK":"APPENDING":"NOT_LOADED"}isTimeBuffered(e,t,s){let i,r;for(let a=0;a<s.length;a++){if(i=s.start(a)-this.bufferPadding,r=s.end(a)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onFragLoaded(e,t){const{frag:s,part:i}=t;if("initSegment"===s.sn||s.bitrateTest)return;const r=i?null:t,a=Ve(s);this.fragments[a]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r}=t;if("initSegment"===s.sn)return;const a=s.type;if(i){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(i)}this.timeRanges=r,Object.keys(r).forEach(o=>{this.detectEvictedFragments(o,r[o],a,i)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Ve(e);return!!this.fragments[t]}hasParts(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==s||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(e){const t=Ve(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=s.filter(r=>r.fragment.sn!==i)}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 xt(n){var e,t,s;return n.buffered&&(n.body.gap||(null==(e=n.range.video)?void 0:e.partial)||(null==(t=n.range.audio)?void 0:t.partial)||(null==(s=n.range.audiovideo)?void 0:s.partial))}function Ve(n){return`${n.type}_${n.level}_${n.sn}`}const Na={length:0,start:()=>0,end:()=>0};class Z{static isBuffered(e,t){try{if(e){const s=Z.getBuffered(e);for(let i=0;i<s.length;i++)if(t>=s.start(i)&&t<=s.end(i))return!0}}catch{}return!1}static bufferInfo(e,t,s){try{if(e){const i=Z.getBuffered(e),r=[];let a;for(a=0;a<i.length;a++)r.push({start:i.start(a),end:i.end(a)});return this.bufferedInfo(r,t,s)}}catch{}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.sort(function(c,h){return c.start-h.start||h.end-c.end});let i=[];if(s)for(let c=0;c<e.length;c++){const h=i.length;if(h){const u=i[h-1].end;e[c].start-u<s?e[c].end>u&&(i[h-1].end=e[c].end):i.push(e[c])}else i.push(e[c])}else i=e;let a,r=0,o=t,l=t;for(let c=0;c<i.length;c++){const h=i[c].start,u=i[c].end;if(t+s>=h&&t<u)o=h,l=u,r=l-t;else if(t+s<h){a=h;break}}return{len:r,start:o||0,end:l||0,nextStart:a}}static getBuffered(e){try{return e.buffered}catch(t){return v.log("failed to get media.buffered",t),Na}}}class cs{constructor(e,t,s,i=0,r=-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={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=a}}function St(n,e){for(let s=0,i=n.length;s<i;s++){var t;if((null==(t=n[s])?void 0:t.cc)===e)return n[s]}return null}function Bi(n,e){if(n){const t=n.start+e;n.start=n.startPTS=t,n.endPTS=t+n.duration}}function $i(n,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)Bi(t[s],n);e.fragmentHint&&Bi(e.fragmentHint,n),e.alignedSliding=!0}function At(n,e){if(!n.hasProgramDateTime||!e.hasProgramDateTime)return;const t=n.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const a=Math.min(e.endCC,n.endCC);e.startCC<a&&n.startCC<a&&(i=St(s,a),r=St(t,a)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=St(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,l=r.programDateTime;o&&l&&$i((l-o)/1e3-(r.start-i.start),n)}const Gi=Math.pow(2,17);class Ka{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new De({type:B.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(f=>"GAP"===f[0]))return void l(Vi(e));e.gap=!1}const c=this.loader=e.loader=r?new r(i):new a(i),h=Ki(e),u=Fi(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:Gi};e.stats=c.stats,c.load(h,d,{onSuccess:(f,m,g,y)=>{this.resetLoader(e,c);let E=f.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(E.slice(0,16)),E=E.slice(16)),o({frag:e,part:null,payload:E,networkDetails:y})},onError:(f,m,g,y)=>{this.resetLoader(e,c),l(new De({type:B.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:re({url:s,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:y}))},onAbort:(f,m,g)=>{this.resetLoader(e,c),l(new De({type:B.NETWORK_ERROR,details:A.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,c),l(new De({type:B.NETWORK_ERROR,details:A.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:g,stats:f}))},onProgress:(f,m,g,y)=>{t&&t({frag:e,part:null,payload:g,networkDetails:y})}})})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void l(Vi(e,t));const c=this.loader=e.loader=r?new r(i):new a(i),h=Ki(e,t),u=Fi(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Gi};t.stats=c.stats,c.load(h,d,{onSuccess:(f,m,g,y)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:f.data,networkDetails:y};s(E),o(E)},onError:(f,m,g,y)=>{this.resetLoader(e,c),l(new De({type:B.NETWORK_ERROR,details:A.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:re({url:h.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:y}))},onAbort:(f,m,g)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new De({type:B.NETWORK_ERROR,details:A.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,c),l(new De({type:B.NETWORK_ERROR,details:A.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:g,stats:f}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(s.loaded/r),l),u=(l-c)*Math.round(s.loaded/c);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);const a=s.loading,o=i.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 Ki(n,e=null){const t=e||n,s={frag:n,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(F(i)&&F(r)){var a;let o=i,l=r;if("initSegment"===n.sn&&"AES-128"===(null==(a=n.decryptdata)?void 0:a.method)){const c=r-i;c%16&&(l=r+(16-c%16)),0!==i&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=l}return s}function Vi(n,e){const t=new Error(`GAP ${n.gap?"tag":"attribute"} found`),s={type:B.MEDIA_ERROR,details:A.FRAG_GAP,fatal:!1,frag:n,error:t,networkDetails:null};return e&&(s.part=e),(e||n).stats.aborted=!0,new De(s)}class De extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Va{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)}}class Ha{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}class Ya{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(4*i);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],a=s[2],o=s[3],l=this.invSubMix,c=l[0],h=l[1],u=l[2],d=l[3],f=new Uint32Array(256);let m=0,g=0,y=0;for(y=0;y<256;y++)f[y]=y<128?y<<1:y<<1^283;for(y=0;y<256;y++){let E=g^g<<1^g<<2^g<<3^g<<4;E=E>>>8^255&E^99,e[m]=E,t[E]=m;const T=f[m],x=f[T],R=f[x];let S=257*f[E]^16843008*E;i[m]=S<<24|S>>>8,r[m]=S<<16|S>>>16,a[m]=S<<8|S>>>24,o[m]=S,S=16843009*R^65537*x^257*T^16843008*m,c[E]=S<<24|S>>>8,h[E]=S<<16|S>>>16,u[E]=S<<8|S>>>24,d[E]=S,m?(m=T^f[f[f[R^T]]],g^=f[f[g]]):m=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const a=this.ksRows=4*(r+6+1);let o,l;const c=this.keySchedule=new Uint32Array(a),h=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,m=f[0],g=f[1],y=f[2],E=f[3];let T,x;for(o=0;o<a;o++)o<r?T=c[o]=t[o]:(x=T,o%r==0?(x=x<<8|x>>>24,x=u[x>>>24]<<24|u[x>>>16&255]<<16|u[x>>>8&255]<<8|u[255&x],x^=d[o/r|0]<<24):r>6&&o%r==4&&(x=u[x>>>24]<<24|u[x>>>16&255]<<16|u[x>>>8&255]<<8|u[255&x]),c[o]=T=(c[o-r]^x)>>>0);for(l=0;l<a;l++)o=a-l,x=3&l?c[o]:c[o-4],h[l]=l<4||o<=4?x:m[u[x>>>24]]^g[u[x>>>16&255]]^y[u[x>>>8&255]]^E[u[255&x]],h[l]=h[l]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(16711680&e)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(s);let f=d[0],m=d[1],g=d[2],y=d[3];const E=new Int32Array(e),T=new Int32Array(E.length);let x,R,S,b,L,C,w,I,_,V,P,G,$,U;const Y=this.networkToHostOrderSwap;for(;t<E.length;){for(_=Y(E[t]),V=Y(E[t+1]),P=Y(E[t+2]),G=Y(E[t+3]),L=_^r[0],C=G^r[1],w=P^r[2],I=V^r[3],$=4,U=1;U<i;U++)x=l[L>>>24]^c[C>>16&255]^h[w>>8&255]^u[255&I]^r[$],R=l[C>>>24]^c[w>>16&255]^h[I>>8&255]^u[255&L]^r[$+1],S=l[w>>>24]^c[I>>16&255]^h[L>>8&255]^u[255&C]^r[$+2],b=l[I>>>24]^c[L>>16&255]^h[C>>8&255]^u[255&w]^r[$+3],L=x,C=R,w=S,I=b,$+=4;x=a[L>>>24]<<24^a[C>>16&255]<<16^a[w>>8&255]<<8^a[255&I]^r[$],R=a[C>>>24]<<24^a[w>>16&255]<<16^a[I>>8&255]<<8^a[255&L]^r[$+1],S=a[w>>>24]<<24^a[I>>16&255]<<16^a[L>>8&255]<<8^a[255&C]^r[$+2],b=a[I>>>24]<<24^a[L>>16&255]<<16^a[C>>8&255]<<8^a[255&w]^r[$+3],T[t]=Y(x^f),T[t+1]=Y(b^m),T[t+2]=Y(S^g),T[t+3]=Y(R^y),f=_,m=V,g=P,y=G,t+=4}return T.buffer}}class hs{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?function Wa(n){const e=n.byteLength,t=e&&new DataView(n.buffer).getUint8(e-1);return t?Fe(n,0,e-t):n}(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s){return this.useSoftware?new Promise((i,r)=>{this.softwareDecrypt(new Uint8Array(e),t,s);const a=this.flush();a?i(a.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s)}softwareDecrypt(e,t,s){const{currentIV:i,currentResult:r,remainderData:a}=this;this.logOnce("JS AES decrypt"),a&&(e=fe(a,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;i&&(s=i);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ya),l.expandKey(t);const c=r;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=Fe(o,-16).buffer,c||null}webCryptoDecrypt(e,t,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s));this.key=t,this.fastAesKey=new Ha(this.subtle,t)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Va(this.subtle,new Uint8Array(s)).decrypt(e.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(v.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,s)))}onWebCryptoError(e,t,s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s);const i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%16;return s!==e.length&&(t=Fe(e,0,s),this.remainderData=Fe(e,s)),t}logOnce(e){this.logEnabled&&(v.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}class us extends Oa{constructor(e,t,s,i,r){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state="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.buffering=!0,this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=r,this.logPrefix=i,this.log=v.log.bind(v,`${i}:`),this.warn=v.warn.bind(v,`${i}:`),this.hls=e,this.fragmentLoader=new Ka(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new hs(e.config),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state="STOPPED"}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const s=t.partList;if(null!=s&&s.length){const r=s[s.length-1];return Z.isBuffered(this.media,r.start+r.duration/2)}return this.fragmentTracker.isEndListAppended(t.fragments[t.fragments.length-1].type)}getLevelDetails(){var e;if(this.levels&&null!==this.levelLastLoaded)return null==(e=this.levelLastLoaded)?void 0:e.details}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),s.addEventListener("seeking",this.onvseeking),s.addEventListener("ended",this.onvended);const i=this.config;this.levels&&i.autoStartLoad&&"STOPPED"===this.state&&this.startLoad(i.startPosition)}onMediaDetaching(){const e=this.media;null!=e&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:s,mediaBuffer:i,state:r}=this,a=s?s.currentTime:0,o=Z.bufferInfo(i||s,a,e.maxBufferHole);if(this.log(`media seeking to ${F(a)?a.toFixed(3):a}, state: ${r}`),"ENDED"===this.state)this.resetLoadingState();else if(t){const l=e.maxFragLookUpTolerance,c=t.start-l,h=t.start+t.duration+l;if(!o.len||h<o.start||c>o.end){const u=a>h;(a<c||u)&&(u&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}s&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),this.lastCurrentTime=a),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=a),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state="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,s){this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){this._doFragLoad(e,t,s,r=>{if(this.fragContextChanged(e))return this.warn(`Fragment ${e.sn}${r.part?" p: "+r.part.index:""} of level ${e.level} was dropped during download.`),void this.fragmentTracker.removeFragment(e);e.stats.chunkCount++,this._handleFragmentLoadProgress(r)}).then(r=>{if(!r)return;const a=this.state;this.fragContextChanged(e)?("FRAG_LOADING"===a||!this.fragCurrent&&"PARSING"===a)&&(this.fragmentTracker.removeFragment(e),this.state="IDLE"):("payload"in r&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(p.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r))}).catch(r=>{"STOPPED"===this.state||"ERROR"===this.state||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if("APPENDING"===s.getState(e)){const a=this.getFwdBufferInfo(this.mediaBuffer,e.type),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;(1==(l?e.sn-l.sn:0)||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else 0===(null==(t=this.mediaBuffer)?void 0:t.buffered.length)?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),"PARTIAL"===s.getState(e)&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,s=null){e-t&&this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:e,endOffset:t,type:s})}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{if(!s||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{payload:r}=s,a=e.decryptdata;if(r&&r.byteLength>0&&null!=a&&a.key&&a.iv&&"AES-128"===a.method){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer).catch(l=>{throw i.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const c=self.performance.now();return i.trigger(p.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:c}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{"STOPPED"===this.state||"ERROR"===this.state||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state="IDLE",e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var s,i,r,a;const o=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${"main"===this.playlistType?"level":"track"} ${e.level} (frag:[${(null!=(s=e.startPTS)?s:NaN).toFixed(3)}-${(null!=(i=e.endPTS)?i:NaN).toFixed(3)}] > buffer:${o?function(n){let e="";const t=n.length;for(let s=0;s<t;s++)e+=`[${n.start(s).toFixed(3)}-${n.end(s).toFixed(3)}]`;return e}(Z.getBuffered(o)):"(detached)"})`),"initSegment"!==e.sn){var l;if("subtitle"!==e.type){const h=e.elementaryStreams;if(!Object.keys(h).some(u=>!!h[u]))return void(this.state="IDLE")}const c=null==(l=this.levels)?void 0:l[e.level];null!=c&&c.fragmentError&&(this.log(`Resetting level fragment error count of ${c.fragmentError} on frag buffered`),c.fragmentError=0)}this.state="IDLE",o&&(!this.loadedmetadata&&"main"==e.type&&o.buffered.length&&(null==(r=this.fragCurrent)?void 0:r.sn)===(null==(a=this.fragPrevious)?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,a=!r||0===r.length||r.some(l=>!l),o=new cs(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;const a=t?.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(!e.encrypted||null!=(r=e.decryptdata)&&r.key?!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments):(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${"[stream-controller]"===this.logPrefix?"level":"track"} ${e.level}`),this.state="KEY_LOADING",this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(p.KEY_LOADED,h),"KEY_LOADING"===this.state&&(this.state="IDLE"),h}),this.hls.trigger(p.KEY_LOADING,{frag:e}),null===this.fragCurrent&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),s=Math.max(e.start,s||0),this.config.lowLatencyMode&&"initSegment"!==e.sn){const h=a.partList;if(h&&i){s>e.end&&a.fragmentHint&&(e=a.fragmentHint);const u=this.getNextPart(h,e,s);if(u>-1){const d=h[u];let f;return this.log(`Loading part sn: ${e.sn} p: ${d.index} cc: ${e.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${u}-${h.length-1}] ${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state="FRAG_LOADING",f=o?o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.doFragPartsLoad(e,d,t,i)).catch(m=>this.handleFragLoadError(m)):this.doFragPartsLoad(e,d,t,i).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(p.FRAG_LOADING,{frag:e,part:d,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}if(!e.url||this.loadedEndOfParts(h,s))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${a?"of ["+a.startSN+"-"+a.endSN+"] ":""}${"[stream-controller]"===this.logPrefix?"level":"track"}: ${e.level}, target: ${parseFloat(s.toFixed(3))}`),F(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state="FRAG_LOADING";const l=this.config.progressive;let c;return c=l&&o?o.then(h=>!h||this.fragContextChanged(h?.frag)?null:this.fragmentLoader.load(e,i)).catch(h=>this.handleFragLoadError(h)):Promise.all([this.fragmentLoader.load(e,l?i:void 0),o]).then(([h])=>(!l&&h&&i&&i(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,s,i){return new Promise((r,a)=>{var o;const l=[],c=null==(o=s.details)?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{l[u.index]=d;const f=d.part;this.hls.trigger(p.FRAG_LOADED,d);const m=_i(s,e.sn,u.index+1)||wi(c,e.sn,u.index+1);if(!m)return r({frag:e,part:f,partsLoaded:l});h(m)}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===A.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(p.ERROR,t)}else this.hls.trigger(p.ERROR,{type:B.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||"PARSING"!==this.state)return void(!this.fragCurrent&&"STOPPED"!==this.state&&"ERROR"!==this.state&&(this.state="IDLE"));const{frag:s,part:i,level:r}=t,a=self.performance.now();s.stats.parsing.end=a,i&&(i.stats.parsing.end=a),this.updateLevelTiming(s,i,r,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:a}=e;if(null==t||!t[i])return this.warn(`Levels object was unset while buffering fragment ${r} of level ${i}. The current chunk will not be buffered.`),null;const o=t[i],l=a>-1?_i(o,r,a):null,c=l?l.fragment:function pa(n,e,t){if(null==n||!n.details)return null;const s=n.details;let i=s.fragments[e-s.startSN];return i||(i=s.fragmentHint,i&&i.sn===e)?i:e<s.startSN&&t&&t.sn===e?t:null}(o,r,s);return c?(s&&s!==c&&(c.stats=s.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){var a;if(!e||"PARSING"!==this.state)return;const{data1:o,data2:l}=e;let c=o;if(o&&l&&(c=fe(o,l)),null!=(a=c)&&a.length&&(this.hls.trigger(p.BUFFER_APPENDING,{type:e.type,frag:t,part:s,chunkMeta:i,parent:t.type,data:c}),e.dropped&&e.independent&&!s)){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!Z.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);const s=t.currentTime,i=Z.bufferInfo(t,s,0),a=Math.min(2*this.config.maxFragLookUpTolerance,.25*e.duration),o=Math.max(Math.min(e.start-a,i.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const s=this.getLoadPosition();return F(s)?this.getFwdBufferInfoAtPos(e,s,t):null}getFwdBufferInfoAtPos(e,t,s){const{config:{maxBufferHole:i}}=this,r=Z.bufferInfo(e,t,i);if(0===r.len&&void 0!==r.nextStart){const a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&r.nextStart<a.end)return Z.bufferInfo(e,t,Math.max(r.nextStart,i))}return r}getMaxBufferLength(e){const{config:t}=this;let s;return s=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-3*t,s.maxMaxBufferLength/2,i);return r>=i&&(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(e,t="main"){const s=this.fragmentTracker.getAppendedFrag(e,"main");return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,a=s[0].start;let o;if(t.live){const l=r.initialLiveManifestSize;if(i<l)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${l})`),null;(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a)&&(o=this.getInitialLiveFragment(t,s),this.startPosition=this.nextLoadPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=a&&(o=s[0]);return o||(o=this.getFragmentAtPosition(e,r.lowLatencyMode?t.partEnd:t.fragmentEnd,t)),this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return("OK"===s||"PARTIAL"===s&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){const a=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(null===o)return o;if(e=o,a&&e&&!e.gap&&s.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i);if(null!==l&&s.len+l.len>=r)return this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||null!=e&&e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,s){let i=-1,r=!1,a=!0;for(let o=0,l=e.length;o<l;o++){const c=e[o];if(a=a&&!c.independent,i>-1&&s<c.start)break;const h=c.loaded;h?i=-1:(r||c.independent||a)&&c.fragment===t&&(i=o),r=h}return i}loadedEndOfParts(e,t){const s=e[e.length-1];return s&&t>s.start&&s.loaded}getInitialLiveFragment(e,t){const s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=function Ea(n,e,t){if(null===e||!Array.isArray(n)||!n.length||!F(e))return null;if(e<(n[0].programDateTime||0))return null;if(e>=(n[n.length-1].endProgramDateTime||0))return null;t=t||0;for(let r=0;r<n.length;++r){const a=n[r];if(xa(e,t,a))return a}return null}(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];s.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=function va(n,e){return Oi_search(n,t=>t.cc<e?1:t.cc>e?-1:0)}(t,s.cc),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;null!==r&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=s;const{fragmentHint:l}=s,{maxFragLookUpTolerance:c}=i,h=s.partList,u=!!(i.lowLatencyMode&&null!=h&&h.length&&l);let d;if(u&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn),d=e<t?Tt(r,a,e,e>t-c?0:c):a[a.length-1],d){const f=d.sn-s.startSN,m=this.fragmentTracker.getState(d);if(("OK"===m||"PARTIAL"===m&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn)&&r&&d.level===r.level){const y=a[f+1];d=d.sn<o&&"OK"!==this.fragmentTracker.getState(y)?y:null}}return d}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=s.currentTime,o=e.edge,l=r>=e.fragments[0].start-t.maxFragLookUpTolerance&&r<=o;null!==i&&s.duration>i&&(r<i||!l)&&(!l&&s.readyState<4||r<o-(void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration))&&(this.loadedmetadata||(this.nextLoadPosition=i),s.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),s.currentTime=i))}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragments[0].start,a=!t,o=e.alignedSliding&&F(r);if(a||!o&&!r){const{fragPrevious:l}=this;!function $a(n,e,t){e&&(function Ga(n,e,t){if(function Ua(n,e,t){return!(!e||!(t.endCC>t.startCC||n&&n.cc<t.startCC))}(n,t,e)){const s=function Ba(n,e){const t=n.fragments,s=e.fragments;if(!s.length||!t.length)return void v.log("No fragments to align");const i=St(t,s[0].cc);if(i&&(!i||i.startPTS))return i;v.log("No frag in previous level to align on")}(t,e);s&&F(s.start)&&(v.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),$i(s.start,e))}}(n,t,e),!t.alignedSliding&&e&&At(t,e),!t.alignedSliding&&e&&!t.skippedSegments&&Ci(e,t))}(l,s,e);const c=e.fragments[0].start;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${l?l.sn:"na"} fragments: ${i}`),c}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let s=this.startPosition;if(s<t&&(s=-1),-1===s||-1===this.lastCurrentTime){const i=null!==this.startTimeOffset,r=i?this.startTimeOffset:e.startTimeOffset;null!==r&&F(r)?(s=t+r,r<0&&(s+=e.totalduration),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Start time offset ${r} found in ${i?"multivariant":"media"} playlist, adjust startPosition to ${s}`),this.startPosition=s):e.live?s=this.hls.liveSyncPosition||t:this.startPosition=s=0,this.lastCurrentTime=s}this.nextLoadPosition=s}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&"initSegment"!==e.sn&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&"FRAG_LOADING_WAITING_RETRY"!==this.state)&&(this.state="IDLE")}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const h=this.getCurrentContext(t.chunkMeta);h&&(t.frag=h.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;var i;if(this.fragContextChanged(s))return void this.warn(`Frag load error must match current frag to retry ${s.url} > ${null==(i=this.fragCurrent)?void 0:i.url}`);const r=t.details===A.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(s,!0);const a=t.errorAction,{action:o,retryCount:l=0,retryConfig:c}=a||{};if(a&&5===o&&c){this.resetStartWhenNotLoaded(this.levelLastLoaded);const h=as(c,l);this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${h}ms`),a.resolved=!0,this.retryDate=self.performance.now()+h,this.state="FRAG_LOADING_WAITING_RETRY"}else if(c&&a){if(this.resetFragmentErrors(e),!(l<c.maxNumRetry))return void v.warn(`${t.details} reached or exceeded max retry (${l})`);!r&&3!==o&&(a.resolved=!0)}else this.state=2===a?.action?"WAITING_LEVEL":"ERROR";this.tickImmediate()}reduceLengthAndFlushBuffer(e){if("PARSING"===this.state||"PARSED"===this.state){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);const a=!r;return a&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){"audio"===e&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),"STOPPED"!==this.state&&(this.state="IDLE")}afterBufferFlushed(e,t,s){if(!e)return;const i=Z.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),"ENDED"===this.state&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state="IDLE"}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=e?e.details:null;null!=t&&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),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){var r;const a=s.details;if(a){if(!Object.keys(e.elementaryStreams).reduce((l,c)=>{const h=e.elementaryStreams[c];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${u})`),l||!1;const d=i?0:Di(a,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:a,level:s,drift:d,type:c,frag:e,start:h.startPTS,end:h.endPTS}),!0}return l},!1)&&null===(null==(r=this.transmuxer)?void 0:r.error)){const l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(0===s.fragmentError&&(s.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state="PARSED",this.hls.trigger(p.FRAG_PARSED,{frag:e,part:t})}else this.warn("level.details undefined")}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class Hi{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;return e.length?(s=1===e.length?e[0]:function za(n,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<n.length;i++){const r=n[i];t.set(r,s),s+=r.length}return t}(e,t),this.reset(),s):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}function Re(n="",e=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class ds{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,s,i){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,s){}demux(e,t){this.cachedData&&(e=fe(this.cachedData,e),this.cachedData=null);let r,s=Xe(e,0),i=s?s.length:0;const a=this._audioTrack,o=this._id3Track,l=s?Yt(s):void 0,c=e.length;for((null===this.basePTS||0===this.frameIndex&&F(l))&&(this.basePTS=Za(l,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:"org.id3",duration:Number.POSITIVE_INFINITY});i<c;){if(this.canParse(e,i)){const h=this.appendFrame(a,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=c}else xn(e,i)?(s=Xe(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:"org.id3",duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===c&&r!==c){const h=Fe(e,r);this.cachedData=this.cachedData?fe(this.cachedData,h):h}}return{audioTrack:a,videoTrack:Re(),id3Track:o,textTrack:Re()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Re(),id3Track:this._id3Track,textTrack:Re()}}destroy(){}}const Za=(n,e,t)=>F(n)?90*n:9e4*e+(t?9e4*t.baseTime/t.timescale:0);function Wi(n,e){return 255===n[e]&&240==(246&n[e+1])}function Yi(n,e){return 1&n[e+1]?7:9}function fs(n,e){return(3&n[e+3])<<11|n[e+4]<<3|(224&n[e+5])>>>5}function Lt(n,e){return e+1<n.length&&Wi(n,e)}function io(n,e){if(Lt(n,e)){const t=Yi(n,e);if(e+t>=n.length)return!1;const s=fs(n,e);if(s<=t)return!1;const i=e+s;return i===n.length||Lt(n,i)}return!1}function qi(n,e,t,s,i){if(!n.samplerate){const r=function eo(n,e,t,s){let i,r,a,o;const l=navigator.userAgent.toLowerCase(),c=s,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=1+((192&e[t+2])>>>6);const u=(60&e[t+2])>>>2;if(!(u>h.length-1))return a=(1&e[t+2])<<2,a|=(192&e[t+3])>>>6,v.log(`manifest codec:${s}, ADTS type:${i}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(i=5,o=new Array(4),r=u-3):(i=2,o=new Array(2),r=u):-1!==l.indexOf("android")?(i=2,o=new Array(2),r=u):(i=5,o=new Array(4),s&&(-1!==s.indexOf("mp4a.40.29")||-1!==s.indexOf("mp4a.40.5"))||!s&&u>=6?r=u-3:((s&&-1!==s.indexOf("mp4a.40.2")&&(u>=6&&1===a||/vivaldi/i.test(l))||!s&&1===a)&&(i=2,o=new Array(2)),r=u)),o[0]=i<<3,o[0]|=(14&u)>>1,o[1]|=(1&u)<<7,o[1]|=a<<3,5===i&&(o[1]|=(14&r)>>1,o[2]=(1&r)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:h[u],channelCount:a,codec:"mp4a.40."+i,manifestCodec:c};{const d=new Error(`invalid ADTS sampling index:${u}`);n.emit(p.ERROR,p.ERROR,{type:B.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!0,error:d,reason:d.message})}}(e,t,s,i);if(!r)return;n.config=r.config,n.samplerate=r.samplerate,n.channelCount=r.channelCount,n.codec=r.codec,n.manifestCodec=r.manifestCodec,v.log(`parsed codec:${n.codec}, rate:${r.samplerate}, channels:${r.channelCount}`)}}function ji(n){return 9216e4/n}function zi(n,e,t,s,i){const a=s+i*ji(n.samplerate),o=function ro(n,e){const t=Yi(n,e);if(e+t<=n.length){const s=fs(n,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}(e,t);let l;if(o){const{frameLength:u,headerLength:d}=o,f=d+u,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+f);const g={unit:l,pts:a};return m||n.samples.push(g),{sample:g,length:f,missing:m}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}let Rt=null;const no=[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],ao=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],oo=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],lo=[0,1,1,4];function Xi(n,e,t,s,i){if(t+24>e.length)return;const r=Qi(e,t);if(r&&t+r.frameLength<=e.length){const o=s+i*(9e4*r.samplesPerFrame/r.sampleRate),l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function Qi(n,e){const t=n[e+1]>>3&3,s=n[e+1]>>1&3,i=n[e+2]>>4&15,r=n[e+2]>>2&3;if(1!==t&&0!==i&&15!==i&&3!==r){const o=n[e+3]>>6,c=1e3*no[14*(3===t?3-s:3===s?3:4)+i-1],u=ao[3*(3===t?0:2===t?1:2)+r],d=3===o?1:2,f=oo[t][s],m=lo[s],g=8*f*m,y=Math.floor(f*c/u+(n[e+2]>>1&1))*m;if(null===Rt){const x=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Rt=x?parseInt(x[1]):0}return!!Rt&&Rt<=87&&2===s&&c>=224e3&&0===o&&(n[e+3]=128|n[e+3]),{sampleRate:u,channelCount:d,frameLength:y,samplesPerFrame:g}}}function gs(n,e){return 255===n[e]&&224==(224&n[e+1])&&0!=(6&n[e+1])}function Ji(n,e){return e+1<n.length&&gs(n,e)}function Zi(n,e){if(e+1<n.length&&gs(n,e)){const s=Qi(n,e);let i=4;null!=s&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===n.length||Ji(n,r)}return!1}const uo=/\/emsg[-/]ID3/i,er=(n,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=n[e];const o=Math.min(s,8),l=8-o;r[0]=4278190080>>>24+l<<l,i[0]=(a[0]&r[0])>>l,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};function tr(n,e,t,s,i){if(t+8>e.length||11!==e[t]||119!==e[t+1])return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],l=63&e[t+4],h=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*l+r];if(t+h>e.length)return-1;const u=e[t+6]>>5;let d=0;2===u?d+=2:(1&u&&1!==u&&(d+=2),4&u&&(d+=2));const f=(e[t+6]<<8|e[t+7])>>12-d&1,g=[2,1,2,3,3,4,4,5][u]+f,E=7&e[t+5],T=new Uint8Array([r<<6|e[t+5]>>3<<1|E>>2,(3&E)<<6|u<<3|f<<2|l>>4,l<<4&224]),R=s+i*(1536/o*9e4),S=e.subarray(t,t+h);return n.config=T,n.channelCount=g,n.samplerate=o,n.samples.push({unit:S,pts:R}),h}class mo{constructor(){this.VideoSample=null}createVideoSample(e,t,s,i){return{key:e,frame:!1,pts:t,dts:s,units:[],debug:i,length:0}}getLastNalUnit(e){var t;let i,s=this.VideoSample;if((!s||0===s.units.length)&&(s=e[e.length-1]),null!=(t=s)&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){const s=t.samples,i=s.length;if(!i)return void t.dropped++;{const r=s[i-1];e.pts=r.pts,e.dts=r.dts}}t.samples.push(e)}e.debug.length&&v.log(e.pts+"/"+e.dts+":"+e.debug)}}class sr{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(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(0===r)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(t=(e-=this.bitsAvailable)>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&v.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}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(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let i,t=8,s=8;for(let r=0;r<e;r++)0!==s&&(i=this.readEG(),s=(t+i+256)%256),t=0===s?t:s}readSPS(){let r,a,o,e=0,t=0,s=0,i=0;const l=this.readUByte.bind(this),c=this.readBits.bind(this),h=this.readUEG.bind(this),u=this.readBoolean.bind(this),d=this.skipBits.bind(this),f=this.skipEG.bind(this),m=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);l();const y=l();if(c(5),d(3),l(),m(),100===y||110===y||122===y||244===y||44===y||83===y||86===y||118===y||128===y){const b=h();if(3===b&&d(1),m(),m(),d(1),u())for(a=3!==b?8:12,o=0;o<a;o++)u()&&g(o<6?16:64)}m();const E=h();if(0===E)h();else if(1===E)for(d(1),f(),f(),r=h(),o=0;o<r;o++)f();m(),d(1);const T=h(),x=h(),R=c(1);0===R&&d(1),d(1),u()&&(e=h(),t=h(),s=h(),i=h());let S=[1,1];if(u()&&u())switch(l()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[l()<<8|l(),l()<<8|l()]}return{width:Math.ceil(16*(T+1)-2*e-2*t),height:(2-R)*(x+1)*16-(R?2:4)*(s+i),pixelRatio:S}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class po extends mo{parseAVCPES(e,t,s,i,r){const a=this.parseAVCNALu(e,s.data);let l,o=this.VideoSample,c=!1;s.data=null,o&&a.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"")),a.forEach(h=>{var u;switch(h.type){case 1:{let g=!1;l=!0;const y=h.data;if(c&&y.length>4){const E=new sr(y).readSliceType();(2===E||4===E||7===E||9===E)&&(g=!0)}var d;g&&null!=(d=o)&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts,"")),o.frame=!0,o.key=g;break}case 5:l=!0,null!=(u=o)&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts,"")),o.key=!0,o.frame=!0;break;case 6:l=!0,ri(h.data,1,s.pts,t.samples);break;case 7:{var f,m;l=!0,c=!0;const g=h.data,E=new sr(g).readSPS();if(!e.sps||e.width!==E.width||e.height!==E.height||(null==(f=e.pixelRatio)?void 0:f[0])!==E.pixelRatio[0]||(null==(m=e.pixelRatio)?void 0:m[1])!==E.pixelRatio[1]){e.width=E.width,e.height=E.height,e.pixelRatio=E.pixelRatio,e.sps=[g],e.duration=r;const T=g.subarray(1,4);let x="avc1.";for(let R=0;R<3;R++){let S=T[R].toString(16);S.length<2&&(S="0"+S),x+=S}e.codec=x}break}case 8:l=!0,e.pps=[h.data];break;case 9:l=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"");break;case 12:l=!0;break;default:l=!1,o&&(o.debug+="unknown NAL "+h.type+" ")}o&&l&&o.units.push(h)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){const s=t.byteLength;let i=e.naluState||0;const r=i,a=[];let l,c,h,o=0,u=-1,d=0;for(-1===i&&(u=0,d=31&t[0],i=0,o=1);o<s;)if(l=t[o++],i)if(1!==i)if(l)if(1===l){if(c=o-i-1,u>=0){const f={data:t.subarray(u,c),type:d};a.push(f)}else{const f=this.getLastNalUnit(e.samples);f&&(r&&o<=4-r&&f.state&&(f.data=f.data.subarray(0,f.data.byteLength-r)),c>0&&(f.data=fe(f.data,t.subarray(0,c)),f.state=0))}o<s?(h=31&t[o],u=o,d=h,i=0):i=-1}else i=0;else i=3;else i=l?0:2;else i=l?0:1;if(u>=0&&i>=0){const f={data:t.subarray(u,s),type:d,state:i};a.push(f)}if(0===a.length){const f=this.getLastNalUnit(e.samples);f&&(f.data=fe(f.data,t))}return e.naluState=i,a}}class yo{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new hs(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)})}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length)return void s();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,s),this.decrypter.isSync())))return}}getAvcEncryptedData(e){const t=16*Math.floor((e.length-48)/160)+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const a=ni(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)})}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length)return void i();const r=e[t].units;for(;!(s>=r.length);s++){const a=r[s];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,s,i,a),this.decrypter.isSync())))return}}}}const oe=188;class we{constructor(e,t,s){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.videoParser=new po}static probe(e){const t=we.syncOffset(e);return t>0&&v.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),-1!==t}static syncOffset(e){const t=e.length;let s=Math.min(940,t-oe)+1,i=0;for(;i<s;){let r=!1,a=-1,o=0;for(let l=i;l<t;l+=oe){if(71!==e[l]||t-l!==oe&&71!==e[l+oe]){if(o)return-1;break}if(o++,-1===a&&(a=l,0!==a&&(s=Math.min(a+18612,e.length-oe)+1)),r||(r=0===ms(e,l)),r&&o>1&&(0===a&&o>2||l+oe>s))return a}i++}return-1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Qs[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=we.createTrack("video"),this._audioTrack=we.createTrack("audio",i),this._id3Track=we.createTrack("id3"),this._txtTrack=we.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s,this._duration=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){let r;s||(this.sampleAes=null);const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack;let h=a.pid,u=a.pesData,d=o.pid,f=l.pid,m=o.pesData,g=l.pesData,y=null,E=this.pmtParsed,T=this._pmtId,x=e.length;if(this.remainderData&&(x=(e=fe(this.remainderData,e)).length,this.remainderData=null),x<oe&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};const R=Math.max(0,we.syncOffset(e));x-=(x-R)%oe,x<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,x,e.buffer.byteLength-x));let S=0;for(let L=R;L<x;L+=oe)if(71===e[L]){const C=!!(64&e[L+1]),w=ms(e,L);let _;if((48&e[L+3])>>4>1){if(_=L+5+e[L+4],_===L+oe)continue}else _=L+4;switch(w){case h:C&&(u&&(r=He(u))&&this.videoParser.parseAVCPES(a,c,r,!1,this._duration),u={data:[],size:0}),u&&(u.data.push(e.subarray(_,L+oe)),u.size+=L+oe-_);break;case d:if(C){if(m&&(r=He(m)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r)}m={data:[],size:0}}m&&(m.data.push(e.subarray(_,L+oe)),m.size+=L+oe-_);break;case f:C&&(g&&(r=He(g))&&this.parseID3PES(l,r),g={data:[],size:0}),g&&(g.data.push(e.subarray(_,L+oe)),g.size+=L+oe-_);break;case 0:C&&(_+=e[_]+1),T=this._pmtId=Eo(e,_);break;case T:{C&&(_+=e[_]+1);const V=To(e,_,this.typeSupported,s,this.observer);h=V.videoPid,h>0&&(a.pid=h,a.segmentCodec=V.segmentVideoCodec),d=V.audioPid,d>0&&(o.pid=d,o.segmentCodec=V.segmentAudioCodec),f=V.id3Pid,f>0&&(l.pid=f),null!==y&&!E&&(v.warn(`MPEG-TS PMT found at ${L} after unknown PID '${y}'. Backtracking to sync byte @${R} to parse all TS packets.`),y=null,L=R-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=w}}else S++;S>0&&It(this.observer,new Error(`Found ${S} TS packet/s that do not start with 0x47`)),a.pesData=u,o.pesData=m,l.pesData=g;const b={audioTrack:o,videoTrack:a,id3Track:l,textTrack:c};return i&&this.extractRemainingSamples(b),b}flush(){const{remainderData:e}=this;let t;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,a=s.pesData,o=t.pesData,l=i.pesData;let c;if(a&&(c=He(a))?(this.videoParser.parseAVCPES(s,r,c,!0,this._duration),s.pesData=null):s.pesData=a,o&&(c=He(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break;case"ac3":this.parseAC3PES(t,c)}t.pesData=null}else null!=o&&o.size&&v.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(c=He(l))?(this.parseID3PES(i,c),i.pesData=null):i.pesData=l}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new yo(this.observer,this.config,t);return this.decrypt(i,r)}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this._duration=0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let a,o,l,r=t.data;if(i){this.aacOverFlow=null;const u=i.missing,d=i.sample.unit.byteLength;if(-1===u)r=fe(i.sample.unit,r);else{const f=d-u;i.sample.unit.set(r.subarray(0,u),f),e.samples.push(i.sample),s=i.missing}}for(a=s,o=r.length;a<o-1&&!Lt(r,a);a++);if(a!==s){let u;const d=a<o-1;if(u=d?`AAC PES did not start with ADTS header,offset:${a}`:"No ADTS header found in AAC PES",It(this.observer,new Error(u),d),!d)return}if(qi(e,this.observer,r,a,this.audioCodec),void 0!==t.pts)l=t.pts;else{if(!i)return void v.warn("[tsdemuxer]: AAC PES unknown PTS");{const u=ji(e.samplerate);l=i.sample.pts+u}}let h,c=0;for(;a<o;){if(h=zi(e,r,a,l,c),a+=h.length,h.missing){this.aacOverFlow=h;break}for(c++;a<o-1&&!Lt(r,a);a++);}}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,a=0;const o=t.pts;if(void 0!==o)for(;a<i;)if(Ji(s,a)){const l=Xi(e,s,a,o,r);if(!l)break;a+=l.length,r++}else a++;else v.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(void 0===i)return void v.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=s.length;let l,a=0,o=0;for(;o<r&&(l=tr(e,s,o,i,a++))>0;)o+=l}}parseID3PES(e,t){if(void 0===t.pts)return void v.warn("[tsdemuxer]: ID3 PES unknown PTS");const s=te({},t,{type:this._videoTrack?ye_emsg:"org.id3",duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function ms(n,e){return((31&n[e+1])<<8)+n[e+2]}function Eo(n,e){return(31&n[e+10])<<8|n[e+11]}function To(n,e,t,s,i){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=e+3+((15&n[e+1])<<8|n[e+2])-4;for(e+=12+((15&n[e+10])<<8|n[e+11]);e<o;){const c=ms(n,e),h=(15&n[e+3])<<8|n[e+4];switch(n[e]){case 207:if(!s){ps("ADTS AAC");break}case 15:-1===r.audioPid&&(r.audioPid=c);break;case 21:-1===r.id3Pid&&(r.id3Pid=c);break;case 219:if(!s){ps("H.264");break}case 27:-1===r.videoPid&&(r.videoPid=c,r.segmentVideoCodec="avc");break;case 3:case 4:t.mpeg||t.mp3?-1===r.audioPid&&(r.audioPid=c,r.segmentAudioCodec="mp3"):v.log("MPEG audio found, not supported in this browser");break;case 193:if(!s){ps("AC-3");break}case 129:t.ac3?-1===r.audioPid&&(r.audioPid=c,r.segmentAudioCodec="ac3"):v.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===r.audioPid&&h>0){let u=e+5,d=h;for(;d>2;){106===n[u]&&(!0!==t.ac3?v.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=c,r.segmentAudioCodec="ac3"));const m=n[u+1]+2;u+=m,d-=m}}break;case 194:case 135:return It(i,new Error("Unsupported EC-3 in M2TS found")),r;case 36:return It(i,new Error("Unsupported HEVC in M2TS found")),r}e+=h+5}return r}function It(n,e,t){v.warn(`parsing error: ${e.message}`),n.emit(p.ERROR,p.ERROR,{type:B.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function ps(n){v.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function He(n){let t,s,i,r,a,e=0;const o=n.data;if(!n||0===n.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=fe(o[0],o[1]),o.splice(1,1);if(t=o[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(s=(t[4]<<8)+t[5],s&&s>n.size-6)return null;const c=t[7];192&c&&(r=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&c?(a=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2,r-a>54e5&&(v.warn(`${Math.round((r-a)/9e4)}s delta between PTS and DTS, align them`),r=a)):a=r),i=t[8];let h=i+9;if(n.size<=h)return null;n.size-=h;const u=new Uint8Array(n.size);for(let d=0,f=o.length;d<f;d++){t=o[d];let m=t.byteLength;if(h){if(h>m){h-=m;continue}t=t.subarray(h),m-=h,h=0}u.set(t,e),e+=m}return s&&(s-=i+3),{data:u,pts:r,dts:a,len:s}}return null}class ir{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}const Pe=Math.pow(2,32)-1;let We=(()=>{class n{static init(){let t;for(t in n.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]},n.types)n.types.hasOwnProperty(t)&&(n.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const s=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);n.HDLR_TYPES={video:s,audio:i};const r=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]);n.STTS=n.STSC=n.STCO=a,n.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),n.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),n.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),n.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const o=new Uint8Array([105,115,111,109]),l=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);n.FTYP=n.box(n.types.ftyp,o,c,o,l),n.DINF=n.box(n.types.dinf,n.box(n.types.dref,r))}static box(t,...s){let i=8,r=s.length;const a=r;for(;r--;)i+=s[r].byteLength;const o=new Uint8Array(i);for(o[0]=i>>24&255,o[1]=i>>16&255,o[2]=i>>8&255,o[3]=255&i,o.set(t,4),r=0,i=8;r<a;r++)o.set(s[r],i),i+=s[r].byteLength;return o}static hdlr(t){return n.box(n.types.hdlr,n.HDLR_TYPES[t])}static mdat(t){return n.box(n.types.mdat,t)}static mdhd(t,s){s*=t;const i=Math.floor(s/(Pe+1)),r=Math.floor(s%(Pe+1));return n.box(n.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(t){return n.box(n.types.mdia,n.mdhd(t.timescale,t.duration),n.hdlr(t.type),n.minf(t))}static mfhd(t){return n.box(n.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return n.box(n.types.minf,"audio"===t.type?n.box(n.types.smhd,n.SMHD):n.box(n.types.vmhd,n.VMHD),n.DINF,n.stbl(t))}static moof(t,s,i){return n.box(n.types.moof,n.mfhd(t),n.traf(i,s))}static moov(t){let s=t.length;const i=[];for(;s--;)i[s]=n.trak(t[s]);return n.box.apply(null,[n.types.moov,n.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(n.mvex(t)))}static mvex(t){let s=t.length;const i=[];for(;s--;)i[s]=n.trex(t[s]);return n.box.apply(null,[n.types.mvex,...i])}static mvhd(t,s){s*=t;const i=Math.floor(s/(Pe+1)),r=Math.floor(s%(Pe+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,255&t,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return n.box(n.types.mvhd,a)}static sdtp(t){const s=t.samples||[],i=new Uint8Array(4+s.length);let r,a;for(r=0;r<s.length;r++)a=s[r].flags,i[r+4]=a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy;return n.box(n.types.sdtp,i)}static stbl(t){return n.box(n.types.stbl,n.stsd(t),n.box(n.types.stts,n.STTS),n.box(n.types.stsc,n.STSC),n.box(n.types.stsz,n.STSZ),n.box(n.types.stco,n.STCO))}static avc1(t){let r,a,o,s=[],i=[];for(r=0;r<t.sps.length;r++)a=t.sps[r],o=a.byteLength,s.push(o>>>8&255),s.push(255&o),s=s.concat(Array.prototype.slice.call(a));for(r=0;r<t.pps.length;r++)a=t.pps[r],o=a.byteLength,i.push(o>>>8&255),i.push(255&o),i=i.concat(Array.prototype.slice.call(a));const l=n.box(n.types.avcC,new Uint8Array([1,s[3],s[4],s[5],255,224|t.sps.length].concat(s).concat([t.pps.length]).concat(i))),c=t.width,h=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return n.box(n.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,255&c,h>>8&255,255&h,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]),l,n.box(n.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),n.box(n.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(t){const s=t.config.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([s]).concat(t.config).concat([6,1,2]))}static audioStsd(t){const s=t.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,s>>8&255,255&s,0,0])}static mp4a(t){return n.box(n.types.mp4a,n.audioStsd(t),n.box(n.types.esds,n.esds(t)))}static mp3(t){return n.box(n.types[".mp3"],n.audioStsd(t))}static ac3(t){return n.box(n.types["ac-3"],n.audioStsd(t),n.box(n.types.dac3,t.config))}static stsd(t){return n.box(n.types.stsd,n.STSD,"audio"===t.type?"mp3"===t.segmentCodec&&"mp3"===t.codec?n.mp3(t):"ac3"===t.segmentCodec?n.ac3(t):n.mp4a(t):n.avc1(t))}static tkhd(t){const s=t.id,i=t.duration*t.timescale,r=t.width,a=t.height,o=Math.floor(i/(Pe+1)),l=Math.floor(i%(Pe+1));return n.box(n.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,s>>24&255,s>>16&255,s>>8&255,255&s,0,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,l>>24,l>>16&255,l>>8&255,255&l,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,a>>8&255,255&a,0,0]))}static traf(t,s){const i=n.sdtp(t),r=t.id,a=Math.floor(s/(Pe+1)),o=Math.floor(s%(Pe+1));return n.box(n.types.traf,n.box(n.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),n.box(n.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,o>>24,o>>16&255,o>>8&255,255&o])),n.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,n.box(n.types.trak,n.tkhd(t),n.mdia(t))}static trex(t){const s=t.id;return n.box(n.types.trex,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,s){const i=t.samples||[],r=i.length,a=12+16*r,o=new Uint8Array(a);let l,c,h,u,d,f;for(o.set(["video"===t.type?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,255&r,(s+=8+a)>>>24&255,s>>>16&255,s>>>8&255,255&s],0),l=0;l<r;l++)c=i[l],h=c.duration,u=c.size,d=c.flags,f=c.cts,o.set([h>>>24&255,h>>>16&255,h>>>8&255,255&h,u>>>24&255,u>>>16&255,u>>>8&255,255&u,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,f>>>24&255,f>>>16&255,f>>>8&255,255&f],12+16*l);return n.box(n.types.trun,o)}static initSegment(t){n.types||n.init();const s=n.moov(t);return fe(n.FTYP,s)}}return n.types=void 0,n.HDLR_TYPES=void 0,n.STTS=void 0,n.STSC=void 0,n.STCO=void 0,n.STSZ=void 0,n.VMHD=void 0,n.SMHD=void 0,n.STSD=void 0,n.FTYP=void 0,n.DINF=void 0,n})();function ys(n,e,t=1,s=!1){const i=n*e*t;return s?Math.round(i):i}function Ze(n,e=!1){return ys(n,1e3,1/9e4,e)}let Ce,Ye=null,Es=null;class bt{constructor(e,t,s,i=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,null===Ye){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ye=a?parseInt(a[1]):0}if(null===Es){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Es=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){v.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){v.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){v.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((r,a)=>{let o=a.pts,l=o-r;return l<-4294967296&&(t=!0,o=ge(o,s),l=o-r),l>0?r:o},s);return t&&v.debug("PTS rollover detected"),i}remux(e,t,s,i,r,a,o,l){let c,h,u,d,f,m,g=r,y=r;const T=t.pid>-1,x=t.samples.length,R=e.samples.length>0,S=o&&x>0||x>1;if((!(e.pid>-1)||R)&&(!T||S)||this.ISGenerated||o){if(this.ISGenerated){var L,C,w,I;const G=this.videoTrackConfig;G&&(t.width!==G.width||t.height!==G.height||(null==(L=t.pixelRatio)?void 0:L[0])!==(null==(C=G.pixelRatio)?void 0:C[0])||(null==(w=t.pixelRatio)?void 0:w[1])!==(null==(I=G.pixelRatio)?void 0:I[1]))&&this.resetInitSegment()}else u=this.generateIS(e,t,r,a);const _=this.isVideoContiguous;let P,V=-1;if(S&&(V=function Io(n){for(let e=0;e<n.length;e++)if(n[e].key)return e;return-1}(t.samples),!_&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,V>0){v.warn(`[mp4-remuxer]: Dropped ${V} out of ${x} video samples due to a missing keyframe`);const G=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(V),t.dropped+=V,y+=(t.samples[0].pts-G)/t.inputTimeScale,P=y}else-1===V&&(v.warn(`[mp4-remuxer]: No keyframe found out of ${x} video samples`),m=!1);if(this.ISGenerated){if(R&&S){const G=this.getVideoStartPts(t.samples),U=(ge(e.samples[0].pts,G)-G)/t.inputTimeScale;g+=Math.max(0,U),y+=Math.max(0,-U)}if(R){if(e.samplerate||(v.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,a)),h=this.remuxAudio(e,g,this.isAudioContiguous,a,T||S||"audio"===l?y:void 0),S){const G=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(v.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,a)),c=this.remuxVideo(t,y,_,G)}}else S&&(c=this.remuxVideo(t,y,_,0));c&&(c.firstKeyFrame=V,c.independent=-1!==V,c.firstKeyFramePTS=P)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=ar(s,r,this._initPTS,this._initDTS)),i.samples.length&&(d=or(i,r,this._initPTS))),{audio:h,video:c,initSegment:u,independent:m,text:d,id3:f}}generateIS(e,t,s,i){const r=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS;let d,f,m,h=!c||i,u="audio/mp4";if(h&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}l.audio={id:"audio",container:u,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&o.mpeg?new Uint8Array(0):We.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(m=e.inputTimeScale,c&&m===c.timescale?h=!1:d=f=r[0].pts-Math.round(m*s))}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:We.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(m=t.inputTimeScale,c&&m===c.timescale)h=!1;else{const g=this.getVideoStartPts(a),y=Math.round(m*s);f=Math.min(f,ge(a[0].dts,g)-y),d=Math.min(d,g-y)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:d,timescale:m},this._initDTS={baseTime:f,timescale:m}):d=m=void 0,{tracks:l,initPTS:d,timescale:m}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,a=e.samples,o=[],l=a.length,c=this._initPTS;let f,m,h=this.nextAvcDts,u=8,d=this.videoSampleDuration,g=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,E=!1;if(!s||null===h){const O=t*r,k=a[0].pts-ge(a[0].dts,a[0].pts);Ye&&null!==h&&Math.abs(O-k-h)<15e3?s=!0:h=O-k}const T=c.baseTime*r/c.timescale;for(let O=0;O<l;O++){const k=a[O];k.pts=ge(k.pts-T,h),k.dts=ge(k.dts-T,h),k.dts<a[O>0?O-1:O].dts&&(E=!0)}E&&a.sort(function(O,k){return O.dts-k.dts||O.pts-k.pts}),f=a[0].dts,m=a[a.length-1].dts;const x=m-f,R=x?Math.round(x/(l-1)):d||e.inputTimeScale/30;if(s){const O=f-h,k=O>R,q=O<-1;if((k||q)&&(v.warn(k?`AVC: ${Ze(O,!0)} ms (${O}dts) hole between fragments detected at ${t.toFixed(3)}`:`AVC: ${Ze(-O,!0)} ms (${O}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!q||h>=a[0].pts||Ye)){f=h;const H=a[0].pts-O;if(k)a[0].dts=f,a[0].pts=H;else for(let Q=0;Q<a.length&&!(a[Q].dts>H);Q++)a[Q].dts-=O,a[Q].pts-=O;v.log(`Video: Initial PTS/DTS adjusted: ${Ze(H,!0)}/${Ze(f,!0)}, delta: ${Ze(O,!0)} ms`)}}f=Math.max(0,f);let S=0,b=0,L=f;for(let O=0;O<l;O++){const k=a[O],q=k.units,H=q.length;let Q=0;for(let se=0;se<H;se++)Q+=q[se].data.length;b+=Q,S+=H,k.length=Q,k.dts<L?(k.dts=L,L+=R/4|0||1):L=k.dts,g=Math.min(k.pts,g),y=Math.max(k.pts,y)}m=a[l-1].dts;const C=b+4*S+8;let w;try{w=new Uint8Array(C)}catch(O){return void this.observer.emit(p.ERROR,p.ERROR,{type:B.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:C,reason:`fail allocating video mdat ${C}`})}const I=new DataView(w.buffer);I.setUint32(0,C),w.set(We.types.mdat,4);let _=!1,V=Number.POSITIVE_INFINITY,P=Number.POSITIVE_INFINITY,G=Number.NEGATIVE_INFINITY,$=Number.NEGATIVE_INFINITY;for(let O=0;O<l;O++){const k=a[O],q=k.units;let Q,H=0;for(let le=0,ce=q.length;le<ce;le++){const pe=q[le],tt=pe.data,Bs=pe.data.byteLength;I.setUint32(u,Bs),u+=4,w.set(tt,u),u+=Bs,H+=4+Bs}if(O<l-1)d=a[O+1].dts-k.dts,Q=a[O+1].pts-k.pts;else{const le=this.config,ce=O>0?k.dts-a[O-1].dts:R;if(Q=O>0?k.pts-a[O-1].pts:R,le.stretchShortVideoTrack&&null!==this.nextAudioPts){const pe=Math.floor(le.maxBufferHole*r),tt=(i?g+i*r:this.nextAudioPts)-k.pts;tt>pe?(d=tt-ce,d<0?d=ce:_=!0,v.log(`[mp4-remuxer]: It is approximately ${tt/90} ms to the next segment; using duration ${d/90} ms for the last video frame.`)):d=ce}else d=ce}const se=Math.round(k.pts-k.dts);V=Math.min(V,d),G=Math.max(G,d),P=Math.min(P,Q),$=Math.max($,Q),o.push(new lr(k.key,d,H,se))}if(o.length)if(Ye){if(Ye<70){const O=o[0].flags;O.dependsOn=2,O.isNonSync=0}}else if(Es&&$-P<G-V&&R/G<.025&&0===o[0].cts){v.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let O=f;for(let k=0,q=o.length;k<q;k++){const H=O+o[k].duration;o[k].duration=k<q-1?H+o[k+1].cts-(O+o[k].cts):k?o[k-1].duration:R,o[k].cts=0,O=H}}d=_||!d?R:d,this.nextAvcDts=h=m+d,this.videoSampleDuration=d,this.isVideoContiguous=!0;const J={data1:We.moof(e.sequenceNumber++,f,te({},e,{samples:o})),data2:w,startPTS:g/r,endPTS:(y+d)/r,startDTS:f/r,endDTS:h/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,J}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,s,i,r){const a=e.inputTimeScale,l=a/(e.samplerate?e.samplerate:a),c=this.getSamplesPerFrame(e),h=c*l,u=this._initPTS,d="mp3"===e.segmentCodec&&this.typeSupported.mpeg,f=[],m=void 0!==r;let g=e.samples,y=d?0:8,E=this.nextAudioPts||-1;const T=t*a,x=u.baseTime*a/u.timescale;if(this.isAudioContiguous=s=s||g.length&&E>0&&(i&&Math.abs(T-E)<9e3||Math.abs(ge(g[0].pts-x,T)-E)<20*h),g.forEach(function(U){U.pts=ge(U.pts-x,T)}),!s||E<0){if(g=g.filter(U=>U.pts>=0),!g.length)return;E=0===r?0:i&&!m?Math.max(0,T):g[0].pts}if("aac"===e.segmentCodec){const U=this.config.maxAudioFramesDrift;for(let Y=0,J=E;Y<g.length;Y++){const O=g[Y],k=O.pts,q=k-J,H=Math.abs(1e3*q/a);if(q<=-U*h&&m)0===Y&&(v.warn(`Audio frame @ ${(k/a).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*q/a)} ms.`),this.nextAudioPts=E=J=k);else if(q>=U*h&&H<1e4&&m){let Q=Math.round(q/h);J=k-Q*h,J<0&&(Q--,J+=h),0===Y&&(this.nextAudioPts=E=J),v.warn(`[mp4-remuxer]: Injecting ${Q} audio frame @ ${(J/a).toFixed(3)}s due to ${Math.round(1e3*q/a)} ms gap.`);for(let se=0;se<Q;se++){const le=Math.max(J,0);let ce=ir.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);ce||(v.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),ce=O.unit.subarray()),g.splice(Y,0,{unit:ce,pts:le}),J+=h,Y++}}O.pts=J,J+=h}}let b,R=null,S=null,L=0,C=g.length;for(;C--;)L+=g[C].unit.byteLength;for(let U=0,Y=g.length;U<Y;U++){const J=g[U],O=J.unit;let k=J.pts;if(null!==S)f[U-1].duration=Math.round((k-S)/l);else{if(s&&"aac"===e.segmentCodec&&(k=E),R=k,!(L>0))return;L+=y;try{b=new Uint8Array(L)}catch(H){return void this.observer.emit(p.ERROR,p.ERROR,{type:B.MUX_ERROR,details:A.REMUX_ALLOC_ERROR,fatal:!1,error:H,bytes:L,reason:`fail allocating audio mdat ${L}`})}d||(new DataView(b.buffer).setUint32(0,L),b.set(We.types.mdat,4))}b.set(O,y);const q=O.byteLength;y+=q,f.push(new lr(!0,c,q,0)),S=k}const w=f.length;if(!w)return;this.nextAudioPts=E=S+l*f[f.length-1].duration;const _=d?new Uint8Array(0):We.moof(e.sequenceNumber++,R/l,te({},e,{samples:f}));e.samples=[];const V=R/a,P=E/a,$={data1:_,data2:b,startPTS:V,endPTS:P,startDTS:V,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:w};return this.isAudioContiguous=!0,$}remuxEmptyAudio(e,t,s,i){const r=e.inputTimeScale,l=this.nextAudioPts,c=this._initDTS,h=9e4*c.baseTime/c.timescale,u=(null!==l?l:i.startDTS*r)+h,f=r/(e.samplerate?e.samplerate:r)*1024,m=Math.ceil((i.endDTS*r+h-u)/f),g=ir.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(v.warn("[mp4-remuxer]: remux empty Audio"),!g)return void v.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");const y=[];for(let E=0;E<m;E++){const T=u+E*f;y.push({unit:g,pts:T,dts:T})}return e.samples=y,this.remuxAudio(e,t,s,!1)}}function ge(n,e){let t;if(null===e)return n;for(t=e<n?-8589934592:8589934592;Math.abs(n-e)>4294967296;)n+=t;return n}function ar(n,e,t,s){const i=n.samples.length;if(!i)return;const r=n.inputTimeScale;for(let o=0;o<i;o++){const l=n.samples[o];l.pts=ge(l.pts-t.baseTime*r/t.timescale,e*r)/r,l.dts=ge(l.dts-s.baseTime*r/s.timescale,e*r)/r}const a=n.samples;return n.samples=[],{samples:a}}function or(n,e,t){const s=n.samples.length;if(!s)return;const i=n.inputTimeScale;for(let a=0;a<s;a++){const o=n.samples[a];o.pts=ge(o.pts-t.baseTime*i/t.timescale,e*i)/i}n.samples.sort((a,o)=>a.pts-o.pts);const r=n.samples;return n.samples=[],{samples:r}}class lr{constructor(e,t,s,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=s,this.cts=i,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}function cr(n,e){const t=n?.codec;if(t&&t.length>4)return t;if("audio"===e){if("ec-3"===t||"ac-3"===t||"alac"===t)return t;if("fLaC"===t||"Opus"===t)return dt(t,!1);const s="mp4a.40.5";return v.info(`Parsed audio codec "${t}" or audio object type not handled. Using "${s}"`),s}return v.warn(`Unhandled video codec "${t}"`),"hvc1"===t||"hev1"===t?"hvc1.1.6.L120.90":"av01"===t?"av01.0.04M.08":"avc1.42e01e"}try{Ce=self.performance.now.bind(self.performance)}catch{v.debug("Unable to use Performance API on this environment"),Ce=Be?.Date.now}const Dt=[{demux:class fo{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,s,i){const r=this.videoTrack=Re("video",1),a=this.audioTrack=Re("audio",1),o=this.txtTrack=Re("text",1);if(this.id3Track=Re("id3",1),this.timeOffset=0,null==e||!e.byteLength)return;const l=ti(e);if(l.video){const{id:c,timescale:h,codec:u}=l.video;r.id=c,r.timescale=o.timescale=h,r.codec=u}if(l.audio){const{id:c,timescale:h,codec:u}=l.audio;a.id=c,a.timescale=h,a.codec=u}o.id=Qs.text,r.sampleDuration=0,r.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return function Cn(n){const e=n.byteLength;for(let t=0;t<e;){const s=M(n,t);if(s>8&&109===n[t+4]&&111===n[t+5]&&111===n[t+6]&&102===n[t+7])return!0;t=s>1?t+s:e}return!1}(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=fe(this.remainderData,e));const o=function Nn(n){const e={valid:null,remainder:null},t=K(n,["moof"]);if(t.length<2)return e.remainder=n,e;const s=t[t.length-1];return e.valid=Fe(n,0,s.byteOffset-8),e.remainder=Fe(n,s.byteOffset-8),e}(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const a=this.extractID3Track(i,t);return r.samples=ii(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=ii(e,t),{videoTrack:t,audioTrack:Re(),id3Track:i,textTrack:Re()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=K(e.samples,["emsg"]);i&&i.forEach(r=>{const a=function $n(n){const e=n[0];let t="",s="",i=0,r=0,a=0,o=0,l=0,c=0;if(0===e){for(;"\0"!==ie(n.subarray(c,c+1));)t+=ie(n.subarray(c,c+1)),c+=1;for(t+=ie(n.subarray(c,c+1)),c+=1;"\0"!==ie(n.subarray(c,c+1));)s+=ie(n.subarray(c,c+1)),c+=1;s+=ie(n.subarray(c,c+1)),c+=1,i=M(n,12),r=M(n,16),o=M(n,20),l=M(n,24),c=28}else if(1===e){c+=4,i=M(n,c),c+=4;const u=M(n,c);c+=4;const d=M(n,c);for(c+=4,a=2**32*u+d,rn(a)||(a=Number.MAX_SAFE_INTEGER,v.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=M(n,c),c+=4,l=M(n,c),c+=4;"\0"!==ie(n.subarray(c,c+1));)t+=ie(n.subarray(c,c+1)),c+=1;for(t+=ie(n.subarray(c,c+1)),c+=1;"\0"!==ie(n.subarray(c,c+1));)s+=ie(n.subarray(c,c+1)),c+=1;s+=ie(n.subarray(c,c+1)),c+=1}return{schemeIdUri:t,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:l,payload:n.subarray(c,n.byteLength)}}(r);if(uo.test(a.schemeIdUri)){const o=F(a.presentationTime)?a.presentationTime/a.timeScale:t+a.presentationTimeDelta/a.timeScale;let l=4294967295===a.eventDuration?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=a.payload;s.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:ye_emsg,duration:l})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}},remux:class bo{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,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(function Pn(n,e){if(!n||!e)return n;const t=e.keyId;return t&&e.isCommonEncryption&&K(n,["moov","trak"]).forEach(i=>{const a=K(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=K(a,["enca"]);const l=o.length>0;l||(o=K(a,["encv"])),o.forEach(c=>{K(c.subarray(l?28:78),["sinf"]).forEach(d=>{const f=si(d);if(f){const m=f.subarray(8,24);m.some(g=>0!==g)||(v.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${ve_hexDump(m)} -> ${ve_hexDump(t)}`),f.set(t,8))}})})}),n}(e,i)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:s}=this;if(null==e||!e.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const i=this.initData=ti(e);i.audio&&(t=cr(i.audio,"audio")),i.video&&(s=cr(i.video,"video"));const r={};i.audio&&i.video?r.audiovideo={container:"video/mp4",codec:t+","+s,initSegment:e,id:"main"}:i.audio?r.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:i.video?r.video={container:"video/mp4",codec:s,initSegment:e,id:"main"}:v.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(e,t,s,i,r,a){var o,l;let{initPTS:c,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};F(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(null==d||!d.length)return u;const f={initPTS:void 0,timescale:1};let m=this.initData;if(null!=(o=m)&&o.length||(this.generateInitSegment(d),m=this.initData),null==(l=m)||!l.length)return v.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const g=function Fn(n,e){let t=0,s=0,i=0;const r=K(n,["moof","traf"]);for(let a=0;a<r.length;a++){const o=r[a],l=K(o,["tfhd"])[0],h=e[M(l,4)];if(!h)continue;const u=h.default,d=M(l,0)|u?.flags;let f=u?.duration;8&d&&(f=M(l,2&d?12:8));const m=h.timescale||9e4,g=K(o,["trun"]);for(let y=0;y<g.length;y++)t=On(g[y]),!t&&f&&(t=f*M(g[y],4)),"video"===h.type?s+=t/m:"audio"===h.type&&(i+=t/m)}if(0===s&&0===i){let a=1/0,o=0,l=0;const c=K(n,["sidx"]);for(let h=0;h<c.length;h++){const u=_n(c[h]);if(null!=u&&u.references){a=Math.min(a,u.earliestPresentationTime/u.timescale);const d=u.references.reduce((f,m)=>f+m.info.duration||0,0);o=Math.max(o,d+u.earliestPresentationTime/u.timescale),l=o-a}}if(l&&F(l))return l}return s||i}(d,m),y=function kn(n,e){return K(e,["moof","traf"]).reduce((t,s)=>{const i=K(s,["tfdt"])[0],r=i[0],a=K(s,["tfhd"]).reduce((o,l)=>{const c=M(l,4),h=n[c];if(h){let u=M(i,4);if(1===r){if(u===ot)return v.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;u*=ot+1,u+=M(i,8)}const f=u/(h.timescale||9e4);if(F(f)&&(null===o||f<o))return f}return o},null);return null!==a&&F(a)&&(null===t||a<t)?a:t},null)}(m,d),E=null===y?r:y;(function Do(n,e,t,s){if(null===n)return!0;const i=Math.max(s,1);return Math.abs(e-n.baseTime/n.timescale-t)>i}(c,E,r,g)||f.timescale!==c.timescale&&a)&&(f.initPTS=E-r,c&&1===c.timescale&&v.warn("Adjusting initPTS by "+(f.initPTS-c.baseTime)),this.initPTS=c={baseTime:f.initPTS,timescale:1});const T=e?E-c.baseTime/c.timescale:h,x=T+g;(function Mn(n,e,t){K(e,["moof","traf"]).forEach(s=>{K(s,["tfhd"]).forEach(i=>{const r=M(i,4),a=n[r];if(!a)return;const o=a.timescale||9e4;K(s,["tfdt"]).forEach(l=>{const c=l[0],h=t*o;if(h){let u=M(l,4);if(0===c)u-=h,u=Math.max(u,0),jt(l,4,u);else{u*=Math.pow(2,32),u+=M(l,8),u-=h,u=Math.max(u,0);const d=Math.floor(u/(ot+1)),f=Math.floor(u%(ot+1));jt(l,4,d),jt(l,8,f)}}})})})})(m,d,c.baseTime/c.timescale),g>0?this.lastEndTime=x:(v.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const R=!!m.audio,S=!!m.video;let b="";R&&(b+="audio"),S&&(b+="video");const L={data1:d,startPTS:T,startDTS:T,endPTS:x,endDTS:x,type:b,hasAudio:R,hasVideo:S,nb:1,dropped:0};return u.audio="audio"===L.type?L:void 0,u.video="audio"!==L.type?L:void 0,u.initSegment=f,u.id3=ar(s,r,c,c),i.samples.length&&(u.text=or(i,r,c)),u}}},{demux:we,remux:bt},{demux:class ho extends ds{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Xe(e,0);let s=t?.length||0;if(Zi(e,s))return!1;for(let i=e.length;s<i;s++)if(io(e,s))return v.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return function so(n,e){return function to(n,e){return e+5<n.length}(n,e)&&Wi(n,e)&&fs(n,e)<=n.length-e}(e,t)}appendFrame(e,t,s){qi(e,this.observer,t,s,e.manifestCodec);const i=zi(e,t,s,this.basePTS,this.frameIndex);if(i&&0===i.missing)return i}},remux:bt},{demux:class xo extends ds{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Xe(e,0);let s=t?.length||0;if(t&&11===e[s]&&119===e[s+1]&&void 0!==Yt(t)&&er(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(Zi(e,s))return v.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return function co(n,e){return gs(n,e)&&4<=n.length-e}(e,t)}appendFrame(e,t,s){if(null!==this.basePTS)return Xi(e,t,s,this.basePTS,this.frameIndex)}},remux:bt}];Dt.splice(2,0,{demux:class go extends ds{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=tr(e,t,s,this.basePTS,this.frameIndex);if(-1!==i)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=Xe(e,0);if(!t)return!1;const s=t.length;return 11===e[s]&&119===e[s+1]&&void 0!==Yt(t)&&er(e,s)<16}},remux:bt});class hr{constructor(e,t,s,i,r){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=s,this.vendor=i,this.id=r}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=Ce();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);const{contiguous:c,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:m}=i||o,{audioCodec:g,videoCodec:y,defaultInitPts:E,duration:T,initSegmentData:x}=l,R=function Co(n,e){let t=null;return n.byteLength>0&&null!=e?.key&&null!==e.iv&&null!=e.method&&(t=e),t}(a,t);if(R&&"AES-128"===R.method){const C=this.getDecrypter();if(!C.isSync())return this.decryptionPromise=C.webCryptoDecrypt(a,R.key.buffer,R.iv.buffer).then(w=>{const I=this.push(w,null,s);return this.decryptionPromise=null,I}),this.decryptionPromise;{let w=C.softwareDecrypt(a,R.key.buffer,R.iv.buffer);if(s.part>-1&&(w=C.flush()),!w)return r.executeEnd=Ce(),Ts(s);a=new Uint8Array(w)}}const S=this.needsProbing(h,u);if(S){const C=this.configureTransmuxer(a);if(C)return v.warn(`[transmuxer] ${C.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:B.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,fatal:!1,error:C,reason:C.message}),r.executeEnd=Ce(),Ts(s)}(h||u||m||S)&&this.resetInitSegment(x,g,y,T,t),(h||m||S)&&this.resetInitialTimestamp(E),c||this.resetContiguity();const b=this.transmux(a,R,f,d,s),L=this.currentTransmuxState;return L.contiguous=!0,L.discontinuity=!1,L.trackSwitch=!1,r.executeEnd=Ce(),b}flush(e){const t=e.transmuxing;t.executeStart=Ce();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return r.then(()=>this.flush(e));const a=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&a.push(this.push(u,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return t.executeEnd=Ce(),[Ts(e)];const h=l.flush(o);return Ct(h)?h.then(u=>(this.flushRemux(a,u,e),a)):(this.flushRemux(a,h,e),a)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;v.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const h=this.remuxer.remux(i,r,a,o,c,l,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=Ce()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let a;return a=t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,s,i,r):this.transmuxUnencrypted(e,s,i,r),a}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,o,l,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i,vendor:r}=this;let a;for(let d=0,f=Dt.length;d<f;d++){var o;if(null!=(o=Dt[d].demux)&&o.probe(e)){a=Dt[d];break}}if(!a)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,c=this.remuxer,h=a.remux,u=a.demux;(!c||!(c instanceof h))&&(this.remuxer=new h(s,t,i,r)),(!l||!(l instanceof u))&&(this.demuxer=new u(s,t,i),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new hs(this.config)),e}}const Ts=n=>({remuxResult:{},chunkMeta:n});function Ct(n){return"then"in n&&n.then instanceof Function}class _o{constructor(e,t,s,i,r){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=s,this.duration=i,this.defaultInitPts=r||null}}class wo{constructor(e,t,s,i,r,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=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=a}}var ur={exports:{}};!function(n){var e=Object.prototype.hasOwnProperty,t="~";function s(){}function i(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function r(l,c,h,u,d){if("function"!=typeof h)throw new TypeError("The listener must be a function");var f=new i(h,u||l,d),m=t?t+c:c;return l._events[m]?l._events[m].fn?l._events[m]=[l._events[m],f]:l._events[m].push(f):(l._events[m]=f,l._eventsCount++),l}function a(l,c){0==--l._eventsCount?l._events=new s:delete l._events[c]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(t=!1)),o.prototype.eventNames=function(){var h,u,c=[];if(0===this._eventsCount)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},o.prototype.listeners=function(c){var u=this._events[t?t+c:c];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,m=new Array(f);d<f;d++)m[d]=u[d].fn;return m},o.prototype.listenerCount=function(c){var u=this._events[t?t+c:c];return u?u.fn?1:u.length:0},o.prototype.emit=function(c,h,u,d,f,m){var g=t?t+c:c;if(!this._events[g])return!1;var T,x,y=this._events[g],E=arguments.length;if(y.fn){switch(y.once&&this.removeListener(c,y.fn,void 0,!0),E){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,u),!0;case 4:return y.fn.call(y.context,h,u,d),!0;case 5:return y.fn.call(y.context,h,u,d,f),!0;case 6:return y.fn.call(y.context,h,u,d,f,m),!0}for(x=1,T=new Array(E-1);x<E;x++)T[x-1]=arguments[x];y.fn.apply(y.context,T)}else{var S,R=y.length;for(x=0;x<R;x++)switch(y[x].once&&this.removeListener(c,y[x].fn,void 0,!0),E){case 1:y[x].fn.call(y[x].context);break;case 2:y[x].fn.call(y[x].context,h);break;case 3:y[x].fn.call(y[x].context,h,u);break;case 4:y[x].fn.call(y[x].context,h,u,d);break;default:if(!T)for(S=1,T=new Array(E-1);S<E;S++)T[S-1]=arguments[S];y[x].fn.apply(y[x].context,T)}}return!0},o.prototype.on=function(c,h,u){return r(this,c,h,u,!1)},o.prototype.once=function(c,h,u){return r(this,c,h,u,!0)},o.prototype.removeListener=function(c,h,u,d){var f=t?t+c:c;if(!this._events[f])return this;if(!h)return a(this,f),this;var m=this._events[f];if(m.fn)m.fn===h&&(!d||m.once)&&(!u||m.context===u)&&a(this,f);else{for(var g=0,y=[],E=m.length;g<E;g++)(m[g].fn!==h||d&&!m[g].once||u&&m[g].context!==u)&&y.push(m[g]);y.length?this._events[f]=1===y.length?y[0]:y:a(this,f)}return this},o.prototype.removeAllListeners=function(c){var h;return c?this._events[h=t?t+c:c]&&a(this,h):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o}(ur);var xs=Zr(ur.exports);class dr{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const a=(c,h)=>{(h=h||{}).frag=this.frag,h.id=this.id,c===p.ERROR&&(this.error=h.error),this.hls.trigger(c,h)};this.observer=new xs,this.observer.on(p.FRAG_DECRYPTED,a),this.observer.on(p.ERROR,a);const o=Oe(r.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:o.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&typeof Worker<"u"&&(r.workerPath||function Xa(){return"function"==typeof __HLS_WORKER_BUNDLE__}()))try{r.workerPath?(v.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=function Ja(n){const e=new self.URL(n,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}(r.workerPath)):(v.log(`injecting Web Worker for "${t}"`),this.workerContext=function Qa(){const n=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(n);return{worker:new self.Worker(e),objectURL:e}}()),this.onwmsg=u=>this.onWorkerMessage(u);const{worker:h}=this.workerContext;h.addEventListener("message",this.onwmsg),h.onerror=u=>{const d=new Error(`${u.message}  (${u.filename}:${u.lineno})`);r.enableWorker=!1,v.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(p.ERROR,{type:B.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})},h.postMessage({cmd:"init",typeSupported:l,vendor:"",id:t,config:JSON.stringify(r)})}catch(h){v.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.resetWorker(),this.error=null,this.transmuxer=new hr(this.observer,l,r,"",t)}else this.transmuxer=new hr(this.observer,l,r,"",t)}resetWorker(){if(this.workerContext){const{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{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,s,i,r,a,o,l,c,h){var u,d;c.transmuxing.start=self.performance.now();const{transmuxer:f}=this,m=a?a.start:r.start,g=r.decryptdata,y=this.frag,E=!(y&&r.cc===y.cc),T=!(y&&c.level===y.level),x=y?c.sn-y.sn:-1,R=this.part?c.part-this.part.index:-1,b=!T&&(1===x||0===x&&(1===R||0===x&&c.id>1&&c.id===y?.stats.chunkCount&&R<=0)),L=self.performance.now();(T||x||0===r.stats.parsing.start)&&(r.stats.parsing.start=L),a&&(R||!b)&&(a.stats.parsing.start=L);const C=!(y&&(null==(u=r.initSegment)?void 0:u.url)===(null==(d=y.initSegment)?void 0:d.url)),w=new wo(E,b,l,T,m,C);if(!b||E||C){v.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id}\n        discontinuity: ${E}\n        trackSwitch: ${T}\n        contiguous: ${b}\n        accurateTimeOffset: ${l}\n        timeOffset: ${m}\n        initSegmentChange: ${C}`);const I=new _o(s,i,t,o,h);this.configureTransmuxer(I)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:g,chunkMeta:c,state:w},e instanceof ArrayBuffer?[e]:[]);else if(f){const I=f.push(e,g,c,w);Ct(I)?(f.async=!0,I.then(_=>{this.handleTransmuxComplete(_)}).catch(_=>{this.transmuxerError(_,c,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(I))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let s=t.flush(e);Ct(s)||t.async?(Ct(s)||(s=Promise.resolve(s)),s.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(s,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data;if(null==t||!t.event)return void v.warn("worker message received with no "+(t?"event name":"data"));const s=this.hls;if(this.hls)switch(t.event){case"init":{var i;const r=null==(i=this.workerContext)?void 0:i.objectURL;r&&self.URL.revokeObjectURL(r);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":v[t.data.logType]&&v[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,s.trigger(t.event,t.data)}}configureTransmuxer(e){const{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)}}function gr(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!et(n[t].attrs,e[t].attrs))return!1;return!0}function et(n,e,t){const s=n["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>n[i]!==e[i])}function vs(n,e){return e.label.toLowerCase()===n.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(n.lang||"").toLowerCase())}class Mo{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end:s=>t("end",s,e.length),start:s=>t("start",s,e.length)}}}class Uo{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,s){const i=this.queues[t];i.push(e),1===i.length&&!s&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const s=new Promise(r=>{t=r});return this.append({execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}},e),s}executeNext(e){const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(i){v.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${i}`),s.onError(i);const r=this.buffers[e];null!=r&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const pr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;function yr(n){const e=n.querySelectorAll("source");[].slice.call(e).forEach(t=>{n.removeChild(t)})}const Go={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},Er=n=>String.fromCharCode(Go[n]||n),_e=100,Ko={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Vo={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Ho={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Wo={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Yo=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class qo{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s="function"==typeof t?t():t;v.log(`${this.time} [${e}] ${s}`)}}}const Ue=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class Tr{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class jo{constructor(){this.uchar=" ",this.penState=new Tr}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return" "===this.uchar&&this.penState.isDefault()}}class zo{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Tr,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<_e;t++)this.chars.push(new jo);this.logger=e}equals(e){for(let t=0;t<_e;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<_e;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<_e;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>_e&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=_e)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Er(e);this.pos>=_e?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<_e;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<_e;s++){const i=this.chars[s].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Ss{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<15;t++)this.rows.push(new zo(e));this.logger=e}reset(){for(let e=0;e<15;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let s=0;s<15;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<15;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<15;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+JSON.stringify(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<15;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[r].cueStartTime,l=this.logger.time;if(null!==o&&null!==l&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(a.rows[r+c])}}this.currRow=t;const s=this.rows[this.currRow];if(null!==e.indent){const a=Math.max(e.indent-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}this.setPen({foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1})}setBkgData(e){this.logger.log(2,()=>"bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const t=this.rows.splice(this.currRow+1-this.nrRollUpRows,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<15;r++){const a=this.rows[r].getTextString();a&&(i=r+1,t.push(e?"Row "+i+": '"+a+"'":a.trim()))}return t.length>0&&(s=e?"["+t.join(" | ")+"]":t.join("\n")),s}getTextAndFormat(){return this.rows}}class xr{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Ss(s),this.nonDisplayedMemory=new Ss(s),this.lastOutputScreen=new Ss(s),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),("MODE_PAINT-ON"===this.mode||"MODE_ROLL-UP"===this.mode)&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const 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){const t={flash:!1};if(t.underline=e%2==1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][s]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class vr{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const i=this.logger=new qo;this.channels=[null,new xr(e,t,i),new xr(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=127&t[s],r=127&t[s+1];let a=!1,o=null;if(0===i&&0===r)continue;this.logger.log(3,()=>"["+Ue([t[s],t[s+1]])+"] -> ("+Ue([i,r])+")");const l=this.cmdHistory;if(i>=16&&i<=31){if(Xo(i,r,l)){_t(null,null,l),this.logger.log(3,()=>"Repeated command ("+Ue([i,r])+") is dropped");continue}_t(i,r,this.cmdHistory),a=this.parseCmd(i,r),a||(a=this.parseMidrow(i,r)),a||(a=this.parsePAC(i,r)),a||(a=this.parseBackgroundAttributes(i,r))}else _t(null,null,l);if(!a&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Ue([i,r])+" orig: "+Ue([t[s],t[s+1]]))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;const r=20===e||21===e||23===e?1:2,a=this.channels[r];return 20===e||21===e||28===e||29===e?32===t?a.ccRCL():33===t?a.ccBS():34===t?a.ccAOF():35===t?a.ccAON():36===t?a.ccDER():37===t?a.ccRU(2):38===t?a.ccRU(3):39===t?a.ccRU(4):40===t?a.ccFON():41===t?a.ccRDC():42===t?a.ccTR():43===t?a.ccRTD():44===t?a.ccEDM():45===t?a.ccCR():46===t?a.ccENM():47===t&&a.ccEOC():a.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((17===e||25===e)&&t>=32&&t<=47){if(s=17===e?1:2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return!!i&&(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Ue([e,t])+")"),!0)}return!1}parsePAC(e,t){let s;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;const a=e<=23?1:2;s=t>=64&&t<=95?1===a?Ko[e]:Ho[e]:1===a?Vo[e]:Wo[e];const o=this.channels[a];return!!o&&(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0)}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return s=t>95?t-96:t-64,i.underline=1==(1&s),s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((s-16)/2),i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let a;a=17===r?t+80:18===r?t+112:t+144,this.logger.log(2,()=>"Special char '"+Er(a)+"' in channel "+s),i=[a]}else e>=32&&e<=127&&(i=0===t?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes =  "+Ue(i).join(",")),i}parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;let r;const a={};return 16===e||24===e?(r=Math.floor((t-32)/2),a.background=Yo[r],t%2==1&&(a.background=a.background+"_semi")):45===t?a.background="transparent":(a.foreground="black",47===t&&(a.underline=!0)),this.channels[e<=23?1:2].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}_t(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function _t(n,e,t){t.a=n,t.b=e}function Xo(n,e,t){return t.a===n&&t.b===e}class wt{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var As=function(){if(null!=Be&&Be.VTTCue)return self.VTTCue;const n=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if("string"!=typeof l||!Array.isArray(o))return!1;const c=l.toLowerCase();return!!~o.indexOf(c)&&c}function i(o){return t(e,o)}function r(o,...l){let c=1;for(;c<arguments.length;c++){const h=arguments[c];for(const u in h)o[u]=h[u]}return o}function a(o,l,c){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",f=!1,m=o,g=l,y=c,E=null,T="",x=!0,R="auto",S="start",b=50,L="middle",C=50,w="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(I){d=""+I}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return m},set:function(I){if("number"!=typeof I)throw new TypeError("Start time must be set to a number.");m=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return g},set:function(I){if("number"!=typeof I)throw new TypeError("End time must be set to a number.");g=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return y},set:function(I){y=""+I,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return E},set:function(I){E=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return T},set:function(I){const _=function s(o){return t(n,o)}(I);if(!1===_)throw new SyntaxError("An invalid or illegal string was specified.");T=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return x},set:function(I){x=!!I,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return R},set:function(I){if("number"!=typeof I&&"auto"!==I)throw new SyntaxError("An invalid number or illegal string was specified.");R=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return S},set:function(I){const _=i(I);if(!_)throw new SyntaxError("An invalid or illegal string was specified.");S=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return b},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");b=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return L},set:function(I){const _=i(I);if(!_)throw new SyntaxError("An invalid or illegal string was specified.");L=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return C},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");C=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return w},set:function(I){const _=i(I);if(!_)throw new SyntaxError("An invalid or illegal string was specified.");w=_,this.hasBeenReset=!0}})),h.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class Jo{decode(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Sr(n){function e(s,i,r,a){return 3600*(0|s)+60*(0|i)+(0|r)+parseFloat(a||0)}const t=n.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class Zo{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&""!==t&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){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)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Ar(n,e,t,s){const i=s?n.split(s):[n];for(const r in i){if("string"!=typeof i[r])continue;const a=i[r].split(t);2===a.length&&e(a[0],a[1])}}const Ls=new As(0,0,""),Pt="middle"===Ls.align?"middle":"center";function el(n,e,t){const s=n;function i(){const o=Sr(n);if(null===o)throw new Error("Malformed timestamp: "+s);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function a(){n=n.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),"--\x3e"!==n.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);n=n.slice(3),a(),e.endTime=i(),a(),function r(o,l){const c=new Zo;Ar(o,function(d,f){let m;switch(d){case"region":for(let g=t.length-1;g>=0;g--)if(t[g].id===f){c.set(d,t[g].region);break}break;case"vertical":c.alt(d,f,["rl","lr"]);break;case"line":m=f.split(","),c.integer(d,m[0]),c.percent(d,m[0])&&c.set("snapToLines",!1),c.alt(d,m[0],["auto"]),2===m.length&&c.alt("lineAlign",m[1],["start",Pt,"end"]);break;case"position":m=f.split(","),c.percent(d,m[0]),2===m.length&&c.alt("positionAlign",m[1],["start",Pt,"end","line-left","line-right","auto"]);break;case"size":c.percent(d,f);break;case"align":c.alt(d,f,["start",Pt,"end","left","right"])}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let h=c.get("line","auto");"auto"===h&&-1===Ls.line&&(h=-1),l.line=h,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Pt);let u=c.get("position","auto");"auto"===u&&50===Ls.position&&(u="start"===l.align||"left"===l.align?0:"end"===l.align||"right"===l.align?100:50),l.position=u}(n,e)}function Lr(n){return n.replace(/<br(?: \/)?>/gi,"\n")}class tl{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Jo,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;function s(){let r=t.buffer,a=0;for(r=Lr(r);a<r.length&&"\r"!==r[a]&&"\n"!==r[a];)++a;const o=r.slice(0,a);return"\r"===r[a]&&++a,"\n"===r[a]&&++a,t.buffer=r.slice(a),o}function i(r){Ar(r,function(a,o){},/:/)}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let r="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^(\xef\xbb\xbf)?WEBVTT([ \t].*)?$/);if(null==o||!o[0])throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new As(0,0,""),t.state="CUE",-1===r.indexOf("--\x3e")){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{el(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=-1!==r.indexOf("--\x3e");if(!r||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+="\n"),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||"HEADER"===e.state)&&(e.buffer+="\n\n",e.parse()),"INITIAL"===e.state||"BADWEBVTT"===e.state)throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const sl=/\r\n|\n\r|\n|\r/g,Rs=function(e,t,s=0){return e.slice(s,s+t.length)===t},Is=function(e){let t=5381,s=e.length;for(;s;)t=33*t^e.charCodeAt(--s);return(t>>>0).toString()};function bs(n,e,t){return Is(n.toString())+Is(e.toString())+Is(t)}const Ds="stpp.ttml.im1t",Rr=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Ir=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,al={left:"start",center:"center",right:"end",start:"start",end:"end"};function br(n,e,t,s){const i=K(new Uint8Array(n),["mdat"]);if(0===i.length)return void s(new Error("Could not parse IMSC1 mdat"));const r=i.map(o=>xe(o)),a=function vo(n,e,t=1,s=!1){return ys(n,e,1/t,s)}(e.baseTime,1,e.timescale);try{r.forEach(o=>t(function ol(n,e){const i=(new DOMParser).parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(r).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||r[d],u),{}),o="preserve"!==i.getAttribute("xml:space"),l=Dr(Cs(i,"styling","style")),c=Dr(Cs(i,"layout","region")),h=Cs(i,"body","[begin]");return[].map.call(h,u=>{const d=Cr(u,o);if(!d||!u.hasAttribute("begin"))return null;const f=ws(u.getAttribute("begin"),a),m=ws(u.getAttribute("dur"),a);let g=ws(u.getAttribute("end"),a);if(null===f)throw _r(u);if(null===g){if(null===m)throw _r(u);g=f+m}const y=new As(f-e,g-e,d);y.id=bs(y.startTime,y.endTime,y.text);const x=function ll(n,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const a=null!=n&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(i=t[a]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((o,l)=>{const c=_s(e,s,l)||_s(n,s,l)||_s(i,s,l);return c&&(o[l]=c),o},{})}(c[u.getAttribute("region")],l[u.getAttribute("style")],l),{textAlign:R}=x;if(R){const S=al[R];S&&(y.lineAlign=S),y.align=R}return te(y,x),y}).filter(u=>null!==u)}(o,a)))}catch(o){s(o)}}function Cs(n,e,t){const s=n.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Dr(n){return n.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Cr(n,e){return[].slice.call(n.childNodes).reduce((t,s,i)=>{var r;return"br"===s.nodeName&&i?t+"\n":null!=(r=s.childNodes)&&r.length?Cr(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function _s(n,e,t){return n&&n.hasAttributeNS(e,t)?n.getAttributeNS(e,t):null}function _r(n){return new Error(`Could not parse ttml timestamp ${n}`)}function ws(n,e){if(!n)return null;let t=Sr(n);return null===t&&(Rr.test(n)?t=function cl(n,e){const t=Rr.exec(n);return 3600*(0|t[1])+60*(0|t[2])+(0|t[3])+((0|t[4])+(0|t[5])/e.subFrameRate)/e.frameRate}(n,e):Ir.test(n)&&(t=function hl(n,e){const t=Ir.exec(n),s=Number(t[1]);switch(t[2]){case"h":return 3600*s;case"m":return 60*s;case"ms":return 1e3*s;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}(n,e))),t}function wr(n){return n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function Pr(n,e){return!!n&&n.kind===wr(e)&&vs(e,n)}function dl(n,e,t,s){return Math.min(e,s)-Math.max(n,t)}class Ps{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&F(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0)return void(this.clientRect=null);const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&v.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,Ps.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.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(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(null==e||!e.length)return-1;const i=(o,l)=>!l||o.width!==l.width||o.height!==l.height;let r=e.length-1;const a=Math.max(t,s);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=a||l.height>=a)&&i(l,e[o+1])){r=o;break}}return r}}const kt="[eme]";let gl=(()=>{class n{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=n.CDMCleanupPromise?[n.CDMCleanupPromise]:[],this.debug=v.debug.bind(v,kt),this.log=v.log.bind(v,kt),this.warn=v.warn.bind(v,kt),this.error=v.error.bind(v,kt),this.onMediaEncrypted=s=>{const{initDataType:i,initData:r}=s,a=`"${s.type}" event: init data type: "${i}"`;if(this.debug(a),null!==r){if(!this.keyFormatPromise){let o=Object.keys(this.keySystemAccessPromises);o.length||(o=nt(this.config));const l=o.map(Ht).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(l)}this.keyFormatPromise.then(o=>{const l=Kt(o);let c,h;if("sinf"===i){if(l!==z.FAIRPLAY)return void this.warn(`Ignoring unexpected "${s.type}" event with init data type: "${i}" for selected key-system ${l}`);const g=ie(new Uint8Array(r));try{const E=si($t(JSON.parse(g).sinf));if(!E)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=E.subarray(8,24),h=z.FAIRPLAY}catch(y){return void this.warn(`${a} Failed to parse sinf: ${y}`)}}else{if(l!==z.WIDEVINE&&l!==z.PLAYREADY)return void this.warn(`Ignoring unexpected "${s.type}" event with init data type: "${i}" for selected key-system ${l}`);const g=function Vn(n){const e=[];if(n instanceof ArrayBuffer){const t=n.byteLength;let s=0;for(;s+32<t;){const r=Hn(new DataView(n,s));e.push(r),s+=r.size}}return e}(r),y=g.filter(T=>!!T.systemId&&Vt(T.systemId)===l);y.length>1&&this.warn(`${a} Using first of ${y.length} pssh found for selected key-system ${l}`);const E=y[0];if(!E)return void(0===g.length||g.some(T=>!T.systemId)?this.warn(`${a} contains incomplete or invalid pssh data`):this.log(`ignoring ${a} for ${g.map(T=>Vt(T.systemId)).join(",")} pssh data in favor of playlist keys`));if(h=Vt(E.systemId),0===E.version&&E.data)if(h===z.WIDEVINE){const T=E.data.length-22;c=E.data.subarray(T,T+16)}else h===z.PLAYREADY&&(c=qs(E.data))}if(!h||!c)return void this.log(`Unable to handle ${a} with key-system ${l}`);const u=ve_hexDump(c),{keyIdToKeySessionPromise:d,mediaKeySessions:f}=this;let m=d[u];for(let g=0;g<f.length;g++){const y=f[g],E=y.decryptdata;if(!E.keyId)continue;const T=ve_hexDump(E.keyId);if(u===T||-1!==E.uri.replace(/-/g,"").indexOf(u)){if(m=d[T],E.pssh)break;delete d[T],E.pssh=new Uint8Array(r),E.keyId=c,m=d[u]=m.then(()=>this.generateRequestWithPreferredKeySession(y,i,r,"encrypted-event-key-match")),m.catch(x=>this.handleError(x));break}}if(!m){if(h!==l)return void this.log(`Ignoring "${a}" with ${h} init data for selected key-system ${l}`);m=d[u]=this.getKeySystemSelectionPromise([h]).then(({keySystem:g,mediaKeys:y})=>{var E;this.throwIfDestroyed();const T=new Qe("ISO-23001-7",u,null!=(E=Ht(g))?E:"");return T.pssh=new Uint8Array(r),T.keyId=c,this.attemptSetMediaKeys(g,y).then(()=>{this.throwIfDestroyed();const x=this.createMediaKeySessionContext({decryptdata:T,keySystem:g,mediaKeys:y});return this.generateRequestWithPreferredKeySession(x,i,r,"encrypted-event-no-match")})}),m.catch(g=>this.handleError(g))}})}},this.onWaitingForKey=s=>{this.log(`"${s.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(t){const{drmSystems:s,widevineLicenseUrl:i}=this.config,r=s[t];return r?r.licenseUrl:t===z.WIDEVINE&&i?i:void 0}getLicenseServerUrlOrThrow(t){const s=this.getLicenseServerUrl(t);if(void 0===s)throw new Error(`no license server URL configured for key-system "${t}"`);return s}getServerCertificateUrl(t){const{drmSystems:s}=this.config,i=s[t];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const s=this.hls.levels,i=(o,l,c)=>!!o&&c.indexOf(o)===l,r=s.map(o=>o.audioCodec).filter(i),a=s.map(o=>o.videoCodec).filter(i);return r.length+a.length===0&&a.push("avc1.42e01e"),new Promise((o,l)=>{const c=h=>{const u=h.shift();this.getMediaKeysPromise(u,r,a).then(d=>o({keySystem:u,mediaKeys:d})).catch(d=>{h.length?c(h):l(d instanceof me?d:new me({type:B.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};c(t)})}requestMediaKeySystemAccess(t,s){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let r=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Ys&&"http:"===self.location.protocol&&(r=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(r))}return i(t,s)}getMediaKeysPromise(t,s,i){const r=function En(n,e,t,s){let i;switch(n){case z.FAIRPLAY:i=["cenc","sinf"];break;case z.WIDEVINE:case z.PLAYREADY:i=["cenc"];break;case z.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return function Tn(n,e,t,s){return[{initDataTypes:n,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs="${r}"`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs="${r}"`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}(i,e,t,s)}(t,s,i,this.config.drmSystemOptions),a=this.keySystemAccessPromises[t];let o=a?.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${t}" key-system access with config: ${JSON.stringify(r)}`),o=this.requestMediaKeySystemAccess(t,r);const l=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(c=>{this.log(`Failed to obtain access to key-system "${t}": ${c}`)}),o.then(c=>{this.log(`Access for key-system "${c.keySystem}" obtained`);const h=this.fetchServerCertificate(t);return this.log(`Create media-keys for "${t}"`),l.mediaKeys=c.createMediaKeys().then(u=>(this.log(`Media-keys created for "${t}"`),h.then(d=>d?this.setMediaKeysServerCertificate(u,t,d):u))),l.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${t}"}: ${u}`)}),l.mediaKeys})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:s,mediaKeys:i}){this.log(`Creating key-system session "${s}" keyId: ${ve_hexDump(t.keyId||[])}`);const r=i.createSession(),a={decryptdata:t,keySystem:s,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a}renewKeySession(t){const s=t.decryptdata;if(s.pssh){const i=this.createMediaKeySessionContext(t),r=this.getKeyIdString(s);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,"cenc",s.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}getKeyIdString(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return ve_hexDump(t.keyId)}updateKeySession(t,s){var i;const r=t.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyID ${ve_hexDump((null==(i=t.decryptdata)?void 0:i.keyId)||[])}\n      } (data length: ${s&&s.byteLength})`),r.update(s)}selectKeySystemFormat(t){const s=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)),this.keyFormatPromise}getKeyFormatPromise(t){return new Promise((s,i)=>{const r=nt(this.config),a=t.map(Kt).filter(o=>!!o&&-1!==r.indexOf(o));return this.getKeySystemSelectionPromise(a).then(({keySystem:o})=>{const l=Ht(o);l?s(l):i(new Error(`Unable to find format for key-system "${o}"`))}).catch(i)})}loadKey(t){const s=t.keyInfo.decryptdata,i=this.getKeyIdString(s),r=`(keyId: ${i} format: "${s.keyFormat}" method: ${s.method} uri: ${s.uri})`;this.log(`Starting session for key ${r}`);let a=this.keyIdToKeySessionPromise[i];return a||(a=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(s).then(({keySystem:o,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${r}`),this.attemptSetMediaKeys(o,l).then(()=>{this.throwIfDestroyed();const c=this.createMediaKeySessionContext({keySystem:o,mediaKeys:l,decryptdata:s});return this.generateRequestWithPreferredKeySession(c,"cenc",s.pssh,"playlist-key")}))),a.catch(o=>this.handleError(o))),a}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t){this.hls&&(this.error(t.message),this.hls.trigger(p.ERROR,t instanceof me?t.data:{type:B.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))}getKeySystemForKeyPromise(t){const s=this.getKeyIdString(t),i=this.keyIdToKeySessionPromise[s];if(!i){const r=Kt(t.keyFormat),a=r?[r]:nt(this.config);return this.attemptKeySystemAccess(a)}return i}getKeySystemSelectionPromise(t){if(t.length||(t=nt(this.config)),0===t.length)throw new me({type:B.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,s){const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const r=Promise.all(i).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(s)});return this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${t}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(a=>-1===i.indexOf(a))})}generateRequestWithPreferredKeySession(t,s,i,r){var a,o;const l=null==(a=this.config.drmSystems)||null==(o=a[t.keySystem])?void 0:o.generateRequest;if(l)try{const g=l.call(this.hls,s,i,t);if(!g)throw new Error("Invalid response from configured generateRequest filter");s=g.initDataType,i=t.decryptdata.pssh=g.initData?new Uint8Array(g.initData):null}catch(g){var c;if(this.warn(g.message),null!=(c=this.hls)&&c.config.debug)throw g}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t);const h=this.getKeyIdString(t.decryptdata);this.log(`Generating key-session request for "${r}": ${h} (init data type: ${s} length: ${i?i.byteLength:null})`);const u=new xs,d=t._onmessage=g=>{const y=t.mediaKeysSession;if(!y)return void u.emit("error",new Error("invalid state"));const{messageType:E,message:T}=g;this.log(`"${E}" message event for session "${y.sessionId}" message size: ${T.byteLength}`),"license-request"===E||"license-renewal"===E?this.renewLicense(t,T).catch(x=>{this.handleError(x),u.emit("error",x)}):"license-release"===E?t.keySystem===z.FAIRPLAY&&(this.updateKeySession(t,Gt("acknowledged")),this.removeSession(t)):this.warn(`unhandled media key message type "${E}"`)},f=t._onkeystatuseschange=g=>{if(!t.mediaKeysSession)return void u.emit("error",new Error("invalid state"));this.onKeyStatusChange(t);const E=t.keyStatus;u.emit("keyStatus",E),"expired"===E&&(this.warn(`${t.keySystem} expired for key ${h}`),this.renewKeySession(t))};t.mediaKeysSession.addEventListener("message",d),t.mediaKeysSession.addEventListener("keystatuseschange",f);const m=new Promise((g,y)=>{u.on("error",y),u.on("keyStatus",E=>{E.startsWith("usable")?g():"output-restricted"===E?y(new me({type:B.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):"internal-error"===E?y(new me({type:B.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${E}"`)):"expired"===E?y(new Error("key expired while generating request")):this.warn(`unhandled key status change "${E}"`)})});return t.mediaKeysSession.generateRequest(s,i).then(()=>{var g;this.log(`Request generated for key-session "${null==(g=t.mediaKeysSession)?void 0:g.sessionId}" keyId: ${h}`)}).catch(g=>{throw new me({type:B.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_NO_SESSION,error:g,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>m).catch(g=>{throw u.removeAllListeners(),this.removeSession(t),g}).then(()=>(u.removeAllListeners(),t))}onKeyStatusChange(t){t.mediaKeysSession.keyStatuses.forEach((s,i)=>{this.log(`key status change "${s}" for keyStatuses keyId: ${ve_hexDump("buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i))} session keyId: ${ve_hexDump(new Uint8Array(t.decryptdata.keyId||[]))} uri: ${t.decryptdata.uri}`),t.keyStatus=s})}fetchServerCertificate(t){const s=this.config,r=new(0,s.loader)(s),a=this.getServerCertificateUrl(t);return a?(this.log(`Fetching server certificate for "${t}"`),new Promise((o,l)=>{const c={responseType:"arraybuffer",url:a},h=s.certLoadPolicy.default;r.load(c,{loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},{onSuccess:(f,m,g,y)=>{o(f.data)},onError:(f,m,g,y)=>{l(new me({type:B.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:re({url:c.url,data:void 0},f)},`"${t}" certificate request failed (${a}). Status: ${f.code} (${f.text})`))},onTimeout:(f,m,g)=>{l(new me({type:B.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${a})`))},onAbort:(f,m,g)=>{l(new Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(t,s,i){return new Promise((r,a)=>{t.setServerCertificate(i).then(o=>{this.log(`setServerCertificate ${o?"success":"not supported by CDM"} (${i?.byteLength}) on "${s}"`),r(t)}).catch(o=>{a(new me({type:B.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:o,fatal:!0},o.message))})})}renewLicense(t,s){return this.requestLicense(t,new Uint8Array(s)).then(i=>this.updateKeySession(t,new Uint8Array(i)).catch(r=>{throw new me({type:B.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:r,fatal:!0},r.message)}))}unpackPlayReadyKeyMessage(t,s){const i=String.fromCharCode.apply(null,new Uint16Array(s.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),s;const r=(new DOMParser).parseFromString(i,"application/xml"),a=r.querySelectorAll("HttpHeader");if(a.length>0){let u;for(let d=0,f=a.length;d<f;d++){var o,l;u=a[d];const m=null==(o=u.querySelector("name"))?void 0:o.textContent,g=null==(l=u.querySelector("value"))?void 0:l.textContent;m&&g&&t.setRequestHeader(m,g)}}const c=r.querySelector("Challenge"),h=c?.textContent;if(!h)throw new Error("Cannot find <Challenge> in key message");return Gt(atob(h))}setupLicenseXHR(t,s,i,r){const a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>{if(!i.decryptdata)throw new Error("Key removed");return a.call(this.hls,t,s,i,r)}).catch(o=>{if(!i.decryptdata)throw o;return t.open("POST",s,!0),a.call(this.hls,t,s,i,r)}).then(o=>(t.readyState||t.open("POST",s,!0),{xhr:t,licenseChallenge:o||r})):(t.open("POST",s,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,s){const i=this.config.keyLoadPolicy.default;return new Promise((r,a)=>{const o=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${o}`);const l=new XMLHttpRequest;l.responseType="arraybuffer",l.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return a(new Error("invalid state"));if(4===l.readyState)if(200===l.status){this._requestLicenseFailureCount=0;let c=l.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const h=this.config.licenseResponseCallback;if(h)try{c=h.call(this.hls,l,o,t)}catch(u){this.error(u)}r(c)}else{const c=i.errorRetry,h=c?c.maxNumRetry:0;this._requestLicenseFailureCount++,this._requestLicenseFailureCount>h||l.status>=400&&l.status<500?a(new me({type:B.KEY_SYSTEM_ERROR,details:A.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:l,response:{url:o,data:void 0,code:l.status,text:l.statusText}},`License Request XHR failed (${o}). Status: ${l.status} (${l.statusText})`)):(this.warn(`Retrying license request, ${h-this._requestLicenseFailureCount+1} attempts left`),this.requestLicense(t,s).then(r,a))}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=l,this.setupLicenseXHR(l,o,t,s).then(({xhr:c,licenseChallenge:h})=>{t.keySystem==z.PLAYREADY&&(h=this.unpackPlayReadyKeyMessage(c,h)),c.send(h)})})}onMediaAttached(t,s){if(!this.config.emeEnabled)return;const i=s.media;this.media=i,i.removeEventListener("encrypted",this.onMediaEncrypted),i.removeEventListener("waitingforkey",this.onWaitingForKey),i.addEventListener("encrypted",this.onMediaEncrypted),i.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const t=this.media,s=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={},Qe.clearKeyUriToKeyIdMap();const i=s.length;n.CDMCleanupPromise=Promise.all(s.map(r=>this.removeSession(r)).concat(t?.setMediaKeys(null).catch(r=>{this.log(`Could not clear media keys: ${r}`)}))).then(()=>{i&&(this.log("finished closing key sessions and clearing media keys"),s.length=0)}).catch(r=>{this.log(`Could not close sessions and clear media keys: ${r}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:s}){if(s&&this.config.emeEnabled&&!this.keyFormatPromise){const i=s.reduce((r,a)=>(-1===r.indexOf(a.keyFormat)&&r.push(a.keyFormat),r),[]);this.log(`Selecting key-system from session-keys ${i.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(i)}}removeSession(t){const{mediaKeysSession:s,licenseXhr:i}=t;if(s){this.log(`Remove licenses and keys and close session ${s.sessionId}`),t._onmessage&&(s.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(s.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(t);return r>-1&&this.mediaKeySessions.splice(r,1),s.remove().catch(a=>{this.log(`Could not remove session: ${a}`)}).then(()=>s.close()).catch(a=>{this.log(`Could not close session: ${a}`)})}}}return n.CDMCleanupPromise=void 0,n})();class me extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var he=function(n){return n.MANIFEST="m",n.AUDIO="a",n.VIDEO="v",n.MUXED="av",n.INIT="i",n.CAPTION="c",n.TIMED_TEXT="tt",n.KEY="k",n.OTHER="o",n}(he||{}),Fr=function(n){return n.DASH="d",n.HLS="h",n.SMOOTH="s",n.OTHER="o",n}(Fr||{}),qe=function(n){return n.OBJECT="CMCD-Object",n.REQUEST="CMCD-Request",n.SESSION="CMCD-Session",n.STATUS="CMCD-Status",n}(qe||{});const ml={[qe.OBJECT]:["br","d","ot","tb"],[qe.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[qe.SESSION]:["cid","pr","sf","sid","st","v"],[qe.STATUS]:["bs","rtp"]};class je{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(s=>s instanceof je?s:new je(s))),this.value=e,this.params=t}}class Or{constructor(e){this.description=void 0,this.description=e}}const pl="Dict";const Mr="Bare Item",Tl="Boolean",xl="Byte Sequence",vl="Decimal",Sl="Integer",Ll=/[\x00-\x1f\x7f]+/,Rl="Token",Il="Key";function Ie(n,e,t){return function El(n,e,t,s){return new Error(`failed to ${n} "${function yl(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n)}(e)}" as ${t}`,{cause:s})}("serialize",n,e,t)}function Nr(n){if(function Al(n){return n<-999999999999999||999999999999999<n}(n))throw Ie(n,Sl);return n.toString()}function Ur(n,e){if(n<0)return-Ur(-n,e);const t=Math.pow(10,e);if(Math.abs(n*t%1-.5)<Number.EPSILON){const i=Math.floor(n*t);return(i%2==0?i:i+1)/t}return Math.round(n*t)/t}function wl(n){const e=Ur(n,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ie(n,vl);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Pl="String";function Br(n){const e=function Fl(n){return n.description||n.toString().slice(7,-1)}(n);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw Ie(e,Rl);return e}function ks(n){switch(typeof n){case"number":if(!F(n))throw Ie(n,Mr);return Number.isInteger(n)?Nr(n):wl(n);case"string":return function kl(n){if(Ll.test(n))throw Ie(n,Pl);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(n);case"symbol":return Br(n);case"boolean":return function bl(n){if("boolean"!=typeof n)throw Ie(n,Tl);return n?"?1":"?0"}(n);case"object":if(n instanceof Date)return function _l(n){return`@${Nr(n.getTime()/1e3)}`}(n);if(n instanceof Uint8Array)return function Cl(n){if(!1===ArrayBuffer.isView(n))throw Ie(n,xl);return`:${function Dl(n){return btoa(String.fromCharCode(...n))}(n)}:`}(n);if(n instanceof Or)return Br(n);default:throw Ie(n,Mr)}}function Fs(n){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(n))throw Ie(n,Il);return n}function Os(n){return null==n?"":Object.entries(n).map(([e,t])=>!0===t?`;${Fs(e)}`:`;${Fs(e)}=${ks(t)}`).join("")}function $r(n){return n instanceof je?`${ks(n.value)}${Os(n.params)}`:ks(n)}const Ul=n=>"ot"===n||"sf"===n||"st"===n,Bl=n=>"number"==typeof n?F(n):null!=n&&""!==n&&!1!==n,Ft=n=>Math.round(n),Ot=n=>100*Ft(n/100),Vl={br:Ft,d:Ft,bl:Ot,dl:Ot,mtp:Ot,nor:(n,e)=>(null!=e&&e.baseUrl&&(n=function $l(n,e){const t=new URL(n),s=new URL(e);if(t.origin!==s.origin)return n;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")}(n,e.baseUrl)),encodeURIComponent(n)),rtp:Ot,tb:Ft};function Gr(n,e={}){return n?function Nl(n,e){return function Ml(n,e={whitespace:!0}){if("object"!=typeof n)throw Ie(n,pl);const t=n instanceof Map?n.entries():Object.entries(n),s=null!=e&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof je||(r=new je(r));let a=Fs(i);return!0===r.value?a+=Os(r.params):(a+="=",Array.isArray(r.value)?a+=function Ol(n){return`(${n.value.map($r).join(" ")})${Os(n.params)}`}(r):a+=$r(r)),a}).join(`,${s}`)}(n,e)}(function Hl(n,e){const t={};if(null==n||"object"!=typeof n)return t;const s=Object.keys(n).sort(),i=te({},Vl,e?.formatters),r=e?.filter;return s.forEach(a=>{if(null!=r&&r(a))return;let o=n[a];const l=i[a];l&&(o=l(o,e)),("v"!==a||1!==o)&&("pr"==a&&1===o||Bl(o)&&(Ul(a)&&"string"==typeof o&&(o=new Or(o)),t[a]=o))}),t}(n,e),te({whitespace:!1},e)):""}const Kr=/CMCD=[^&#]+/;function Vr(n,e,t,s){n&&Object.keys(e).forEach(i=>{const r=n.filter(a=>a.groupId===i).map(a=>{const o=te({},a);return o.details=void 0,o.attrs=new ee(o.attrs),o.url=o.attrs.URI=Hr(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});n.push(...r)})}function Hr(n,e,t,s){const{HOST:i,PARAMS:r,[t]:a}=s;let o;e&&(o=a?.[e],o&&(n=o));const l=new self.URL(n);return i&&!o&&(l.host=i),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}const Zl=/^age:\s*[\d.]+\s*$/im;class Wr{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=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new it,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===s&&!this.stats.aborted)return r(s,t.url)}).catch(a=>{if(this.loader===s&&!this.stats.aborted)return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{this.callbacks.onError({code:s.status,text:a.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);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),s.timeout=r&&F(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(0===s.loading.first&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const a=t.status;if(a>=200&&a<300){const u=("text"===t.responseType?t.responseText:null)??t.response;if(null!=u){if(s.loading.end=Math.max(self.performance.now(),s.loading.first),s.loaded=s.total="arraybuffer"===t.responseType?u.byteLength:u.length,s.bwEstimate=8e3*s.total/(s.loading.end-s.loading.first),!this.callbacks)return;const f=this.callbacks.onProgress;if(f&&f(s,e,u,t),!this.callbacks)return;return void this.callbacks.onSuccess({url:t.responseURL,data:u,code:a},s,e,t)}}const l=r.loadPolicy.errorRetry;Et(l,s.retry,!1,{url:e.url,data:void 0,code:a})?this.retry(l):(v.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,s))}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry;if(Et(e,this.stats.retry,!0))this.retry(e);else{var s;v.warn(`timeout while loading ${null==(s=this.context)?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=as(e,s.retry),s.retry++,v.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.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){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Zl.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const tc=/(\d+)-(\d+)\/(\d+)/;class Yr{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||nc,this.controller=new self.AbortController,this.stats=new it}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=function sc(n,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(te({},n.headers))};return n.rangeEnd&&t.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),t}(e,this.controller.signal),a=s.onProgress,o="arraybuffer"===e.responseType,l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&F(c)?c:h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(i,e,this.response)},t.timeout),self.fetch(this.request).then(u=>{this.response=this.loader=u;const d=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(i,e,this.response)},h-(d-i.loading.start)),!u.ok){const{status:f,statusText:m}=u;throw new ac(m||"fetch, bad network response",f,u)}return i.loading.first=d,i.total=function rc(n){const e=n.get("Content-Range");if(e){const s=function ic(n){const e=tc.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(F(s))return s}const t=n.get("Content-Length");if(t)return parseInt(t)}(u.headers)||i.total,a&&F(t.highWaterMark)?this.loadProgressively(u,i,e,t.highWaterMark,a):o?u.arrayBuffer():"json"===e.responseType?u.json():u.text()}).then(u=>{const d=this.response;if(!d)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const f=u[l];f&&(i.loaded=i.total=f);const m={url:d.url,data:u,code:d.status};a&&!F(t.highWaterMark)&&a(i,e,u,d),s.onSuccess(m,i,e,d)}).catch(u=>{self.clearTimeout(this.requestTimeout),i.aborted||s.onError({code:u&&u.code||0,text:u?u.message:null},e,u?u.details:null,i)})}getCacheAge(){let e=null;if(this.response){const 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,s,i=0,r){const a=new Hi,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&r(t,s,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const h=c.value,u=h.length;return t.loaded+=u,u<i||a.dataLength?(a.push(h),a.dataLength>=i&&r(t,s,a.flush(),e)):r(t,s,h,e),l()}).catch(()=>Promise.reject());return l()}}function nc(n,e){return new self.Request(n.url,e)}class ac extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const oc=/\s/,lc={newCue(n,e,t,s){const i=[];let r,a,o,l,c;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(r=s.rows[d],o=!0,l=0,c="",!r.isEmpty()){var u;for(let g=0;g<r.chars.length;g++)oc.test(r.chars[g].uchar)&&o?l++:(c+=r.chars[g].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const f=Lr(c.trim()),m=bs(e,t,f);null!=n&&null!=(u=n.cues)&&u.getCueById(m)||(a=new h(e,t,f),a.id=m,a.line=d+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),i.push(a))}return n&&i.length&&(i.sort((d,f)=>"auto"===d.line||"auto"===f.line?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),i.forEach(d=>Ai(n,d))),i}},qr=re(re({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Wr,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class Fa{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:s,hls:i}=this,{autoLevelEnabled:r,media:a}=i;if(!t||!a)return;const o=performance.now(),l=s?s.stats:t.stats,c=s?s.duration:t.duration,h=o-l.loading.start,u=i.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||t.level<=u)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!r||a.paused||!a.playbackRate||!a.readyState)return;const d=i.mainForwardBufferInfo;if(null===d)return;const f=this.bwEstimator.getEstimateTTFB(),m=Math.abs(a.playbackRate);if(h<=Math.max(f,c/(2*m)*1e3))return;const g=d.len/m,y=l.loading.first?l.loading.first-l.loading.start:-1,E=l.loaded&&y>-1,T=this.getBwEstimate(),x=i.levels,S=l.total||Math.max(l.loaded,Math.round(c*x[t.level].averageBitrate/8));let b=E?h-y:h;b<1&&E&&(b=Math.min(h,8*l.loaded/T));const L=E?1e3*l.loaded/b:0,C=L?(S-l.loaded)/L:8*S/T+f/1e3;if(C<=g)return;const w=L?8*L:T;let _,I=Number.POSITIVE_INFINITY;for(_=t.level-1;_>u&&(I=this.getTimeToLoadFrag(f/1e3,w,c*x[_].maxBitrate,!x[_].details),!(I<g));_--);if(I>=C||I>10*c)return;i.nextLoadLevel=i.nextAutoLevel=_,E?this.bwEstimator.sample(h-Math.min(f,y),l.loaded):this.bwEstimator.sampleTTFB(h);const V=x[_].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>V&&this.resetEstimator(V),this.clearTimer(),v.warn(`[abr] Fragment ${t.sn}${s?" part "+s.index:""} of level ${t.level} is loading too slowly;\n      Time to underbuffer: ${g.toFixed(3)} s\n      Estimated load time for current fragment: ${C.toFixed(3)} s\n      Estimated load time for down switch fragment: ${I.toFixed(3)} s\n      TTFB estimate: ${0|y} ms\n      Current BW estimate: ${F(T)?0|T:"Unknown"} bps\n      New BW estimate: ${0|this.getBwEstimate()} bps\n      Switching to level ${_} @ ${0|V} bps`),i.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:s,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(v.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new Aa(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(p.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;var i;this.ignoreFragment(s)||(s.bitrateTest||(this.fragCurrent=s,this.partCurrent=null!=(i=t.part)?i:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case A.BUFFER_ADD_CODEC_ERROR:case A.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case A.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const a=performance.now(),o=r?r.stats:s.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,s,i){return e+s/t+(i?this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.start;F(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if("main"===t.type&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+i.loaded,l=(a.loaded?a.loaded.duration:0)+(s?s.duration:t.duration);a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}t.bitrateTest?(this.onFragBuffered(p.FRAG_BUFFERED,{stats:i,frag:t,part:s,id:t.type}),t.bitrateTest=!1):this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=null!=i&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),this.bitrateTestDelay=s.bitrateTest?a/1e3:0}ignoreFragment(e){return"main"!==e.type||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),r=this.findBestLevel(s,t,e,0,this.hls.config.maxStarvationDelay,1,1);if(r>-1)return r;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return v.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===e||s&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){const a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this,{maxAutoLevel:i,config:r,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(c){const y=this.findBestLevel(l,a,i,c,0,h,u);if(y>=0)return y}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!c){const y=this.bitrateTestDelay;y&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-y,v.info(`[abr] bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const f=this.findBestLevel(l,a,i,c,d,h,u);if(v.info(`[abr] ${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`),f>-1)return f;const m=s.levels[a],g=s.levels[s.loadLevel];return m?.bitrate<g?.bitrate?a:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,a,o){var l;const c=i+r,h=this.lastLoadedFragLevel,u=-1===h?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:f}=this,{levels:m,allAudioTracks:g,loadLevel:y,config:E}=this.hls;if(1===m.length)return 0;const T=m[u],x=!(null==T||null==(l=T.details)||!l.live),R=-1===y||-1===h;let S,b="SDR",L=T?.frameRate||0;const{audioPreference:C,videoPreference:w}=E,I=this.audioTracksByGroup||(this.audioTracksByGroup=function _a(n){return n.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}(g));if(R){if(-1!==this.firstSelection)return this.firstSelection;const $=this.codecTiers||(this.codecTiers=function wa(n,e,t,s){return n.slice(t,s+1).reduce((i,r)=>{if(!r.codecSet)return i;const a=r.audioGroups;let o=i[r.codecSet];o||(i[r.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return o.minHeight=Math.min(o.minHeight,l),o.minFramerate=Math.min(o.minFramerate,r.frameRate),o.maxScore=Math.max(o.maxScore,r.score),o.fragmentError+=r.fragmentError,o.videoRanges[r.videoRange]=(o.videoRanges[r.videoRange]||0)+1,a&&a.forEach(c=>{if(!c)return;const h=e.groups[c];h&&(o.hasDefaultAudio=o.hasDefaultAudio||e.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(h.channels).forEach(u=>{o.channels[u]=(o.channels[u]||0)+h.channels[u]}))}),i},{})}(m,I,t,s)),U=function Ca(n,e,t,s,i){const r=Object.keys(n),a=s?.channels,o=s?.audioCodec,l=a&&2===parseInt(a);let c=!0,h=!1,u=1/0,d=1/0,f=1/0,m=0,g=[];const{preferHDR:y,allowedVideoRanges:E}=function Da(n,e){let t=!1,s=[];return n&&(t="SDR"!==n,s=[n]),e&&(s=e.allowedVideoRanges||mt.slice(0),t=void 0!==e.preferHDR?e.preferHDR:function ba(){if("function"==typeof matchMedia){const n=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(n.media!==e.media)return!0===n.matches}return!1}(),s=t?s.filter(i=>"SDR"!==i):["SDR"]),{preferHDR:t,allowedVideoRanges:s}}(e,i);for(let S=r.length;S--;){const b=n[r[S]];c=b.channels[2]>0,u=Math.min(u,b.minHeight),d=Math.min(d,b.minFramerate),f=Math.min(f,b.minBitrate);const L=E.filter(C=>b.videoRanges[C]>0);L.length>0&&(h=!0,g=L)}u=F(u)?u:0,d=F(d)?d:0;const T=Math.max(1080,u),x=Math.max(30,d);return f=F(f)?f:t,t=Math.max(f,t),h||(e=void 0,g=[]),{codecSet:r.reduce((S,b)=>{const L=n[b];if(b===S)return S;if(L.minBitrate>t)return be(b,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),S;if(!L.hasDefaultAudio)return be(b,"no renditions with default or auto-select sound found"),S;if(o&&b.indexOf(o.substring(0,4))%5!=0)return be(b,`audio codec preference "${o}" not found`),S;if(a&&!l){if(!L.channels[a])return be(b,`no renditions with ${a} channel sound found (channels options: ${Object.keys(L.channels)})`),S}else if((!o||l)&&c&&0===L.channels[2])return be(b,"no renditions with stereo sound found"),S;return L.minHeight>T?(be(b,`min resolution of ${L.minHeight} > maximum of ${T}`),S):L.minFramerate>x?(be(b,`min framerate of ${L.minFramerate} > maximum of ${x}`),S):g.some(C=>L.videoRanges[C]>0)?L.maxScore<m?(be(b,`max score of ${L.maxScore} < selected max of ${m}`),S):S&&(ut(b)>=ut(S)||L.fragmentError>n[S].fragmentError)?S:(m=L.maxScore,b):(be(b,`no variants with VIDEO-RANGE of ${JSON.stringify(g)} found`),S)},void 0),videoRanges:g,preferHDR:y,minFramerate:d,minBitrate:f}}($,b,e,C,w),{codecSet:Y,videoRanges:J,minFramerate:O,minBitrate:k,preferHDR:q}=U;S=Y,b=q?J[J.length-1]:J[0],L=O,e=Math.max(e,k),v.log(`[abr] picked start tier ${JSON.stringify(U)}`)}else S=T?.codecSet,b=T?.videoRange;const _=f?f.duration:d?d.duration:0,V=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let $=s;$>=t;$--){var G;const U=m[$],Y=$>u;if(!U)continue;if(E.useMediaCapabilities&&!U.supportedResult&&!U.supportedPromise){const se=navigator.mediaCapabilities;"function"==typeof se?.decodingInfo&&La(U,I,b,L,e,C)?(U.supportedPromise=Ra(U,I,se),U.supportedPromise.then(le=>{if(!this.hls)return;U.supportedResult=le;const ce=this.hls.levels,pe=ce.indexOf(U);le.error?v.warn(`[abr] MediaCapabilities decodingInfo error: "${le.error}" for level ${pe} ${JSON.stringify(le)}`):le.supported||(v.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${pe} ${JSON.stringify(le)}`),pe>-1&&ce.length>1&&(v.log(`[abr] Removing unsupported level ${pe}`),this.hls.removeLevel(pe)))})):U.supportedResult=Mi}if(S&&U.codecSet!==S||b&&U.videoRange!==b||Y&&L>U.frameRate||!Y&&L>0&&L<U.frameRate||U.supportedResult&&(null==(G=U.supportedResult.decodingInfoResults)||!G[0].smooth)){P.push($);continue}const J=U.details,O=(f?J?.partTarget:J?.averagetargetduration)||_;let k;k=Y?o*e:a*e;const q=_&&i>=2*_&&0===r?m[$].averageBitrate:m[$].maxBitrate,H=this.getTimeToLoadFrag(V,k,q*O,void 0===J);if(k>=q&&($===h||0===U.loadError&&0===U.fragmentError)&&(H<=V||!F(H)||x&&!this.bitrateTestDelay||H<c)){const se=this.forcedAutoLevel;return $!==y&&(-1===se||se!==y)&&(P.length&&v.trace(`[abr] Skipped level(s) ${P.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${m[P[0]].codecs}" ${m[P[0]].videoRange}; not compatible with "${T.codecs}" ${b}`),v.info(`[abr] switch candidate:${u}->${$} adjustedbw(${Math.round(k)})-bitrate=${Math.round(k-q)} ttfb:${V.toFixed(1)} avgDuration:${O.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${H.toFixed(1)} firstSelection:${R} codecSet:${S} videoRange:${b} hls.loadLevel:${y}`)),R&&(this.firstSelection=$),$}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls,i=Math.min(Math.max(e,s),t);this._nextAutoLevel!==i&&(this.nextAutoLevelKey="",this._nextAutoLevel=i)}},bufferController:class Bo{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.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=s=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:s,mediaSource:i}=this;this.log("Media source opened"),s&&(s.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(p.MEDIA_ATTACHED,{media:s,mediaSource:i})),i&&i.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&v.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e;const t="[buffer-controller]";this.appendSource=function qn(n){return typeof self<"u"&&n===self.ManagedMediaSource}(Oe(e.config.preferManagedMediaSource)),this.log=v.log.bind(v,t),this.warn=v.warn.bind(v,t),this.error=v.error.bind(v,t),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_APPENDING,this.onBufferAppending,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.BUFFER_EOS,this.onBufferEos,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.FRAG_PARSED,this.onFragParsed,this),e.on(p.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_APPENDING,this.onBufferAppending,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_EOS,this.onBufferEos,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.FRAG_PARSED,this.onFragParsed,this),e.off(p.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Uo(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const s=this.media=t.media,i=Oe(this.appendSource);if(s&&i){var r;const a=this.mediaSource=new i;this.log(`created media source: ${null==(r=a.constructor)?void 0:r.name}`),a.addEventListener("sourceopen",this._onMediaSourceOpen),a.addEventListener("sourceended",this._onMediaSourceEnded),a.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.addEventListener("startstreaming",this._onStartStreaming),a.addEventListener("endstreaming",this._onEndStreaming));const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");const l=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||l&&a instanceof l,yr(s),function $o(n,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,n.appendChild(t)}(s,o),s.load()}catch{s.src=o}else s.src=o;s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:s}=this;if(t){if(this.log("media source detaching"),"open"===t.readyState)try{t.endOfStream()}catch(i){this.warn(`onMediaDetaching: ${i.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(e.removeAttribute("src"),this.appendSource&&yr(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(p.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{this.resetBuffer(e)}),this._initSourceBuffer(),this.hls.resumeBuffering()}resetBuffer(e){const t=this.sourceBuffer[e];try{var s;t&&(this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t))}catch(i){this.warn(`onBufferReset ${e}`,i)}}onBufferCodecs(e,t){const s=this.getSourceBufferTypes().length,i=Object.keys(t);if(i.forEach(a=>{if(s){const l=this.tracks[a];if(l&&"function"==typeof l.buffer.changeType){var o;const{id:c,codec:h,levelCodec:u,container:d,metadata:f}=t[a],m=ui(l.codec,l.levelCodec),g=m?.replace(pr,"$1");let y=ui(h,u);const E=null==(o=y)?void 0:o.replace(pr,"$1");y&&g!==E&&("audio"===a.slice(0,5)&&(y=dt(y,this.appendSource)),this.appendChangeType(a,`${d};codecs=${y}`),this.log(`switching codec ${m} to ${y}`),this.tracks[a]={buffer:l.buffer,codec:h,container:d,levelCodec:u,metadata:f,id:c})}}else this.pendingTracks[a]=t[a]}),s)return;const r=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==r&&(this.log(`${r} bufferCodec event(s) expected ${i.join(",")}`),this.bufferCodecEventsExpected=r),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:s}=this,i={execute:()=>{const r=this.sourceBuffer[e];r&&(this.log(`changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),s.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:r=>{this.warn(`Failed to change ${e} SourceBuffer type`,r)}};s.append(i,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:s,operationQueue:i,tracks:r}=this,{data:a,type:o,frag:l,part:c,chunkMeta:h}=t,u=h.buffering[o],d=self.performance.now();u.start=d;const f=l.stats.buffering,m=c?c.stats.buffering:null;0===f.start&&(f.start=d),m&&0===m.start&&(m.start=d);const g=r.audio;let y=!1;"audio"===o&&"audio/mpeg"===g?.container&&(y=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const E=l.start;i.append({execute:()=>{if(u.executeStart=self.performance.now(),y){const x=this.sourceBuffer[o];if(x){const R=E-x.timestampOffset;Math.abs(R)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${E} (delta: ${R}) sn: ${l.sn})`),x.timestampOffset=E)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();u.executeEnd=u.end=x,0===f.first&&(f.first=x),m&&0===m.first&&(m.first=x);const{sourceBuffer:R}=this,S={};for(const b in R)S[b]=Z.getBuffered(R[b]);this.appendErrors[o]=0,"audio"===o||"video"===o?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(p.BUFFER_APPENDED,{type:o,frag:l,part:c,chunkMeta:h,parent:l.type,timeRanges:S})},onError:x=>{const R={type:B.MEDIA_ERROR,parent:l.type,details:A.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:c,chunkMeta:h,error:x,err:x,fatal:!1};if(x.code===DOMException.QUOTA_EXCEEDED_ERR)R.details=A.BUFFER_FULL_ERROR;else{const S=++this.appendErrors[o];R.details=A.BUFFER_APPEND_ERROR,this.warn(`Failed ${S}/${s.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer`),S>=s.config.appendErrorMaxRetry&&(R.fatal=!0)}s.trigger(p.ERROR,R)}},o,!!this.pendingTracks[o])}onBufferFlushing(e,t){const{operationQueue:s}=this,i=r=>({execute:this.removeExecutor.bind(this,r,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(p.BUFFER_FLUSHED,{type:r})},onError:a=>{this.warn(`Failed to remove from ${r} SourceBuffer`,a)}});t.type?s.append(i(t.type),t.type):this.getSourceBufferTypes().forEach(r=>{s.append(i(r),r)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],a=i?i.elementaryStreams:s.elementaryStreams;a.audiovideo?r.push("audiovideo"):(a.audio&&r.push("audio"),a.video&&r.push("video")),0===r.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(()=>{const l=self.performance.now();s.stats.buffering.end=l,i&&(i.stats.buffering.end=l),this.hls.trigger(p.FRAG_BUFFERED,{frag:s,part:i,stats:i?i.stats:s.stats,id:s.type})},r)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((i,r)=>{const a=this.sourceBuffer[r];return a&&(!t.type||t.type===r)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${r} sourceBuffer now EOS`))),i&&!(a&&!a.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(r=>{const a=this.sourceBuffer[r];a&&(a.ending=!1)});const{mediaSource:i}=this;i&&"open"===i.readyState?(this.log("Calling mediaSource.endOfStream()"),i.endOfStream()):i&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${i.readyState}`)}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||null===t||!this.getSourceBufferTypes().length)return;const r=e.config,a=s.currentTime,o=t.levelTargetDuration,l=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if(F(l)&&l>0){const c=Math.max(l,o),h=Math.floor(a/o)*o-c;this.flushBackBuffer(a,o,h)}if(F(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const c=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),h=Math.max(c,o),u=Math.floor(a/o)*o+h;this.flushFrontBuffer(a,o,u)}}flushBackBuffer(e,t,s){const{details:i,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(o=>{const l=r[o];if(l){const c=Z.getBuffered(l);if(c.length>0&&s>c.start(0)){if(this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:s}),null!=i&&i.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(l.ended&&c.end(c.length-1)-e<2*t)return void this.log(`Cannot flush ${o} back buffer while SourceBuffer is in ended state`);this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:o})}}})}flushFrontBuffer(e,t,s){const{sourceBuffer:i}=this;this.getSourceBufferTypes().forEach(a=>{const o=i[a];if(o){const l=Z.getBuffered(o),c=l.length;if(c<2)return;const h=l.start(c-1),u=l.end(c-1);if(s>h||e>=h&&e<=u)return;if(o.ended&&e-u<2*t)return void this.log(`Cannot flush ${a} front buffer while SourceBuffer is in ended state`);this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:h,endOffset:1/0,type:a})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||"open"!==this.mediaSource.readyState)return;const{details:e,hls:t,media:s,mediaSource:i}=this,r=e.fragments[0].start+e.totalduration,a=s.duration,o=F(i.duration)?i.duration:0;e.live&&t.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(e)):(r>o&&r>a||!F(a))&&(this.log(`Updating Media Source duration to ${r.toFixed(3)}`),i.duration=r)}updateSeekableRange(e){const t=this.mediaSource,s=e.fragments;if(s.length&&e.live&&null!=t&&t.setLiveSeekableRange){const r=Math.max(0,s[0].start),a=Math.max(r,r+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${r}-${a}.`),t.setLiveSeekableRange(r,a)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:s}=this,i=Object.keys(s).length;if(i&&(!e||2===i||"audiovideo"in s)){this.createSourceBuffers(s),this.pendingTracks={};const r=this.getSourceBufferTypes();if(r.length)this.hls.trigger(p.BUFFER_CREATED,{tracks:this.tracks}),r.forEach(a=>{t.executeNext(a)});else{const a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const r in e)if(!t[r]){var i;const a=e[r];if(!a)throw Error(`source buffer exists for track ${r}, however track does not`);let o=-1===(null==(i=a.levelCodec)?void 0:i.indexOf(","))?a.levelCodec:a.codec;o&&"audio"===r.slice(0,5)&&(o=dt(o,this.appendSource));const l=`${a.container};codecs=${o}`;this.log(`creating sourceBuffer(${l})`);try{const c=t[r]=s.addSourceBuffer(l),h=r;this.addBufferListener(h,"updatestart",this._onSBUpdateStart),this.addBufferListener(h,"updateend",this._onSBUpdateEnd),this.addBufferListener(h,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(h,"bufferedchange",(u,d)=>{const f=d.removedRanges;null!=f&&f.length&&this.hls.trigger(p.BUFFER_FLUSHED,{type:r})}),this.tracks[r]={buffer:c,codec:o,container:a.container,levelCodec:a.levelCodec,metadata:a.metadata,id:a.id}}catch(c){this.error(`error while trying to add sourceBuffer: ${c.message}`),this.hls.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,sourceBufferName:r,mimeType:l})}}}get mediaSrc(){var e,t;const s=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return s?.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if("closed"===(null==(t=this.mediaSource)?void 0:t.readyState))return void this.resetBuffer(e);const{operationQueue:s}=this;s.current(e).onComplete(),s.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(s=this.mediaSource)?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.operationQueue.current(e);r&&r.onError(i)}removeExecutor(e,t,s){const{media:i,mediaSource:r,operationQueue:a,sourceBuffer:o}=this,l=o[e];if(!i||!r||!l)return this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),void a.shiftAndExecuteNext(e);const c=F(i.duration)?i.duration:1/0,h=F(r.duration)?r.duration:1/0,u=Math.max(0,t),d=Math.min(s,c,h);d>u&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${u},${d}] from the ${e} SourceBuffer`),l.remove(u,d)):a.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.sourceBuffer[t];if(s)s.ended=!1,s.appendBuffer(e);else if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map(r=>s.appendBlocker(r));Promise.all(i).then(()=>{e(),t.forEach(r=>{const a=this.sourceBuffer[r];null!=a&&a.updating||s.shiftAndExecuteNext(r)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,s){const i=this.sourceBuffer[e];if(!i)return;const r=s.bind(this,e);this.listeners[e].push({event:t,listener:r}),i.addEventListener(t,r)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(s=>{t.removeEventListener(s.event,s.listener)})}},capLevelController:Ps,errorController:class Sa{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=v.log.bind(v,"[info]:"),this.warn=v.warn.bind(v,"[warning]:"),this.error=v.error.bind(v,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.ERROR,this.onError,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.ERROR,this.onError,this),e.off(p.ERROR,this.onErrorOut,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return"main"===e?.type?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var s,i;if(t.fatal)return;const r=this.hls,a=t.context;switch(t.details){case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case A.FRAG_PARSING_ERROR:if(null!=(s=t.frag)&&s.gap)return void(t.errorAction={action:0,flags:0});case A.FRAG_GAP:case A.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=2);case A.LEVEL_EMPTY_ERROR:case A.LEVEL_PARSING_ERROR:{var o,l;const c="main"===t.parent?t.level:r.loadLevel;t.details===A.LEVEL_EMPTY_ERROR&&null!=(o=t.context)&&null!=(l=o.levelDetails)&&l.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case A.LEVEL_LOAD_ERROR:case A.LEVEL_LOAD_TIMEOUT:return void("number"==typeof a?.level&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.level)));case A.AUDIO_TRACK_LOAD_ERROR:case A.AUDIO_TRACK_LOAD_TIMEOUT:case A.SUBTITLE_LOAD_ERROR:case A.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const c=r.levels[r.loadLevel];if(c&&("audioTrack"===a.type&&c.hasAudioGroup(a.groupId)||"subtitleTrack"===a.type&&c.hasSubtitleGroup(a.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=2,void(t.errorAction.flags=1)}return;case A.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const c=r.levels[r.loadLevel],h=c?.attrs["HDCP-LEVEL"];h?t.errorAction={action:2,flags:2,hdcpLevel:h}:this.keySystemError(t)}return;case A.BUFFER_ADD_CODEC_ERROR:case A.REMUX_ALLOC_ERROR:case A.BUFFER_APPEND_ERROR:return void(t.errorAction=this.getLevelSwitchAction(t,null!=(i=t.level)?i:r.loadLevel));case A.INTERNAL_EXCEPTION:case A.BUFFER_APPENDING_ERROR:case A.BUFFER_FULL_ERROR:case A.LEVEL_SWITCH_ERROR:case A.BUFFER_STALLED_ERROR:case A.BUFFER_SEEK_OVER_HOLE:case A.BUFFER_NUDGE_ON_STALL:return void(t.errorAction={action:0,flags:0})}t.type===B.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const i=ki(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(Et(i,r,yt(e),e.response))return{action:5,flags:0,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=ki(e.details.startsWith("key")?a:r,e),l=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(e.details!==A.FRAG_GAP&&i.fragmentError++,Et(o,l,yt(e),e.response)))return{action:5,flags:0,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(e,s);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){const s=this.hls;null==t&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,a;const c=e.details;i.loadError++,c===A.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:f,maxAutoLevel:m}=s;s.autoLevelEnabled||(s.loadLevel=-1);const g=null==(r=e.frag)?void 0:r.type,E=("audio"===g&&c===A.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(c===A.BUFFER_ADD_CODEC_ERROR||c===A.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:b})=>i.audioCodec!==b),x="video"===e.sourceBufferName&&(c===A.BUFFER_ADD_CODEC_ERROR||c===A.BUFFER_APPEND_ERROR)&&u.some(({codecSet:b,audioCodec:L})=>i.codecSet!==b&&i.audioCodec===L),{type:R,groupId:S}=null!=(a=e.context)?a:{};for(let b=u.length;b--;){const L=(b+d)%u.length;if(L!==d&&L>=f&&L<=m&&0===u[L].loadError){var o,l;const C=u[L];if(c===A.FRAG_GAP&&"main"===g&&e.frag){const w=u[L].details;if(w){const I=Tt(e.frag,w.fragments,e.frag.start);if(null!=I&&I.gap)continue}}else{if("audioTrack"===R&&C.hasAudioGroup(S)||"subtitleTrack"===R&&C.hasSubtitleGroup(S))continue;if("audio"===g&&null!=(o=i.audioGroups)&&o.some(w=>C.hasAudioGroup(w))||"subtitle"===g&&null!=(l=i.subtitleGroups)&&l.some(w=>C.hasSubtitleGroup(w))||E&&i.audioCodec===C.audioCodec||!E&&i.audioCodec!==C.audioCodec||x&&i.codecSet===C.codecSet)continue}h=L;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:h}}return{action:2,flags:1}}onErrorOut(e,t){var s;switch(null==(s=t.errorAction)?void 0:s.action){case 0:break;case 2:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===A.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}t.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i,hdcpLevel:r,nextAutoLevel:a}=s;switch(i){case 0:this.switchLevel(e,a);break;case 2:r&&(t.maxHdcpLevel=is[is.indexOf(r)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)}s.resolved||this.switchLevel(e,a)}switchLevel(e,t){void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}},fpsController:class fl{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}registerListeners(){this.hls.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/(i-this.lastTime),c=this.hls;if(c.trigger(p.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let h=c.currentLevel;v.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(-1===c.autoLevelCapping||c.autoLevelCapping>=h)&&(h-=1,c.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:c.currentLevel}),c.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Ys,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},function hc(){return{cueHandler:lc,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}()),{},{subtitleStreamController:class Oo extends us{constructor(e,t,s){super(e,t,s,"[subtitle-stream-controller]","subtitle"),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.ERROR,this.onError,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.ERROR,this.onError,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state="IDLE",this.setInterval(500),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(this.fragPrevious=s,this.state="IDLE",!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a;const o=s.start;for(let c=0;c<r.length;c++)if(o>=r[c].start&&o<=r[c].end){a=r[c];break}const l=s.start+s.duration;a?a.end=l:(a={start:o,end:l},r.push(a)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null)}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(0===s&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;)if(a[o].end<=r)a.shift();else{if(!(a[o].start<r))break;a[o].start=r,o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,"subtitle")}}onFragBuffered(e,t){var s;this.loadedmetadata||"main"!==t.frag.type||null!=(s=this.media)&&s.buffered.length&&(this.loadedmetadata=!0)}onError(e,t){const s=t.frag;"subtitle"===s?.type&&(t.details===A.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),"STOPPED"!==this.state&&(this.state="IDLE"))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){this.levels&&gr(this.levels,t)?this.levels=t.map(s=>new Ge(s)):(this.tracksBuffered=[],this.levels=t.map(s=>{const i=new Ge(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,"subtitle"),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,null==(s=this.levels)||!s.length||-1===this.currentTrackId)return void this.clearInterval();const i=this.levels[this.currentTrackId];this.mediaBuffer=null!=i&&i.details?this.mediaBufferTimeRanges:null,i&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:a,id:o}=t;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${o}`);const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||null!=(s=l.details)&&s.live){const u=this.mainDetails;if(a.deltaUpdateFailed||!u)return;const d=u.fragments[0];var h;l.details?(c=this.alignPlaylists(a,l.details,null==(h=this.levelLastLoaded)?void 0:h.details),0===c&&d&&(c=d.start,ns(a,c))):a.hasProgramDateTime&&u.hasProgramDateTime?(At(a,u),c=a.fragments[0].start):d&&(c=d.start,ns(a,c))}l.details=a,this.levelLastLoaded=l,o===i&&(!this.startFragRequested&&(this.mainDetails||!a.live)&&this.setStartPosition(this.mainDetails||a,c),this.tick(),a.live&&!this.fragCurrent&&this.media&&"IDLE"===this.state&&(Tt(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&null!=i&&i.key&&i.iv&&"AES-128"===i.method){const a=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer).catch(o=>{throw r.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();r.trigger(p.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state="IDLE"})}}doTick(){if(this.media){if("IDLE"===this.state){const{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details)return;const{config:i}=this,r=this.getLoadPosition(),a=Z.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:l}=a,c=this.getFwdBufferInfo(this.media,"main"),h=s.details;if(l>this.getMaxBufferLength(c?.len)+h.levelTargetDuration)return;const d=h.fragments,f=d.length,m=h.edge;let g=null;const y=this.fragPrevious;if(o<m){const E=i.maxFragLookUpTolerance,T=o>m-E?0:E;g=Tt(y,d,Math.max(d[0].start,o),T),!g&&y&&y.start<d[0].start&&(g=d[0])}else g=d[f-1];if(!g)return;if(g=this.mapToInitFragWhenRequired(g),"initSegment"!==g.sn){const T=d[g.sn-h.startSN-1];T&&T.cc===g.cc&&"NOT_LOADED"===this.fragmentTracker.getState(T)&&(g=T)}"NOT_LOADED"===this.fragmentTracker.getState(g)&&this.loadFragment(g,s,o)}}else this.state="IDLE"}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,s){this.fragCurrent=e,"initSegment"===e.sn?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,s))}get mediaBufferTimeRanges(){return new Mo(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class No extends ls{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=ft(this.media.textTracks);for(let r=0;r<s.length;r++)if("hidden"===s[r].mode)t=s[r];else if("showing"===s[r].mode){t=s[r];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.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.onTextTracksChanged,e)}onMediaDetaching(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),ft(this.media.textTracks).forEach(t=>{$e(t)}),this.subtitleTrack=-1,this.media=null)}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i)return void this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${a?.groupId}`);const o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||null!=s&&s.some(a=>-1===i?.indexOf(a))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!s||-1!==s.indexOf(h.groupId));if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=Le(o,a);if(h>-1)r=a[h];else{const u=Le(o,this.tracks);r=this.tracks[u]}}let l=this.findTrackId(r);-1===l&&r&&(l=this.findTrackId(null));const c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,c),-1!==l&&-1===this.trackId&&this.setSubtitleTrack(l)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if((!s||r.default)&&(s||e)&&(!e||Me(r,e)))return i}if(e){for(let i=0;i<t.length;i++)if(et(e.attrs,t[i].attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i;for(let i=0;i<t.length;i++)if(et(e.attrs,t[i].attrs,["LANGUAGE"]))return i}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++)if(vs(t[s],e))return s}return-1}onError(e,t){t.fatal||!t.context||"subtitleTrack"===t.context.type&&t.context.id===this.trackId&&(!this.groupIds||-1!==this.groupIds.indexOf(t.context.groupId))&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&Me(e,s))return s;const i=Le(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}if(s)return null;{const r=Le(e,t);if(r>-1)return t[r]}}}return null}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){const s=t.id,i=t.groupId;let r=t.url;if(e)try{r=e.addDirectives(r)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`Loading subtitle playlist for id ${s}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=ft(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>vs(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{"disabled"!==r.mode&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media)return void(this.queuedDefaultTrack=e);if(e<-1||e>=t.length||!F(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i)return void this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:e});if(e===this.trackId&&i===s&&i.details&&!i.details.live)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:a,groupId:o="",name:l,type:c,url:h}=i;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:c,url:h});const u=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(u)}},timelineController:class ul{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=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}},e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new wt(this,"textTrack1"),t=new wt(this,"textTrack2"),s=new wt(this,"textTrack3"),i=new wt(this,"textTrack4");this.cea608Parser1=new vr(1,e,t),this.cea608Parser2=new vr(3,s,i)}}addCues(e,t,s,i,r){let a=!1;for(let o=r.length;o--;){const l=r[o],c=dl(l[0],l[1],t,s);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],s),a=!0,c/(s-t)>.5))return}if(a||r.push([t,s]),this.config.renderTextTracksNatively)this.Cues.newCue(this.captionsTracks[e],t,s,i);else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r}){const{unparsedVttFrags:a}=this;"main"===s&&(this.initPTS[t.cc]={baseTime:i,timescale:r}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(p.FRAG_LOADED,o)}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Pr(r,{name:e,lang:t,attrs:{}}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:a}=t[e],o=this.getExistingTrack(r,a);if(o)s[e]=o,$e(s[e]),Si(s[e],i);else{const l=this.createTextTrack("captions",r,a);l&&(l[e]=!0,s[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach(t=>{$e(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)$e(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===Ds);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(gr(this.tracks,s))return void(this.tracks=s);if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const a=this.media,o=a?ft(a.textTracks):null;if(this.tracks.forEach((l,c)=>{let h;if(o){let u=null;for(let d=0;d<o.length;d++)if(o[d]&&Pr(o[d],l)){u=o[d],o[d]=null;break}u&&(h=u)}if(h)$e(h);else{const u=wr(l);h=this.createTextTrack(u,l.name,l.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),null!=o&&o.length){const l=o.filter(c=>null!==c).map(c=>c.label);l.length&&v.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const a=this.captionsProperties[`textTrack${i[1]}`];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&"main"===t.frag.type){var s,i;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=t.frag,h=null!=(s=null==(i=t.part)?void 0:i.index)?s:-1;r&&a&&(c!==o+1||c===o&&h!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if("subtitle"===s.type)if(i.byteLength){const r=s.decryptdata;if(null==r||!r.encrypted||"stats"in t){const o=this.tracks[s.level],l=this.vttCCs;l[s.cc]||(l[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Ds?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;br(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{v.log(`Failed to parse IMSC1: ${i}`),s.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:a}=this,o=r.length-1;if(!r[s.cc]&&-1===o)return void a.push(e);const l=this.hls;!function nl(n,e,t,s,i,r,a){const o=new tl,l=xe(new Uint8Array(n)).trim().replace(sl,"\n").split("\n"),c=[],h=e?function So(n,e=1){return ys(n,9e4,1/e)}(e.baseTime,e.timescale):0;let m,u="00:00.000",d=0,f=0,g=!0;o.oncue=function(y){const E=t[s];let T=t.ccOffset;const x=(d-h)/9e4;if(null!=E&&E.new&&(void 0!==f?T=t.ccOffset=E.start:function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;null!=(a=r)&&a.new;){var a;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s}(t,s,x)),x){if(!e)return void(m=new Error("Missing initPTS for VTT MPEGTS"));T=x-t.presentationOffset}const R=y.endTime-y.startTime,S=ge(9e4*(y.startTime+T-f),9e4*i)/9e4;y.startTime=Math.max(S,0),y.endTime=Math.max(S+R,0);const b=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(b)),y.id||(y.id=bs(y.startTime,y.endTime,b)),y.endTime>0&&c.push(y)},o.onparsingerror=function(y){m=y},o.onflush=function(){m?a(m):r(c)},l.forEach(y=>{if(g){if(Rs(y,"X-TIMESTAMP-MAP=")){g=!1,y.slice(16).split(",").forEach(E=>{Rs(E,"LOCAL:")?u=E.slice(6):Rs(E,"MPEGTS:")&&(d=parseInt(E.slice(7)))});try{f=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(F(t)&&F(s)&&F(i)&&F(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=6e4*i,t+=36e5*r,t}(u)/1e3}catch(E){m=E}return}""===y&&(g=!1)}o.parse(y+"\n")}),o.flush()}(null!=(t=s.initSegment)&&t.data?fe(s.initSegment.data,new Uint8Array(i)):i,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),l.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},h=>{const u="Missing initPTS for VTT MPEGTS"===h.message;u?a.push(e):this._fallbackToIMSC1(s,i),v.log(`Failed to parse VTT cue: ${h}`),!(u&&o>s.cc)&&l.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:h})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||br(t,this.initPTS[e.cc],()=>{s.textCodec=Ds,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||"disabled"===i.mode)return;e.forEach(r=>Ai(i,r))}else{const i=this.tracks[t];if(!i)return;s.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:i.default?"default":"subtitles"+t})}}onFragDecrypted(e,t){const{frag:s}=t;"subtitle"===s.type&&this.onFragLoaded(p.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:i}=this;if(!this.enabled||!s||!i)return;const{frag:r,samples:a}=t;if("main"!==r.type||"NONE"!==this.closedCaptionsForLevel(r))for(let o=0;o<a.length;o++){const l=a[o].bytes;if(l){const c=this.extractCea608Data(l);s.addData(a[o].pts,c[0]),i.addData(a[o].pts,c[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:a}=this;if(a&&!(a.currentTime<s)){if(!r||"video"===r){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>es(o[l],t,s))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==i){const{textTracks:o}=this;Object.keys(o).forEach(l=>es(o[l],t,i))}}}extractCea608Data(e){const t=[[],[]],s=31&e[0];let i=2;for(let r=0;r<s;r++){const a=e[i++],o=127&e[i++],l=127&e[i++];if((0!==o||0!==l)&&0!=(4&a)){const h=3&a;(0===h||1===h)&&(t[h].push(o),t[h].push(l))}}return t}},audioStreamController:class ko extends us{constructor(e,t,s){super(e,t,s,"[audio-stream-controller]","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.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r}){if("main"===s){const a=t.cc;this.initPTS[t.cc]={baseTime:i,timescale:r},this.log(`InitPTS for cc: ${a} found from main: ${i}`),this.videoTrackCC=a,"WAITING_INIT_PTS"===this.state&&this.tick()}}startLoad(e){if(!this.levels)return this.startPosition=e,void(this.state="STOPPED");const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),t>0&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state="IDLE"):(this.loadedmetadata=!1,this.state="WAITING_TRACK"),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case"IDLE":this.doTickIdle();break;case"WAITING_TRACK":{var e;const{levels:s,trackId:i}=this,r=null==s||null==(e=s[i])?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state="WAITING_INIT_PTS"}break}case"FRAG_LOADING_WAITING_RETRY":{var t;const s=performance.now(),i=this.retryDate;if(!i||s>=i||null!=(t=this.media)&&t.seeking){const{levels:r,trackId:a}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(r?.[a]||null),this.state="IDLE"}break}case"WAITING_INIT_PTS":{const s=this.waitingData;if(s){const{frag:i,part:r,cache:a,complete:o}=s;if(void 0!==this.initPTS[i.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state="FRAG_LOADING";const c={frag:i,part:r,payload:a.flush(),networkDetails:null};this._handleFragmentLoadProgress(c),o&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),c=Z.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);os(c.end,this.config.maxFragLookUpTolerance,i)<0&&(this.log(`Waiting fragment cc (${i.cc}) @ ${i.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state="IDLE"}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state="IDLE")}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:s,trackId:i}=this;if(!this.buffering||!s&&(this.startFragRequested||!e.config.startFragPrefetch)||null==t||!t[i])return;const a=t[i],o=a.details;if(!o||o.live&&this.levelLastLoaded!==a||this.waitForCdnTuneIn(o))return void(this.state="WAITING_TRACK");const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,"audio","audio"));const c=this.getFwdBufferInfo(l,"audio");if(null===c)return;if(!this.switchingTrack&&this._streamEnded(c,o))return e.trigger(p.BUFFER_EOS,{type:"audio"}),void(this.state="ENDED");const h=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,"main"),u=c.len,d=this.getMaxBufferLength(h?.len),f=o.fragments,m=f[0].start,g=this.getLoadPosition(),y=this.flushing?g:c.end;if(this.switchingTrack&&s&&o.PTSKnown&&g<m&&(c.end>m||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=m+.05),u>=d&&!this.switchingTrack&&y<f[f.length-1].start)return;let E=this.getNextFragment(y,o),T=!1;if(E&&this.isLoopLoading(E,y)&&(T=!!E.gap,E=this.getNextFragmentLoopLoading(E,o,c,"main",d)),!E)return void(this.bufferFlushed=!0);const x=h&&E.start>h.end+o.targetduration;if(x||(null==h||!h.len)&&c.len){const R=this.getAppendedFrag(E.start,"main");if(null===R||(T||(T=!!R.gap||!!x&&0===h.len),x&&!T||T&&c.nextStart&&c.nextStart<R.end))return}this.loadFragment(E,a,y)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Ge(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?this.setInterval(100):this.resetTransmuxer(),s?(this.switchingTrack=t,this.state="IDLE",this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state="STOPPED"),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,null!==this.cachedTrackLoadedData&&(this.hls.trigger(p.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var s;if(null==this.mainDetails)return void(this.cachedTrackLoadedData=t);const{levels:i}=this,{details:r,id:a}=t;if(!i)return void this.warn(`Audio tracks were reset while loading level ${a}`);this.log(`Audio track ${a} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const o=i[a];let l=0;if(r.live||null!=(s=o.details)&&s.live){this.checkLiveUpdate(r);const h=this.mainDetails;if(r.deltaUpdateFailed||!h)return;var c;!o.details&&r.hasProgramDateTime&&h.hasProgramDateTime?(At(r,h),l=r.fragments[0].start):l=this.alignPlaylists(r,o.details,null==(c=this.levelLastLoaded)?void 0:c.details)}o.details=r,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!r.live)&&this.setStartPosition(this.mainDetails||r,l),"WAITING_TRACK"===this.state&&!this.waitForCdnTuneIn(r)&&(this.state="IDLE"),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:s,part:i,payload:r}=e,{config:a,trackId:o,levels:l}=this;if(!l)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const c=l[o];if(!c)return void this.warn("Audio track is undefined on fragment load progress");const h=c.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(s.start);const u=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new dr(this.hls,"audio",this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[s.cc],m=null==(t=s.initSegment)?void 0:t.data;if(void 0!==f){const y=i?i.index:-1,T=new cs(s.level,s.sn,s.stats.chunkCount,r.byteLength,y,-1!==y);d.push(r,m,u,"",s,i,h.totalduration,!1,T,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:g}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new Hi,complete:!1};g.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state="WAITING_INIT_PTS"}}_handleFragmentLoadComplete(e){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:s,part:i}=t;if("audio"===s.type)if(this.fragContextChanged(s))this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if("initSegment"!==s.sn){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(p.AUDIO_TRACK_SWITCHED,re({},r)))}this.fragBufferedComplete(s,i)}else if(!this.loadedmetadata&&"main"===s.type){const r=this.videoBuffer||this.media;r&&Z.getBuffered(r).length&&(this.loadedmetadata=!0)}}onError(e,t){var s;if(t.fatal)this.state="ERROR";else switch(t.details){case A.FRAG_GAP:case A.FRAG_PARSING_ERROR:case A.FRAG_DECRYPT_ERROR:case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError("audio",t);break;case A.AUDIO_TRACK_LOAD_ERROR:case A.AUDIO_TRACK_LOAD_TIMEOUT:case A.LEVEL_PARSING_ERROR:!t.levelRetry&&"WAITING_TRACK"===this.state&&"audioTrack"===(null==(s=t.context)?void 0:s.type)&&(this.state="IDLE");break;case A.BUFFER_APPEND_ERROR:case A.BUFFER_FULL_ERROR:if(!t.parent||"audio"!==t.parent)return;if(t.details===A.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case A.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){"video"!==t&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if("video"!==t){this.flushing=!1,this.bufferFlushed=!0,"ENDED"===this.state&&(this.state="IDLE");const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,"audio"),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o)return void this.resetWhenMissingContext(a);const{frag:l,part:c,level:h}=o,{details:u}=h,{audio:d,text:f,id3:m,initSegment:g}=r;if(!this.fragContextChanged(l)&&u){if(this.state="PARSING",this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),null!=g&&g.tracks){const y=l.initSegment||l;this._bufferInitSegment(h,g.tracks,y,a),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:g.tracks})}if(d){const{startPTS:y,endPTS:E,startDTS:T,endDTS:x}=d;c&&(c.elementaryStreams.audio={startPTS:y,endPTS:E,startDTS:T,endDTS:x}),l.setElementaryStreamInfo("audio",y,E,T,x),this.bufferFragmentData(d,l,c,a)}if(null!=m&&null!=(t=m.samples)&&t.length){const y=te({id:s,frag:l,details:u},m);i.trigger(p.FRAG_PARSING_METADATA,y)}if(f){const y=te({id:s,frag:l,details:u},f);i.trigger(p.FRAG_PARSING_USERDATA,y)}}else this.fragmentTracker.removeFragment(l)}_bufferInitSegment(e,t,s,i){if("PARSING"!==this.state)return;t.video&&delete t.video;const r=t.audio;if(!r)return;r.id="audio";const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&1===a.split(",").length&&(r.levelCodec=a),this.hls.trigger(p.BUFFER_CODECS,t);const o=r.initSegment;null!=o&&o.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o}),this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);var r;if(this.fragCurrent=e,this.switchingTrack||"NOT_LOADED"===i||"PARTIAL"===i)if("initSegment"===e.sn)this._loadInitSegment(e,t);else if(null!=(r=t.details)&&r.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="WAITING_INIT_PTS";const a=this.mainDetails;a&&a.fragments[0].start!==t.details.fragments[0].start&&At(t.details,a)}else this.startFragRequested=!0,super.loadFragment(e,t,s);else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o}=this.bufferedTrack;Me({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o},e,Ne)||(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(p.AUDIO_TRACK_SWITCHED,re({},e))}},audioTrackController:class Fo extends ls{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i)return void this.warn(`Audio track with id:${s} and group:${i} not found in active group ${a?.groupId}`);const o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||null!=s&&s.some(o=>-1===i?.indexOf(o))){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!s||-1!==s.indexOf(d.groupId));if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,f)=>{d.id=f});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!r&&l){const d=Le(l,o,Ne);if(d>-1)r=o[d];else{const f=Le(l,this.tracks);r=this.tracks[f]}}let c=this.findTrackId(r);-1===c&&r&&(c=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(p.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(-1!==c&&-1===u)this.setAudioTrack(c);else if(o.length&&-1===u){var a;const d=new Error(`No audio track selected for current audio group-ID(s): ${null==(a=this.groupIds)?void 0:a.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}else this.shouldReloadPlaylist(r)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||"audioTrack"===t.context.type&&t.context.id===this.trackId&&(!this.groupIds||-1!==this.groupIds.indexOf(t.context.groupId))&&(this.requestScheduled=-1,this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&Me(e,i,Ne))return i;const r=Le(e,this.tracksInGroup,Ne);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r),a}if(i){let a=t.loadLevel;-1===a&&(a=t.firstAutoLevel);const o=function ka(n,e,t,s,i){const r=e[s],o=e.reduce((d,f,m)=>{const g=f.uri;return(d[g]||(d[g]=[])).push(m),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const l=r.videoRange,c=r.frameRate,h=r.codecSet.substring(0,4),u=Ui(e,s,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==h)return!1;const f=d.audioGroups,m=t.filter(g=>!f||-1!==f.indexOf(g.groupId));return Le(n,m,i)>-1});return u>-1?u:Ui(e,s,d=>{const f=d.audioGroups,m=t.filter(g=>!f||-1!==f.indexOf(g.groupId));return Le(n,m,i)>-1})}(e,t.levels,s,a,Ne);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Le(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,re({},i)),r))return;const a=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if((!this.selectDefaultTrack||i.default)&&(!e||Me(e,i,Ne)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++)if(Me({name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:l},t[c],Ne))return c;for(let c=0;c<t.length;c++)if(et(e.attrs,t[c].attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c;for(let c=0;c<t.length;c++)if(et(e.attrs,t[c].attrs,["LANGUAGE"]))return c}return-1}loadPlaylist(e){const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){super.loadPlaylist();const s=t.id,i=t.groupId;let r=t.url;if(e)try{r=e.addDirectives(r)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`loading audio-track playlist ${s} "${t.name}" lang:${t.lang} group:${i}`),this.clearTimer(),this.hls.trigger(p.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null})}}},emeController:gl,cmcdController:class Xl{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:he.MANIFEST,su:!this.initialized})}catch(r){v.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const r=i.frag,a=this.hls.levels[r.level],o=this.getObjectType(r),l={d:1e3*r.duration,ot:o};(o===he.VIDEO||o===he.AUDIO||o==he.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(i,l)}catch(r){v.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;null!=s&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||function Gl(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const r=(t+16*Math.random())%16|0;return t=Math.floor(t/16),("x"==i?r:3&r|8).toString(16)})}}}(),this.cid=s.contentId,this.useHeaders=!0===s.useHeaders,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=null==(s=t.tracks.audio)?void 0:s.buffer,this.videoBuffer=null==(i=t.tracks.video)?void 0:i.buffer}createData(){var e;return{v:1,sf:Fr.HLS,sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){te(t,this.createData()),this.starved&&(t.ot===he.INIT||t.ot===he.VIDEO||t.ot===he.MUXED)&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((r,a)=>(i.includes(a)&&(r[a]=t[a]),r),{})),this.useHeaders?(e.headers||(e.headers={}),function Yl(n,e,t){return te(n,function Wl(n,e={}){if(!n)return{};const t=Object.entries(n),s=Object.entries(ml).concat(Object.entries(e?.customHeaderMap||{})),i=t.reduce((r,a)=>{var o;const[c,h]=a,u=(null==(o=s.find(d=>d[1].includes(c)))?void 0:o[0])||qe.REQUEST;return null!=r[u]||(r[u]={}),r[u][c]=h,r},{});return Object.entries(i).reduce((r,[a,o])=>(r[a]=Gr(o,e),r),{})}(e,t))}(e.headers,t)):e.url=function zl(n,e,t){const s=function jl(n,e={}){if(!n)return"";const t=Gr(n,e);return`CMCD=${encodeURIComponent(t)}`}(e,t);if(!s)return n;if(Kr.test(n))return n.replace(Kr,s);const i=n.includes("?")?"&":"?";return`${n}${i}${s}`}(e.url,t)}getObjectType(e){const{type:t}=e;return"subtitle"===t?he.TIMED_TEXT:"initSegment"===e.sn?he.INIT:"audio"===t?he.AUDIO:"main"===t?this.hls.audioTracks.length?he.VIDEO:he.MUXED:void 0}getTopBandwidth(e){let s,t=0;const i=this.hls;if(e===he.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel;s=i.levels.slice(0,r>-1?r+1:i.levels.length)}for(const r of s)r.bitrate>t&&(t=r.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,s=e===he.AUDIO?this.audioBuffer:this.videoBuffer;return s&&t?1e3*Z.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len:NaN}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}},contentSteeringController:class Jl{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=v.log.bind(v,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==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){const{contentSteering:s}=t;null!==s&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if(2===s?.action&&1===s.flags){const i=this.levels;let r=this.pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&i?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&i&&(r=i.reduce((o,l)=>(-1===o.indexOf(l.pathwayId)&&o.push(l.pathwayId),o),[])),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==a),s.resolved||v.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this.pathwayPriority=e;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>3e5&&delete s[r]});for(let r=0;r<e.length;r++){const a=e[r];if(a in s)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Pi(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if("audioTrack"===t&&i[r].hasAudioGroup(e)||"subtitleTrack"===t&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(h=>h.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(h=>{const u=new ee(h.attrs);u["PATHWAY-ID"]=a;const d=u.AUDIO&&`${u.AUDIO}_clone_${a}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),f&&(i[u.SUBTITLES]=f,u.SUBTITLES=f);const m=Hr(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new Ge({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:m,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let y=1;y<h.audioGroups.length;y++)g.addGroupId("audio",`${h.audioGroups[y]}_clone_${a}`);if(h.subtitleGroups)for(let y=1;y<h.subtitleGroups.length;y++)g.addGroupId("text",`${h.subtitleGroups[y]}_clone_${a}`);return g});t.push(...c),Vr(this.audioTracks,s,l,a),Vr(this.subtitleTracks,i,l,a)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;let i;this.loader&&this.loader.destroy(),this.loader=new s(t);try{i=new self.URL(e)}catch{return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${e}`)}if("data:"!==i.protocol){const h=0|(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate);i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(h,u,d,f)=>{this.log(`Loaded steering manifest: "${i}"`);const m=h.data;if(1!==m.VERSION)return void this.log(`Steering VERSION ${m.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=m.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":E}=m;if(g)try{this.uri=new self.URL(g,i).href}catch{return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`)}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const T={steeringManifest:m,url:i.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,T),E&&this.updatePathwayPriority(E)},onError:(h,u,d,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),410===h.code)return this.enabled=!1,void this.log(`Steering manifest ${u.url} no longer available`);let m=1e3*this.timeToLoad;if(429!==h.code)this.scheduleRefresh(this.uri||u.url,m);else{const g=this.loader;if("function"==typeof g?.getResponseHeader){const y=g.getResponseHeader("Retry-After");y&&(m=1e3*parseFloat(y))}this.log(`Steering manifest ${u.url} rate limited`)}},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,l,c)}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=null==(s=this.hls)?void 0:s.media;!i||i.ended?this.scheduleRefresh(e,1e3*this.timeToLoad):this.loadSteeringManifest(e)},t)}}});function Ms(n){return n&&"object"==typeof n?Array.isArray(n)?n.map(Ms):Object.keys(n).reduce((e,t)=>(e[t]=Ms(n[t]),e),{}):n}let Ns;class fc extends ls{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},a={};let o=!1,l=!1,c=!1;t.levels.forEach(h=>{var u,d;const f=h.attrs;let{audioCodec:m,videoCodec:g}=h;-1!==(null==(u=m)?void 0:u.indexOf("mp4a.40.34"))&&(Ns||(Ns=/chrome|firefox/i.test(navigator.userAgent)),Ns&&(h.audioCodec=m=void 0)),m&&(h.audioCodec=m=dt(m,s)),0===(null==(d=g)?void 0:d.indexOf("avc1"))&&(g=h.videoCodec=function Qn(n){const e=n.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");if(s.length>2){let i=s.shift()+".";i+=parseInt(s.shift()).toString(16),i+=("000"+parseInt(s.shift()).toString(16)).slice(-4),e[t]=i}}return e.join(",")}(g));const{width:y,height:E,unknownCodecs:T}=h;if(o||(o=!(!y||!E)),l||(l=!!g),c||(c=!!m),null!=T&&T.length||m&&!Qt(m,"audio",s)||g&&!Qt(g,"video",s))return;const{CODECS:x,"FRAME-RATE":R,"HDCP-LEVEL":S,"PATHWAY-ID":b,RESOLUTION:L,"VIDEO-RANGE":C}=f,I=`${b||"."}-${h.bitrate}-${L}-${R}-${x}-${C}-${S}`;if(r[I])if(r[I].uri===h.url||h.attrs["PATHWAY-ID"])r[I].addGroupId("audio",f.AUDIO),r[I].addGroupId("text",f.SUBTITLES);else{const _=a[I]+=1;h.attrs["PATHWAY-ID"]=new Array(_+1).join(".");const V=new Ge(h);r[I]=V,i.push(V)}else{const _=new Ge(h);r[I]=_,a[I]=1,i.push(_)}}),this.filterAndSortMediaOptions(i,t,o,l,c)}filterAndSortMediaOptions(e,t,s,i,r){let a=[],o=[],l=e;if((s||i)&&r&&(l=l.filter(({videoCodec:m,videoRange:g,width:y,height:E})=>(!!m||!(!y||!E))&&function ha(n){return!!n&&mt.indexOf(n)>-1}(g))),0===l.length)return void Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const m=new Error("no level with compatible codecs found in manifest");this.hls.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:m,reason:m.message})}});if(t.audioTracks){const{preferManagedMediaSource:m}=this.hls.config;a=t.audioTracks.filter(g=>!g.audioCodec||Qt(g.audioCodec,"audio",m)),jr(a)}t.subtitles&&(o=t.subtitles,jr(o));const c=l.slice(0);l.sort((m,g)=>{if(m.attrs["HDCP-LEVEL"]!==g.attrs["HDCP-LEVEL"])return(m.attrs["HDCP-LEVEL"]||"")>(g.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&m.height!==g.height)return m.height-g.height;if(m.frameRate!==g.frameRate)return m.frameRate-g.frameRate;if(m.videoRange!==g.videoRange)return mt.indexOf(m.videoRange)-mt.indexOf(g.videoRange);if(m.videoCodec!==g.videoCodec){const y=hi(m.videoCodec),E=hi(g.videoCodec);if(y!==E)return E-y}if(m.uri===g.uri&&m.codecSet!==g.codecSet){const y=ut(m.codecSet),E=ut(g.codecSet);if(y!==E)return E-y}return m.averageBitrate!==g.averageBitrate?m.averageBitrate-g.averageBitrate:0});let h=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length))for(let m=0;m<c.length;m++)if(c[m].pathwayId===l[0].pathwayId){h=c[m];break}this._levels=l;for(let m=0;m<l.length;m++)if(l[m]===h){var u;this._firstLevel=m;const g=h.bitrate,y=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${g}`),void 0===(null==(u=this.hls.userConfig)?void 0:u.abrEwmaDefaultEstimate)){const E=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);E>y&&y===qr.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=E)}break}const f={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:!(r&&!i)&&a.some(m=>!!m.url)};this.hls.trigger(p.MANIFEST_PARSED,f),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return 0===this._levels.length?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(p.ERROR,{type:B.OTHER_ERROR,details:A.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&a.details&&i&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`),this.hls.trigger(p.LEVEL_SWITCHING,{level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds});const c=a.details;if(!c||c.live){const h=this.switchParams(a.uri,i?.details,c);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){const e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||"level"===t.context.type&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&"main"===t.type){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,a=this._levels[i];var o;if(!a)return this.warn(`Invalid level index ${i}`),void(null!=(o=t.deliveryDirectives)&&o.skip&&(r.deltaUpdateFailed=!0));i===this.currentLevelIndex?(0===a.fragmentError&&(a.loadError=0),this.playlistLoaded(i,t,a.details)):null!=(s=t.deliveryDirectives)&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){let i=s.uri;if(e)try{i=e.addDirectives(i)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const r=s.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${void 0!==e?.msn?" at sn "+e.msn+" part "+e.part:""} with${r?" Pathway "+r:""} ${i}`),this.clearTimer(),this.hls.trigger(p.LEVEL_LOADING,{url:i,level:t,pathwayId:s.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const s=this._levels.filter((i,r)=>r!==e||(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(a=>a.level=-1)),!1));Pi(s),this._levels=s,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(p.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function jr(n){const e={};n.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}class gc{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[s].loader;if(i){var t;if(e&&e!==(null==(t=i.context)?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=A.KEY_LOAD_ERROR,s,i,r){return new De({type:B.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:i}=e;for(let r=0;r<t.length;r++){const a=t[r];if(i<=a.cc&&("initSegment"===s||"initSegment"===a.sn||s<a.sn)){this.emeController.selectKeySystemFormat(a).then(o=>{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const c=new 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,A.KEY_LOAD_ERROR,c))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,A.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if(null!=(s=o)&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});var l;if(null!=(i=o)&&i.keyLoadPromise)switch(null==(l=o.mediaKeySessionContext)?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(r.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}switch(o=this.keyUriToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===r.keyFormat?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,A.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const i=this.emeController.loadKey(s);if(i)return(e.keyLoadPromise=i.then(r=>(e.mediaKeySessionContext=r,s))).catch(r=>{throw e.keyLoadPromise=null,r})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,r=new(0,s.loader)(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=s.keyLoadPolicy.default;r.load(l,{loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},{onSuccess:(d,f,m,g)=>{const{frag:y,keyInfo:E,url:T}=m;if(!y.decryptdata||E!==this.keyUriToKeyInfo[T])return o(this.createKeyLoadError(y,A.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));E.decryptdata.key=y.decryptdata.key=new Uint8Array(d.data),y.keyLoader=null,E.loader=null,a({frag:y,keyInfo:E})},onError:(d,f,m,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,A.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),m,re({url:l.url,data:void 0},d)))},onTimeout:(d,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,A.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(d,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,A.INTERNAL_ABORTED,new Error("key loading aborted"),m))}})})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}function zr(){return self.SourceBuffer||self.WebKitSourceBuffer}function Xr(){if(!Oe())return!1;const e=zr();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class xc{constructor(e,t,s,i){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=s,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:s,media:i,stalled:r}=this;if(null===i)return;const{currentTime:a,seeking:o}=i,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),null!==r){if(this.stallReported){const y=self.performance.now()-r;v.warn(`playback not stuck anymore @${a}, after ${Math.round(y)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l)return void(this.stalled=null);if(i.paused&&!o||i.ended||0===i.playbackRate||!Z.getBuffered(i).length)return void(this.nudgeRetry=0);const h=Z.bufferInfo(i,a,0),u=h.nextStart||0;if(o){const y=h.len>2,E=!u||t&&t.start<=a||u-a>2&&!this.fragmentTracker.getPartialFragment(a);if(y||E)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var d;if(!(h.len>0||u))return;const E=Math.max(u,h.start||0)-a,T=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,R=(null==T||null==(d=T.details)?void 0:d.live)?2*T.details.targetduration:2,S=this.fragmentTracker.getPartialFragment(a);if(E>0&&(E<=R||S))return void(i.paused||this._trySkipBufferHole(S))}const f=self.performance.now();if(null===r)return void(this.stalled=f);const m=f-r;if(!o&&m>=250&&(this._reportStall(h),!this.media))return;const g=Z.bufferInfo(i,a,s.maxBufferHole);this._tryFixBufferStall(g,m)}_tryFixBufferStall(e,t){const{config:s,fragmentTracker:i,media:r}=this;if(null===r)return;const a=r.currentTime,o=i.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>s.maxBufferHole||e.nextStart&&e.nextStart-a<s.maxBufferHole)&&t>1e3*s.highBufferWatchdogPeriod&&(v.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:s,stallReported:i}=this;if(!i&&s){this.stallReported=!0;const r=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(e)})`);v.warn(r.message),t.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:s,media:i}=this;if(null===i)return 0;const r=i.currentTime,a=Z.bufferInfo(i,r,0),o=r<a.start?a.start:a.nextStart;if(o){const h=o-r;if(h>0&&(a.len<=t.maxBufferHole||a.len>0&&a.len<1&&i.readyState<3)){if(h>t.maxBufferHole){const{fragmentTracker:d}=this;let f=!1;if(0===r){const m=d.getAppendedFrag(0,"main");m&&o<m.end&&(f=!0)}if(!f){const m=e||d.getAppendedFrag(r,"main");if(m){let g=!1,y=m.end;for(;y<o;){const E=d.getPartialFragment(y);if(!E){g=!0;break}y+=E.duration}if(g)return 0}}}const u=Math.max(o+.05,r+.1);if(v.warn(`skipping hole, adjusting currentTime from ${r} to ${u}`),this.moved=!0,this.stalled=null,i.currentTime=u,e&&!e.gap){const d=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${u}`);s.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:e})}return u}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:s,nudgeRetry:i}=this;if(null===s)return;const r=s.currentTime;if(this.nudgeRetry++,i<e.nudgeMaxRetry){const a=r+(i+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${r} to ${a}`);v.warn(o.message),s.currentTime=a,t.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const a=new Error(`Playhead still not moving while enough data buffered @${r} after ${e.nudgeMaxRetry} nudges`);v.error(a.message),t.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:A.BUFFER_STALLED_ERROR,error:a,fatal:!0})}}}class Sc extends us{constructor(e,t,s){super(e,t,s,"[stream-controller]","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(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.ERROR,this.onError,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.ERROR,this.onError,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let i=s.startLevel;-1===i&&(s.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=s.firstAutoLevel),s.nextLoadLevel=i,this.level=s.loadLevel,this.loadedmetadata=!1}t>0&&-1===e&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state="IDLE",this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state="STOPPED"}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case"WAITING_LEVEL":{const{levels:t,level:s}=this,i=t?.[s],r=i?.details;if(r&&(!r.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(r))break;this.state="IDLE";break}if(this.hls.nextLoadLevel!==this.level){this.state="IDLE";break}break}case"FRAG_LOADING_WAITING_RETRY":{var e;const t=self.performance.now(),s=this.retryDate;if(!s||t>=s||null!=(e=this.media)&&e.seeking){const{levels:i,level:r}=this,a=i?.[r];this.resetStartWhenNotLoaded(a||null),this.state="IDLE"}}}"IDLE"===this.state&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(null===t||!i&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(null==s||!s[r])return;const a=s[r],o=this.getMainFwdBufferInfo();if(null===o)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const g={};return this.altAudio&&(g.type="video"),this.hls.trigger(p.BUFFER_EOS,g),void(this.state="ENDED")}if(!this.buffering)return;e.loadLevel!==r&&-1===e.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const c=a.details;if(!c||"WAITING_LEVEL"===this.state||c.live&&this.levelLastLoaded!==a)return this.level=r,void(this.state="WAITING_LEVEL");const h=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&"initSegment"!==f.sn&&"OK"!==this.fragmentTracker.getState(f)){var m;const y=(null!=(m=this.backtrackFragment)?m:f).sn-c.startSN,E=c.fragments[y-1];E&&f.cc===E.cc&&(f=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,d)){if(!f.gap){const y=this.audioOnly&&!this.altAudio?"audio":"video",E=("video"===y?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,y,"main")}f=this.getNextFragmentLoopLoading(f,c,o,"main",u)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);this.fragCurrent=e,"NOT_LOADED"===i||"PARTIAL"===i?"initSegment"===e.sn?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,s)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,"main")}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(null!=t&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(null!=r&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<2*r.targetduration)return}if(!t.paused&&e){const c=this.fragLastKbps;s=c&&this.fragCurrent?this.fragCurrent.duration*e[this.hls.nextLoadLevel].maxBitrate/(1e3*c)+1:0}else s=0;const a=this.getBufferedFrag(t.currentTime+s);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const c=o.duration,h=Math.max(a.end,(o.maxStartPTS?o.maxStartPTS:o.start)+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case"KEY_LOADING":case"FRAG_LOADING":case"FRAG_LOADING_WAITING_RETRY":case"PARSING":case"PARSED":this.state="IDLE"}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),s.addEventListener("playing",this.onvplaying),s.addEventListener("seeked",this.onvseeked),this.gapController=new xc(this.config,s,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;F(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const s=this.getMainFwdBufferInfo();null!==s&&0!==s.len?this.tick():this.warn(`Main forward buffer length on "seeked" event ${s?s.len:"empty"})`)}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let s=!1,i=!1;t.levels.forEach(r=>{const a=r.audioCodec;a&&(s=s||-1!==a.indexOf("mp4a.40.2"),i=i||-1!==a.indexOf("mp4a.40.5"))}),this.audioCodecSwitch=s&&i&&!function pc(){var n;const e=zr();return"function"==typeof(null==e||null==(n=e.prototype)?void 0:n.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||"IDLE"!==this.state)return;const i=s[t.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state="WAITING_LEVEL")}onLevelLoaded(e,t){var s;const{levels:i}=this,r=t.level,a=t.details,o=a.totalduration;if(!i)return void this.warn(`Levels were reset while loading level ${r}`);this.log(`Level ${r} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=i[r],c=this.fragCurrent;c&&("FRAG_LOADING"===this.state||"FRAG_LOADING_WAITING_RETRY"===this.state)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let h=0;if(a.live||null!=(s=l.details)&&s.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(p.LEVEL_UPDATED,{details:a,level:r}),"WAITING_LEVEL"===this.state){if(this.waitForCdnTuneIn(a))return;this.state="IDLE"}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,h),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:s,part:i,payload:r}=e,{levels:a}=this;if(!a)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);const o=a[s.level],l=o.details;if(!l)return this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),void this.fragmentTracker.removeFragment(s);const c=o.videoCodec,h=l.PTSKnown||!l.live,u=null==(t=s.initSegment)?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new dr(this.hls,"main",this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=i?i.index:-1,y=new cs(s.level,s.sn,s.stats.chunkCount,r.byteLength,m,-1!==m);f.push(r,u,d,c,s,i,l.totalduration,h,y,this.initPTS[s.cc])}onAudioTrackSwitching(e,t){const s=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;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;s&&(r.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),r.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=!!this.hls.audioTracks[t.id].url;if(i){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,a=!1;for(const o in s){const l=s[o];if("main"===l.id){if(r=o,i=l,"video"===o){const c=s[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s&&"main"!==s.type)return;if(this.fragContextChanged(s))return this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),void("PARSED"===this.state&&(this.state="IDLE"));const r=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),"initSegment"!==s.sn&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}onError(e,t){var s;if(t.fatal)this.state="ERROR";else switch(t.details){case A.FRAG_GAP:case A.FRAG_PARSING_ERROR:case A.FRAG_DECRYPT_ERROR:case A.FRAG_LOAD_ERROR:case A.FRAG_LOAD_TIMEOUT:case A.KEY_LOAD_ERROR:case A.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError("main",t);break;case A.LEVEL_LOAD_ERROR:case A.LEVEL_LOAD_TIMEOUT:case A.LEVEL_PARSING_ERROR:!t.levelRetry&&"WAITING_LEVEL"===this.state&&"level"===(null==(s=t.context)?void 0:s.type)&&(this.state="IDLE");break;case A.BUFFER_APPEND_ERROR:case A.BUFFER_FULL_ERROR:if(!t.parent||"main"!==t.parent)return;if(t.details===A.BUFFER_APPEND_ERROR)return void this.resetLoadingState();this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case A.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}checkBuffer(){const{media:e,gapController:t}=this;e&&t&&e.readyState&&(!this.loadedmetadata&&Z.getBuffered(e).length||t.poll(this.lastCurrentTime,"IDLE"!==this.state?this.fragCurrent:null),this.lastCurrentTime=e.currentTime)}onFragLoadEmergencyAborted(){this.state="IDLE",this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){("audio"!==t||this.audioOnly&&!this.altAudio)&&(this.afterBufferFlushed(("video"===t?this.videoBuffer:this.mediaBuffer)||this.media,t,"main"),this.tick())}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking)return void this.log(`could not seek to ${s}, already seeking at ${t}`);const i=Z.getBuffered(e),a=(i.length?i.start(0):0)-s;a>0&&(a<this.config.maxBufferHole||a<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${a} to match buffer start`),s+=a,this.startPosition=s),this.log(`seek to target start position ${s} from current time ${t}`),e.currentTime=s}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this;if(!s||this.fragContextChanged(e))return;t.fragmentError=0,this.state="IDLE",this.startFragRequested=!1,this.bitrateTest=!1;const r=e.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(p.FRAG_LOADED,s),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const s="main",{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o)return void this.resetWhenMissingContext(a);const{frag:l,part:c,level:h}=o,{video:u,text:d,id3:f,initSegment:m}=r,{details:g}=h,y=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l))this.fragmentTracker.removeFragment(l);else{if(this.state="PARSING",m){if(null!=m&&m.tracks){const x=l.initSegment||l;this._bufferInitSegment(h,m.tracks,x,a),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:s,tracks:m.tracks})}const E=m.initPTS,T=m.timescale;F(E)&&(this.initPTS[l.cc]={baseTime:E,timescale:T},i.trigger(p.INIT_PTS_FOUND,{frag:l,id:s,initPTS:E,timescale:T}))}if(u&&g&&"initSegment"!==l.sn){const E=g.fragments[l.sn-1-g.startSN],T=l.sn===g.startSN,x=!E||l.cc>E.cc;if(!1!==r.independent){const{startPTS:R,endPTS:S,startDTS:b,endDTS:L}=u;if(c)c.elementaryStreams[u.type]={startPTS:R,endPTS:S,startDTS:b,endDTS:L};else if(u.firstKeyFrame&&u.independent&&1===a.id&&!x&&(this.couldBacktrack=!0),u.dropped&&u.independent){const C=this.getMainFwdBufferInfo(),w=(C?C.end:this.getLoadPosition())+this.config.maxBufferHole;if(!T&&w<(u.firstKeyFramePTS?u.firstKeyFramePTS:R)-this.config.maxBufferHole&&!x)return void this.backtrack(l);x&&(l.gap=!0),l.setElementaryStreamInfo(u.type,l.start,S,l.start,L,!0)}else T&&R>2&&(l.gap=!0);l.setElementaryStreamInfo(u.type,R,S,b,L),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(u,l,c,a,T||x)}else{if(!T&&!x)return void this.backtrack(l);l.gap=!0}}if(y){const{startPTS:E,endPTS:T,startDTS:x,endDTS:R}=y;c&&(c.elementaryStreams.audio={startPTS:E,endPTS:T,startDTS:x,endDTS:R}),l.setElementaryStreamInfo("audio",E,T,x,R),this.bufferFragmentData(y,l,c,a)}g&&null!=f&&null!=(t=f.samples)&&t.length&&i.trigger(p.FRAG_PARSING_METADATA,{id:s,frag:l,details:g,samples:f.samples}),g&&d&&i.trigger(p.FRAG_PARSING_USERDATA,{id:s,frag:l,details:g,samples:d.samples})}}_bufferInitSegment(e,t,s,i){if("PARSING"!==this.state)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:r,video:a,audiovideo:o}=t;if(r){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l=-1!==l.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const h=r.metadata;h&&"channelCount"in h&&1!==(h.channelCount||1)&&-1===c.indexOf("firefox")&&(l="mp4a.40.5")}l&&-1!==l.indexOf("mp4a.40.5")&&-1!==c.indexOf("android")&&"audio/mpeg"!==r.container&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),r.levelCodec=l,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${r.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.codecs}/${o.codec}]`),this.hls.trigger(p.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const h=t[l].initSegment;null!=h&&h.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:h,frag:s,part:null,chunkMeta:i,parent:s.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,"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="IDLE"}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&!1===e.seeking){const s=e.currentTime;if(Z.isBuffered(e,s)?t=this.getAppendedFrag(s):Z.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!i||i.level!==r)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,s=this.currentFrag;if(s&&F(t)&&F(s.programDateTime))return new Date(s.programDateTime+1e3*(t-s.start))}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}let Us=(()=>{class n{static get version(){return"1.5.20"}static isMSESupported(){return Xr()}static isSupported(){return function mc(){if(!Xr())return!1;const n=Oe();return"function"==typeof n?.isTypeSupported&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>n.isTypeSupported(Je(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(Je(e,"audio"))))}()}static getMediaSource(){return Oe()}static get Events(){return p}static get ErrorTypes(){return B}static get ErrorDetails(){return A}static get DefaultConfig(){return n.defaultConfig?n.defaultConfig:qr}static set DefaultConfig(t){n.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new xs,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,function ln(n,e){if("object"==typeof console&&!0===n||"object"==typeof n){!function on(n,...e){e.forEach(function(t){ze[t]=n[t]?n[t].bind(n):function an(n){const e=self.console[n];return e?e.bind(self.console,`[${n}] >`):ke}(t)})}(n,"debug","log","info","warn","error");try{ze.log(`Debug logs enabled for "${e}" in hls.js version 1.5.20`)}catch{ze=Ut}}else ze=Ut}(t.debug||!1,"Hls instance");const s=this.config=function uc(n,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const t=Ms(n),i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(r=>{const a=`${"level"===r?"playlist":r}LoadPolicy`,o=void 0===e[a],l=[];i.forEach(c=>{const h=`${r}Loading${c}`,u=e[h];if(void 0!==u&&o){l.push(h);const d=t[a].default;switch(e[a]={default:d},c){case"TimeOut":d.maxLoadTimeMs=u,d.maxTimeToFirstByteMs=u;break;case"MaxRetry":d.errorRetry.maxNumRetry=u,d.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":d.errorRetry.retryDelayMs=u,d.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=u,d.timeoutRetry.maxRetryDelayMs=u}}}),l.length&&v.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),re(re({},t),e)}(n.DefaultConfig,t);this.userConfig=t,s.progressive&&function dc(n){const e=n.loader;e!==Yr&&e!==Wr?(v.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):function ec(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}()&&(n.loader=Yr,n.progressive=!0,n.enableSoftwareAES=!0,v.log("[config]: Progressive streaming enabled, using FetchLoader"))}(s);const{abrController:i,bufferController:r,capLevelController:a,errorController:o,fpsController:l}=s,c=new o(this),h=this.abrController=new i(this),u=this.bufferController=new r(this),d=this.capLevelController=new a(this),f=new l(this),m=new sa(this),g=new oa(this),y=s.contentSteeringController,E=y?new y(this):null,T=this.levelController=new fc(this,E),x=new Ma(this),R=new gc(this.config),S=this.streamController=new Sc(this,x,R);d.setStreamController(S),f.setStreamController(S);const b=[m,T,S];E&&b.splice(1,0,E),this.networkControllers=b;const L=[h,u,d,f,g,x];this.audioTrackController=this.createController(s.audioTrackController,b);const C=s.audioStreamController;C&&b.push(new C(this,x,R)),this.subtitleTrackController=this.createController(s.subtitleTrackController,b);const w=s.subtitleStreamController;w&&b.push(new w(this,x,R)),this.createController(s.timelineController,L),R.emeController=this.emeController=this.createController(s.emeController,L),this.cmcdController=this.createController(s.cmcdController,L),this.latencyController=this.createController(la,L),this.coreComponents=L,b.push(c);const I=c.onErrorOut;"function"==typeof I&&this.on(p.ERROR,I,c)}createController(t,s){if(t){const i=new t(this);return s&&s.push(i),i}return null}on(t,s,i=this){this._emitter.on(t,s,i)}once(t,s,i=this){this._emitter.once(t,s,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,s,i=this,r){this._emitter.off(t,s,i,r)}listeners(t){return this._emitter.listeners(t)}emit(t,s,i){return this._emitter.emit(t,s,i)}trigger(t,s){if(this.config.debug)return this.emit(t,t,s);try{return this.emit(t,t,s)}catch(i){v.error("An internal error happened while handling event "+t+'. Error message: "'+i.message+'". Here is a stacktrace:',i),this.triggeringException||(this.triggeringException=!0,this.trigger(p.ERROR,{type:B.OTHER_ERROR,details:A.INTERNAL_EXCEPTION,fatal:t===p.ERROR,event:t,error:i}),this.triggeringException=!1)}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){v.log("destroy"),this.trigger(p.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(s=>s.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(s=>s.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){v.log("attachMedia"),this._media=t,this.trigger(p.MEDIA_ATTACHING,{media:t})}detachMedia(){v.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,void 0),this._media=null}loadSource(t){this.stopLoad();const s=this.media,i=this.url,r=this.url=Nt.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,v.log(`loadSource:${r}`),s&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),this.trigger(p.MANIFEST_LOADING,{url:t})}startLoad(t=-1){v.log(`startLoad(${t})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(t),this.started&&this.networkControllers);s++);}stopLoad(){v.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}resumeBuffering(){v.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()})}pauseBuffering(){v.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()})}swapAudioCodec(){v.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){v.log("recoverMediaError");const t=this._media;this.detachMedia(),t&&this.attachMedia(t)}removeLevel(t){this.levelController.removeLevel(t)}get levels(){return this.levelController.levels||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){v.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){v.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){v.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){v.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){v.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const s=!!t;s!==this.config.capLevelToPlayerSize&&(s?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(v.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function ca(n){return is.indexOf(n)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:s}}=this;if(!t)return 0;const i=t.length;for(let r=0;r<i;r++)if(t[r].maxBitrate>=s)return r;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:s,maxHdcpLevel:i}=this;let r;if(r=-1===s&&null!=t&&t.length?t.length-1:s,i)for(let a=r;a--;){const o=t[a].attrs["HDCP-LEVEL"];if(o&&o<=i)return a}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(t){var s;return null==(s=this.audioTrackController)?void 0:s.setAudioOption(t)}setSubtitleOption(t){var s;return null==(s=this.subtitleTrackController)||s.setSubtitleOption(t),null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const s=this.audioTrackController;s&&(s.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const s=this.subtitleTrackController;s&&(s.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const s=this.subtitleTrackController;s&&(s.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}return n.defaultConfig=void 0,n})();const Ac=["file","extension","filetype","type","ext"],Lc={mp4:"video/mp4",webm:"video/mp4",cmaf:"video/mp4",cmfv:"video/mp4",m3u8:"application/x-mpegURL"};class Qr{constructor(e,t,s,i,r,a,o,l,c,h){this.pipMode=!1,this._videoType=null,this._videoContainer=null,this._firstReadyToPlay=!0,this._isEnded=!1,this._videoRate=1,this._videoExitOnEnd=!0,this._videoLoopOnEnd=!1,this._url=t,this._container=o,this._mode=e,this._width=c||320,this._height=h||180,this._mode=e,this._videoRate=i,this._zIndex=l||1,this._playerId=s,this._videoExitOnEnd=r,this._videoLoopOnEnd=a}initialize(){var e=this;return(0,j.A)(function*(){if(e._getVideoType()){"fullscreen"===e._mode&&(e._container.style.position="absolute",e._container.style.width="100vw",e._container.style.height="100vh"),"embedded"===e._mode&&(e._container.style.position="relative",e._container.style.width=e._width.toString()+"px",e._container.style.height=e._height.toString()+"px"),e._container.style.left="0",e._container.style.top="0",e._container.style.display="flex",e._container.style.alignItems="center",e._container.style.justifyContent="center",e._container.style.backgroundColor="#000000",e._container.style.zIndex=e._zIndex.toString();const s="fullscreen"===e._mode?window.innerWidth:e._width,i="fullscreen"===e._mode?window.innerHeight:e._height,r="http://www.w3.org/2000/svg",a=document.createElementNS(r,"svg");a.setAttributeNS(null,"width",s.toString()),a.setAttributeNS(null,"height",i.toString());const o="0 0 "+s.toString()+" "+i.toString();a.setAttributeNS(null,"viewBox",o),a.style.zIndex=(e._zIndex+1).toString();const l=document.createElementNS(r,"rect");l.setAttributeNS(null,"x","0"),l.setAttributeNS(null,"y","0"),l.setAttributeNS(null,"width",s.toString()),l.setAttributeNS(null,"height",i.toString()),l.setAttributeNS(null,"fill","#000000"),a.appendChild(l),e._container.appendChild(a);const c=s*e._height/e._width;e._videoContainer=document.createElement("div"),e._videoContainer.style.position="absolute",e._videoContainer.style.left="0",e._videoContainer.style.width=s.toString()+"px",e._videoContainer.style.height=c.toString()+"px",e._videoContainer.style.zIndex=(e._zIndex+2).toString(),e._container.appendChild(e._videoContainer),(yield e.createVideoElement(s,c))||e._createEvent("Exit",e._playerId,"Video Error: failed to create the Video Element")}else e._createEvent("Exit",e._playerId,"Url Error: type not supported")})()}createVideoElement(e,t){var s=this;return(0,j.A)(function*(){s.videoEl=document.createElement("video"),s.videoEl.controls=!0,s.videoEl.style.zIndex=(s._zIndex+3).toString(),s.videoEl.style.width=`${e.toString()}px`,s.videoEl.style.height=`${t.toString()}px`,s.videoEl.playbackRate=s._videoRate,s._videoContainer.appendChild(s.videoEl);const i=yield s._setPlayer();if(i&&(s.videoEl.onended=(0,j.A)(function*(){s._isEnded=!0,s.isPlaying=!1,s.videoEl&&(s.videoEl.currentTime=0),s._videoExitOnEnd?("fullscreen"===s._mode&&s._closeFullscreen(),s._createEvent("Ended",s._playerId)):s._videoLoopOnEnd&&null!=s.videoEl&&(yield s.videoEl.play())}),s.videoEl.oncanplay=(0,j.A)(function*(){s._firstReadyToPlay&&(s._createEvent("Ready",s._playerId),null!=s.videoEl&&(s.videoEl.muted=!1,"fullscreen"===s._mode&&(yield s.videoEl.play()),s._firstReadyToPlay=!1))}),s.videoEl.onplay=()=>{s.isPlaying=!0,s._firstReadyToPlay&&(s._firstReadyToPlay=!1),s._createEvent("Play",s._playerId)},s.videoEl.onplaying=()=>{s._createEvent("Playing",s._playerId)},s.videoEl.onpause=()=>{s.isPlaying=!1,s._createEvent("Pause",s._playerId)},"fullscreen"===s._mode)){const r=document.createElement("button");r.textContent="X",r.style.position="absolute",r.style.left="1%",r.style.top="5%",r.style.width="5vmin",r.style.padding="0.5%",r.style.fontSize="1.2rem",r.style.background="rgba(51,51,51,.4)",r.style.color="#fff",r.style.visibility="hidden",r.style.zIndex=(s._zIndex+4).toString(),r.style.border="1px solid rgba(51,51,51,.4)",r.style.borderRadius="20px",s._videoContainer.onclick=(0,j.A)(function*(){s._initial=yield s._doHide(r,3e3)}),s._videoContainer.ontouchstart=(0,j.A)(function*(){s._initial=yield s._doHide(r,3e3)}),s._videoContainer.onmousemove=(0,j.A)(function*(){s._initial=yield s._doHide(r,3e3)}),r.onclick=()=>{s._createEvent("Exit",s._playerId)},r.ontouchstart=()=>{s._createEvent("Exit",s._playerId)},s._videoContainer.appendChild(r),s._initial=yield s._doHide(r,3e3),s._goFullscreen()}return i})()}_goFullscreen(){var e=this;return(0,j.A)(function*(){e._container.mozRequestFullScreen?e._container.mozRequestFullScreen():e._container.webkitRequestFullscreen?e._container.webkitRequestFullscreen():e._container.msRequestFullscreen?e._container.msRequestFullscreen():e._container.requestFullscreen&&e._container.requestFullscreen()})()}_setPlayer(){var e=this;return(0,j.A)(function*(){return new Promise(t=>{if(null!=e.videoEl){if(Us.isSupported()&&"application/x-mpegURL"===e._videoType){const s=new Us;s.loadSource(e._url),s.attachMedia(e.videoEl),s.once(Us.Events.FRAG_PARSED,()=>{null!=e.videoEl?(e.videoEl.muted=!0,e.videoEl.crossOrigin="anonymous",t(!0)):t(!1)})}else"video/mp4"===e._videoType?(e.videoEl.src=e._url,"https"!=e._url.substring(0,5)&&"http"===e._url.substring(0,4)&&(e.videoEl.crossOrigin="anonymous"),("https"===e._url.substring(0,5)||"http"===e._url.substring(0,4))&&(e.videoEl.muted=!0),t(!0)):t(!1);e.videoEl.addEventListener("enterpictureinpicture",s=>{e.pipWindow=s.pictureInPictureWindow,e.pipMode=!0,e._closeFullscreen()}),e.videoEl.addEventListener("leavepictureinpicture",()=>{e.pipMode=!1,e._isEnded||(e._goFullscreen(),null!=e.videoEl&&e.videoEl.play())})}else t(!1)})})()}_getVideoType(){const e=this._url?this._url:"";return null!=e&&e.length>0?(Object.entries(Lc).forEach(([i,r])=>e.match(new RegExp(`.(${i})`,"i"))||e.match(new RegExp(`(${i})`,"i"))?this._videoType=r:void 0),e.match(/\.(.*)/i)||e.match(new RegExp(`(${Ac.join("|")})=+(.*)&?(?=&|$))`,"i"))?this._videoType=null:"video/mp4"):null}_doHide(e,t){var s=this;return(0,j.A)(function*(){return clearTimeout(s._initial),e.style.visibility="visible",setTimeout(()=>{e.style.visibility="hidden"},t)})()}_createEvent(e,t,s){const i=s||null;let r;r=null!=i?new CustomEvent(`videoPlayer${e}`,{detail:{fromPlayerId:t,message:i}}):new CustomEvent(`videoPlayer${e}`,{detail:{fromPlayerId:t,currentTime:this.videoEl?this.videoEl.currentTime:0}}),document.dispatchEvent(r)}_closeFullscreen(){const e=document;(e.fullscreenElement&&null!==e.fullscreenElement||e.webkitFullscreenElement&&null!==e.webkitFullscreenElement||e.mozFullScreenElement&&null!==e.mozFullScreenElement||e.msFullscreenElement&&null!==e.msFullscreenElement)&&(e.mozCancelFullScreen?e.mozCancelFullScreen():e.webkitExitFullscreen?e.webkitExitFullscreen():e.msExitFullscreen?e.msExitFullscreen():e.exitFullscreen&&e.exitFullscreen())}}class Rc extends Jr.E_{constructor(){super(),this._players=[],this.addListeners()}echo(e){return(0,j.A)(function*(){return Promise.resolve({result:!0,method:"echo",value:e})})()}initPlayer(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"initPlayer",message:"Must provide a capVideoPlayerOptions object"});if(t.mode=e.mode?e.mode:"",null==t.mode||0===t.mode.length)return Promise.resolve({result:!1,method:"initPlayer",message:"Must provide a Mode (fullscreen/embedded)"});if("fullscreen"===t.mode||"embedded"===t.mode){const s=e.url?e.url:"";if(null==s||0===s.length)return Promise.resolve({result:!1,method:"initPlayer",message:"Must provide a Video Url"});if("internal"==s)return Promise.resolve({result:!1,method:"initPlayer",message:"Internal Videos not supported on Web Platform"});const i=e.playerId?e.playerId:"";if(null==i||0===i.length)return Promise.resolve({result:!1,method:"initPlayer",message:"Must provide a Player Id"});const r=e.rate?e.rate:1;let a=!0;Object.keys(e).includes("exitOnEnd")&&(a=e.exitOnEnd??!0);let o=!1;Object.keys(e).includes("loopOnEnd")&&!a&&(o=e.loopOnEnd??!1);const l=e.componentTag?e.componentTag:"";if(null==l||0===l.length)return Promise.resolve({result:!1,method:"initPlayer",message:"Must provide a Component Tag"});let c=null;"embedded"===t.mode&&(c=t.checkSize(e));const h=yield t._initializeVideoPlayer(s,i,t.mode,r,a,o,l,c);return Promise.resolve({result:h})}return Promise.resolve({result:!1,method:"initPlayer",message:"Must provide a Mode either fullscreen or embedded)"})})()}isPlaying(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"isPlaying",message:"Must provide a capVideoPlayerIdOptions object"});let s=e.playerId?e.playerId:"";return(null==s||0===s.length)&&(s="fullscreen"),Promise.resolve(t._players[s]?{method:"isPlaying",result:!0,value:t._players[s].isPlaying}:{method:"isPlaying",result:!1,message:"Given PlayerId does not exist)"})})()}play(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"play",message:"Must provide a capVideoPlayerIdOptions object"});let s=e.playerId?e.playerId:"";return(null==s||0===s.length)&&(s="fullscreen"),t._players[s]?(yield t._players[s].videoEl.play(),Promise.resolve({method:"play",result:!0,value:!0})):Promise.resolve({method:"play",result:!1,message:"Given PlayerId does not exist)"})})()}pause(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"pause",message:"Must provide a capVideoPlayerIdOptions object"});let s=e.playerId?e.playerId:"";return(null==s||0===s.length)&&(s="fullscreen"),t._players[s]?(t._players[s].isPlaying&&(yield t._players[s].videoEl.pause()),Promise.resolve({method:"pause",result:!0,value:!0})):Promise.resolve({method:"pause",result:!1,message:"Given PlayerId does not exist)"})})()}getDuration(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"getDuration",message:"Must provide a capVideoPlayerIdOptions object"});let s=e.playerId?e.playerId:"";return(null==s||0===s.length)&&(s="fullscreen"),Promise.resolve(t._players[s]?{method:"getDuration",result:!0,value:t._players[s].videoEl.duration}:{method:"getDuration",result:!1,message:"Given PlayerId does not exist)"})})()}setRate(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"setRate",message:"Must provide a capVideoRateOptions object"});let s=e.playerId?e.playerId:"";(null==s||0===s.length)&&(s="fullscreen");const r=e.rate&&[.25,.5,.75,1,2,4].includes(e.rate)?e.rate:1;return t._players[s]?(t._players[s].videoEl.playbackRate=r,Promise.resolve({method:"setRate",result:!0,value:r})):Promise.resolve({method:"setRate",result:!1,message:"Given PlayerId does not exist)"})})()}getRate(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"getRate",message:"Must provide a capVideoPlayerIdOptions object"});let s=e.playerId?e.playerId:"";return(null==s||0===s.length)&&(s="fullscreen"),Promise.resolve(t._players[s]?{method:"getRate",result:!0,value:t._players[s].videoEl.playbackRate}:{method:"getRate",result:!1,message:"Given PlayerId does not exist)"})})()}setVolume(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"setVolume",message:"Must provide a capVideoVolumeOptions object"});let s=e.playerId?e.playerId:"";(null==s||0===s.length)&&(s="fullscreen");const i=e.volume?e.volume:.5;return t._players[s]?(t._players[s].videoEl.volume=i,Promise.resolve({method:"setVolume",result:!0,value:i})):Promise.resolve({method:"setVolume",result:!1,message:"Given PlayerId does not exist)"})})()}getVolume(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"getVolume",message:"Must provide a capVideoPlayerIdOptions object"});let s=e.playerId?e.playerId:"";return(null==s||0===s.length)&&(s="fullscreen"),Promise.resolve(t._players[s]?{method:"getVolume",result:!0,value:t._players[s].videoEl.volume}:{method:"getVolume",result:!1,message:"Given PlayerId does not exist)"})})()}setMuted(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"setMuted",message:"Must provide a capVideoMutedOptions object"});let s=e.playerId?e.playerId:"";(null==s||0===s.length)&&(s="fullscreen");const i=!!e.muted&&e.muted;return t._players[s]?(t._players[s].videoEl.muted=i,Promise.resolve({method:"setMuted",result:!0,value:i})):Promise.resolve({method:"setMuted",result:!1,message:"Given PlayerId does not exist)"})})()}getMuted(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"getMuted",message:"Must provide a capVideoPlayerIdOptions object"});let s=e.playerId?e.playerId:"";return(null==s||0===s.length)&&(s="fullscreen"),Promise.resolve(t._players[s]?{method:"getMuted",result:!0,value:t._players[s].videoEl.muted}:{method:"getMuted",result:!1,message:"Given PlayerId does not exist)"})})()}setCurrentTime(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"setCurrentTime",message:"Must provide a capVideoTimeOptions object"});let s=e.playerId?e.playerId:"";(null==s||0===s.length)&&(s="fullscreen");let i=e.seektime?e.seektime:0;if(t._players[s]){const r=t._players[s].videoEl.duration;return i=i<=r&&i>=0?i:r/2,t._players[s].videoEl.currentTime=i,Promise.resolve({method:"setCurrentTime",result:!0,value:i})}return Promise.resolve({method:"setCurrentTime",result:!1,message:"Given PlayerId does not exist)"})})()}getCurrentTime(e){var t=this;return(0,j.A)(function*(){if(null==e)return Promise.resolve({result:!1,method:"getCurrentTime",message:"Must provide a capVideoPlayerIdOptions object"});let s=e.playerId?e.playerId:"";return(null==s||0===s.length)&&(s="fullscreen"),Promise.resolve(t._players[s]?{method:"getCurrentTime",result:!0,value:t._players[s].videoEl.currentTime}:{method:"getCurrentTime",result:!1,message:"Given PlayerId does not exist)"})})()}stopAllPlayers(){var e=this;return(0,j.A)(function*(){for(const t in e._players){if(e._players[t].pipMode){const s=document;s.pictureInPictureElement&&(yield s.exitPictureInPicture())}e._players[t].videoEl.paused||e._players[t].videoEl.pause()}return Promise.resolve({method:"stopAllPlayers",result:!0,value:!0})})()}showController(){return(0,j.A)(function*(){return Promise.resolve({method:"showController",result:!0,value:!0})})()}isControllerIsFullyVisible(){return(0,j.A)(function*(){return Promise.resolve({method:"isControllerIsFullyVisible",result:!0,value:!0})})()}exitPlayer(){return(0,j.A)(function*(){return Promise.resolve({method:"exitPlayer",result:!0,value:!0})})()}checkSize(e){const t={width:e.width?e.width:320,height:e.height?e.height:180},s=t.height/t.width;return t.width>window.innerWidth&&(t.width=window.innerWidth,t.height=Math.floor(t.width*s)),t.height>window.innerHeight&&(t.height=window.innerHeight,t.width=Math.floor(t.height/s)),t}_initializeVideoPlayer(e,t,s,i,r,a,o,l){var c=this;return(0,j.A)(function*(){const h=e?-1==e.indexOf("%2F")?encodeURI(e):e:null;if(null===h)return Promise.resolve(!1);if(c.videoContainer=yield c._getContainerElement(t,o),null===c.videoContainer)return Promise.resolve({method:"initPlayer",result:!1,message:"componentTag or divContainerElement must be provided"});if("embedded"===s&&null==l)return Promise.resolve({method:"initPlayer",result:!1,message:"playerSize must be defined in embedded mode"});if("embedded"===s)c._players[t]=new Qr("embedded",h,t,i,r,a,c.videoContainer,2,l.width,l.height),yield c._players[t].initialize();else{if("fullscreen"!==s)return Promise.resolve({method:"initPlayer",result:!1,message:"mode not supported"});c._players.fullscreen=new Qr("fullscreen",h,"fullscreen",i,r,a,c.videoContainer,99995),yield c._players.fullscreen.initialize()}return Promise.resolve({method:"initPlayer",result:!0,value:!0})})()}_getContainerElement(e,t){return(0,j.A)(function*(){const s=document.createElement("div");if(s.id=`vc_${e}`,null!=t&&t.length>0){const i=document.querySelector(`${t}`);if(null===i)return Promise.resolve(null);let r=null;const a=i.shadowRoot?i.shadowRoot:null;return r=null!=a?a.querySelector(`[id='${e}']`):i.querySelector(`[id='${e}']`),r?.appendChild(s),Promise.resolve(s)}return Promise.resolve(null)})()}handlePlayerPlay(e){this.notifyListeners("jeepCapVideoPlayerPlay",e)}handlePlayerPause(e){this.notifyListeners("jeepCapVideoPlayerPause",e)}handlePlayerEnded(e){var t;"fullscreen"===this.mode&&(null===(t=this.videoContainer)||void 0===t||t.remove()),this.removeListeners(),this.notifyListeners("jeepCapVideoPlayerEnded",e)}handlePlayerExit(){var e;"fullscreen"===this.mode&&(null===(e=this.videoContainer)||void 0===e||e.remove()),this.removeListeners(),this.notifyListeners("jeepCapVideoPlayerExit",{dismiss:!0})}handlePlayerReady(e){this.notifyListeners("jeepCapVideoPlayerReady",e)}addListeners(){document.addEventListener("videoPlayerPlay",e=>{this.handlePlayerPlay(e.detail)},!1),document.addEventListener("videoPlayerPause",e=>{this.handlePlayerPause(e.detail)},!1),document.addEventListener("videoPlayerEnded",e=>{this.handlePlayerEnded(e.detail)},!1),document.addEventListener("videoPlayerReady",e=>{this.handlePlayerReady(e.detail)},!1),document.addEventListener("videoPlayerExit",()=>{this.handlePlayerExit()},!1)}removeListeners(){document.removeEventListener("videoPlayerPlay",e=>{this.handlePlayerPlay(e.detail)},!1),document.removeEventListener("videoPlayerPause",e=>{this.handlePlayerPause(e.detail)},!1),document.removeEventListener("videoPlayerEnded",e=>{this.handlePlayerEnded(e.detail)},!1),document.removeEventListener("videoPlayerReady",e=>{this.handlePlayerReady(e.detail)},!1),document.removeEventListener("videoPlayerExit",()=>{this.handlePlayerExit()},!1)}}}}]);