lemon-mse 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/hls.mjs CHANGED
@@ -1,14 +1,14 @@
1
- function Pt(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var Ft={exports:{}};(function(a,e){(function(t){var i=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,d,h){if(h=h||{},l=l.trim(),d=d.trim(),!d){if(!h.alwaysNormalize)return l;var c=o.parseURL(l);if(!c)throw new Error("Error trying to parse base URL.");return c.path=o.normalizePath(c.path),o.buildURLFromParts(c)}var u=o.parseURL(d);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return h.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):d;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=s.exec(f.path);f.netLoc=m[1],f.path=m[2]}f.netLoc&&!f.path&&(f.path="/");var g={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(g.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)g.path=f.path,u.params||(g.params=f.params,u.query||(g.query=f.query));else{var p=f.path,v=p.substring(0,p.lastIndexOf("/")+1)+u.path;g.path=o.normalizePath(v)}return g.path===null&&(g.path=h.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(g)},parseURL:function(l){var d=i.exec(l);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(n,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};a.exports=o})()})(Ft);var it=Ft.exports;function Ot(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(a);e&&(i=i.filter(function(s){return Object.getOwnPropertyDescriptor(a,s).enumerable})),t.push.apply(t,i)}return t}function oe(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ot(Object(t),!0).forEach(function(i){ds(a,i,t[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):Ot(Object(t)).forEach(function(i){Object.defineProperty(a,i,Object.getOwnPropertyDescriptor(t,i))})}return a}function os(a,e){if(typeof a!="object"||!a)return a;var t=a[Symbol.toPrimitive];if(t!==void 0){var i=t.call(a,e||"default");if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(a)}function ls(a){var e=os(a,"string");return typeof e=="symbol"?e:String(e)}function ds(a,e,t){return e=ls(e),e in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function ae(){return ae=Object.assign?Object.assign.bind():function(a){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(a[i]=t[i])}return a},ae.apply(this,arguments)}const k=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},hs=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=cs},cs=Number.MAX_SAFE_INTEGER||9007199254740991;let x=function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a}({}),K=function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a}({}),R=function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.UNKNOWN="unknown",a}({});const Le=function(){},st={trace:Le,debug:Le,log:Le,warn:Le,info:Le,error:Le};let Pe=st;function us(a){const e=self.console[a];return e?e.bind(self.console,`[${a}] >`):Le}function fs(a,...e){e.forEach(function(t){Pe[t]=a[t]?a[t].bind(a):us(t)})}function ms(a,e){if(typeof console=="object"&&a===!0||typeof a=="object"){fs(a,"debug","log","info","warn","error");try{Pe.log(`Debug logs enabled for "${e}" in hls.js version 1.5.8`)}catch{Pe=st}}else Pe=st}const S=Pe,gs=/^(\d+)x(\d+)$/,kt=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Z{constructor(e){typeof e=="string"&&(e=Z.parseAttrList(e)),ae(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}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=(t.length&1?"0":"")+t;const i=new Uint8Array(t.length/2);for(let s=0;s<t.length/2;s++)i[s]=parseInt(t.slice(s*2,s*2+2),16);return i}else 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 i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const t=gs.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const i={},s='"';for(kt.lastIndex=0;(t=kt.exec(e))!==null;){let r=t[2];r.indexOf(s)===0&&r.lastIndexOf(s)===r.length-1&&(r=r.slice(1,-1));const n=t[1].trim();i[n]=r}return i}}function ps(a){return a!=="ID"&&a!=="CLASS"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function xs(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"}class Mt{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const i=t.attr;for(const s in i)if(Object.prototype.hasOwnProperty.call(e,s)&&e[s]!==i[s]){S.warn(`DATERANGE tag attribute: "${s}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=s;break}e=ae(new Z({}),i,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const i=new Date(this.attr["END-DATE"]);k(i.getTime())&&(this._endDate=i)}}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 e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(k(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&&k(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class ke{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var Q={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Nt{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[Q.AUDIO]:null,[Q.VIDEO]:null,[Q.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const i=e.split("@",2);let s;i.length===1?s=t?.byteRangeEndOffset||0:s=parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}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=it.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class rt extends Nt{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 ke,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 i=Object.keys(this.levelkeys);if(i.length===1)return this._decryptdata=this.levelkeys[i[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!k(this.programDateTime))return null;const e=k(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),i=t.length;if(i>1||i===1&&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;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,i,s,r,n=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:i,startDTS:s,endDTS:r,partial:n};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,s),l.endDTS=Math.max(l.endDTS,r)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Q.AUDIO]=null,e[Q.VIDEO]=null,e[Q.AUDIOVIDEO]=null}}class vs extends Nt{constructor(e,t,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new ke,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=s;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,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)}}const ys=10;class Es{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&i>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?k(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||ys}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}var Fe=void 0,Ts=Pt(Fe);function Ae(a,e,t){return Uint8Array.prototype.slice?a.slice(e,t):new Uint8Array(Array.prototype.slice.call(a,e,t))}const nt=(a,e)=>e+10<=a.length&&a[e]===73&&a[e+1]===68&&a[e+2]===51&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128,Bt=(a,e)=>e+10<=a.length&&a[e]===51&&a[e+1]===68&&a[e+2]===73&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128,Me=(a,e)=>{const t=e;let i=0;for(;nt(a,e);){i+=10;const s=Ne(a,e+6);i+=s,Bt(a,e+10)&&(i+=10),e+=i}if(i>0)return a.subarray(t,t+i)},Ne=(a,e)=>{let t=0;return t=(a[e]&127)<<21,t|=(a[e+1]&127)<<14,t|=(a[e+2]&127)<<7,t|=a[e+3]&127,t},Ss=(a,e)=>nt(a,e)&&Ne(a,e+6)+10<=a.length-e,Ut=a=>{const e=Gt(a);for(let t=0;t<e.length;t++){const i=e[t];if($t(i))return Ds(i)}},$t=a=>a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp",Ls=a=>{const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=Ne(a,4),i=10;return{type:e,size:t,data:a.subarray(i,i+t)}},Gt=a=>{let e=0;const t=[];for(;nt(a,e);){const i=Ne(a,e+6);e+=10;const s=e+i;for(;e+8<s;){const r=Ls(a.subarray(e)),n=As(r);n&&t.push(n),e+=r.size+10}Bt(a,e)&&(e+=10)}return t},As=a=>a.type==="PRIV"?Rs(a):a.type[0]==="W"?Is(a):bs(a),Rs=a=>{if(a.size<2)return;const e=ye(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}},bs=a=>{if(a.size<2)return;if(a.type==="TXXX"){let t=1;const i=ye(a.data.subarray(t),!0);t+=i.length+1;const s=ye(a.data.subarray(t));return{key:a.type,info:i,data:s}}const e=ye(a.data.subarray(1));return{key:a.type,data:e}},Is=a=>{if(a.type==="WXXX"){if(a.size<2)return;let t=1;const i=ye(a.data.subarray(t),!0);t+=i.length+1;const s=ye(a.data.subarray(t));return{key:a.type,info:i,data:s}}const e=ye(a.data);return{key:a.type,data:e}},Ds=a=>{if(a.data.byteLength===8){const e=new Uint8Array(a.data),t=e[3]&1;let i=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return i/=45,t&&(i+=4772185884e-2),Math.round(i)}},ye=(a,e=!1)=>{const t=Cs();if(t){const d=t.decode(a);if(e){const h=d.indexOf("\0");return h!==-1?d.substring(0,h):d}return d.replace(/\0/g,"")}const i=a.length;let s,r,n,o="",l=0;for(;l<i;){if(s=a[l++],s===0&&e)return o;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(s);break;case 12:case 13:r=a[l++],o+=String.fromCharCode((s&31)<<6|r&63);break;case 14:r=a[l++],n=a[l++],o+=String.fromCharCode((s&15)<<12|(r&63)<<6|(n&63)<<0);break}}return o};let at;function Cs(){if(!navigator.userAgent.includes("PlayStation 4"))return!at&&typeof self.TextDecoder<"u"&&(at=new self.TextDecoder("utf-8")),at}const Vt={hexDump:function(a){let e="";for(let t=0;t<a.length;t++){let i=a[t].toString(16);i.length<2&&(i="0"+i),e+=i}return e}},Be=Math.pow(2,32)-1,_s=[].push,Ht={video:1,audio:2,id3:3,text:4};function ee(a){return String.fromCharCode.apply(null,a)}function Kt(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function N(a,e){const t=Yt(a,e);return t<0?4294967296+t:t}function Wt(a,e){let t=N(a,e);return t*=Math.pow(2,32),t+=N(a,e+4),t}function Yt(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function ot(a,e,t){a[e]=t>>24,a[e+1]=t>>16&255,a[e+2]=t>>8&255,a[e+3]=t&255}function ws(a){const e=a.byteLength;for(let t=0;t<e;){const i=N(a,t);if(i>8&&a[t+4]===109&&a[t+5]===111&&a[t+6]===111&&a[t+7]===102)return!0;t=i>1?t+i:e}return!1}function G(a,e){const t=[];if(!e.length)return t;const i=a.byteLength;for(let s=0;s<i;){const r=N(a,s),n=ee(a.subarray(s+4,s+8)),o=r>1?s+r:i;if(n===e[0])if(e.length===1)t.push(a.subarray(s+8,o));else{const l=G(a.subarray(s+8,o),e.slice(1));l.length&&_s.apply(t,l)}s=o}return t}function Ps(a){const e=[],t=a[0];let i=8;const s=N(a,i);i+=4;let r=0,n=0;t===0?(r=N(a,i),n=N(a,i+4),i+=8):(r=Wt(a,i),n=Wt(a,i+8),i+=16),i+=2;let o=a.length+n;const l=Kt(a,i);i+=2;for(let d=0;d<l;d++){let h=i;const c=N(a,h);h+=4;const u=c&2147483647;if((c&2147483648)>>>31===1)return S.warn("SIDX has hierarchical references (not supported)"),null;const m=N(a,h);h+=4,e.push({referenceSize:u,subsegmentDuration:m,info:{duration:m/s,start:o,end:o+u-1}}),o+=u,h+=4,i=h}return{earliestPresentationTime:r,timescale:s,version:t,referencesCount:l,references:e}}function jt(a){const e=[],t=G(a,["moov","trak"]);for(let s=0;s<t.length;s++){const r=t[s],n=G(r,["tkhd"])[0];if(n){let o=n[0];const l=N(n,o===0?12:20),d=G(r,["mdia","mdhd"])[0];if(d){o=d[0];const h=N(d,o===0?12:20),c=G(r,["mdia","hdlr"])[0];if(c){const u=ee(c.subarray(8,12)),f={soun:Q.AUDIO,vide:Q.VIDEO}[u];if(f){const m=G(r,["mdia","minf","stbl","stsd"])[0],g=Fs(m);e[l]={timescale:h,type:f},e[f]=oe({timescale:h,id:l},g)}}}}}return G(a,["moov","mvex","trex"]).forEach(s=>{const r=N(s,4),n=e[r];n&&(n.default={duration:N(s,12),flags:N(s,20)})}),e}function Fs(a){const e=a.subarray(8),t=e.subarray(86),i=ee(e.subarray(4,8));let s=i;const r=i==="enca"||i==="encv";if(r){const o=G(e,[i])[0].subarray(i==="enca"?28:78);G(o,["sinf"]).forEach(d=>{const h=G(d,["schm"])[0];if(h){const c=ee(h.subarray(4,8));if(c==="cbcs"||c==="cenc"){const u=G(d,["frma"])[0];u&&(s=ee(u))}}})}switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const n=G(t,["avcC"])[0];s+="."+Ue(n[1])+Ue(n[2])+Ue(n[3]);break}case"mp4a":{const n=G(e,[i])[0],o=G(n.subarray(28),["esds"])[0];if(o&&o.length>12){let l=4;if(o[l++]!==3)break;l=lt(o,l),l+=2;const d=o[l++];if(d&128&&(l+=2),d&64&&(l+=o[l++]),o[l++]!==4)break;l=lt(o,l);const h=o[l++];if(h===64)s+="."+Ue(h);else break;if(l+=12,o[l++]!==5)break;l=lt(o,l);const c=o[l++];let u=(c&248)>>3;u===31&&(u+=1+((c&7)<<3)+((o[l]&224)>>5)),s+="."+u}break}case"hvc1":case"hev1":{const n=G(t,["hvcC"])[0],o=n[1],l=["","A","B","C"][o>>6],d=o&31,h=N(n,2),c=(o&32)>>5?"H":"L",u=n[12],f=n.subarray(6,12);s+="."+l+d,s+="."+h.toString(16).toUpperCase(),s+="."+c+u;let m="";for(let g=f.length;g--;){const p=f[g];(p||m)&&(m="."+p.toString(16).toUpperCase()+m)}s+=m;break}case"dvh1":case"dvhe":{const n=G(t,["dvcC"])[0],o=n[2]>>1&127,l=n[2]<<5&32|n[3]>>3&31;s+="."+fe(o)+"."+fe(l);break}case"vp09":{const n=G(t,["vpcC"])[0],o=n[4],l=n[5],d=n[6]>>4&15;s+="."+fe(o)+"."+fe(l)+"."+fe(d);break}case"av01":{const n=G(t,["av1C"])[0],o=n[1]>>>5,l=n[1]&31,d=n[2]>>>7?"H":"M",h=(n[2]&64)>>6,c=(n[2]&32)>>5,u=o===2&&h?c?12:10:h?10:8,f=(n[2]&16)>>4,m=(n[2]&8)>>3,g=(n[2]&4)>>2,p=n[2]&3;s+="."+o+"."+fe(l)+d+"."+fe(u)+"."+f+"."+m+g+p+"."+fe(1)+"."+fe(1)+"."+fe(1)+"."+0;break}}return{codec:s,encrypted:r}}function lt(a,e){const t=e+5;for(;a[e++]&128&&e<t;);return e}function Ue(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function fe(a){return(a<10?"0":"")+a}function Os(a,e){if(!a||!e)return a;const t=e.keyId;return t&&e.isCommonEncryption&&G(a,["moov","trak"]).forEach(s=>{const n=G(s,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=G(n,["enca"]);const l=o.length>0;l||(o=G(n,["encv"])),o.forEach(d=>{const h=l?d.subarray(28):d.subarray(78);G(h,["sinf"]).forEach(u=>{const f=ks(u);if(f){const m=f.subarray(8,24);m.some(g=>g!==0)||(S.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${Vt.hexDump(m)} -> ${Vt.hexDump(t)}`),f.set(t,8))}})})}),a}function ks(a){const e=G(a,["schm"])[0];if(e){const t=ee(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return G(a,["schi","tenc"])[0]}return S.error("[eme] missing 'schm' box"),null}function Ms(a,e){return G(e,["moof","traf"]).reduce((t,i)=>{const s=G(i,["tfdt"])[0],r=s[0],n=G(i,["tfhd"]).reduce((o,l)=>{const d=N(l,4),h=a[d];if(h){let c=N(s,4);if(r===1){if(c===Be)return S.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;c*=Be+1,c+=N(s,8)}const u=h.timescale||9e4,f=c/u;if(k(f)&&(o===null||f<o))return f}return o},null);return n!==null&&k(n)&&(t===null||n<t)?n:t},null)}function Ns(a,e){let t=0,i=0,s=0;const r=G(a,["moof","traf"]);for(let n=0;n<r.length;n++){const o=r[n],l=G(o,["tfhd"])[0],d=N(l,4),h=e[d];if(!h)continue;const c=h.default,u=N(l,0)|c?.flags;let f=c?.duration;u&8&&(u&2?f=N(l,12):f=N(l,8));const m=h.timescale||9e4,g=G(o,["trun"]);for(let p=0;p<g.length;p++){if(t=Bs(g[p]),!t&&f){const v=N(g[p],4);t=f*v}h.type===Q.VIDEO?i+=t/m:h.type===Q.AUDIO&&(s+=t/m)}}if(i===0&&s===0){let n=1/0,o=0,l=0;const d=G(a,["sidx"]);for(let h=0;h<d.length;h++){const c=Ps(d[h]);if(c!=null&&c.references){n=Math.min(n,c.earliestPresentationTime/c.timescale);const u=c.references.reduce((f,m)=>f+m.info.duration||0,0);o=Math.max(o,u+c.earliestPresentationTime/c.timescale),l=o-n}}if(l&&k(l))return l}return i||s}function Bs(a){const e=N(a,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let i=0;const s=N(a,4);for(let r=0;r<s;r++){if(e&256){const n=N(a,t);i+=n,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return i}function Us(a,e,t){G(e,["moof","traf"]).forEach(i=>{G(i,["tfhd"]).forEach(s=>{const r=N(s,4),n=a[r];if(!n)return;const o=n.timescale||9e4;G(i,["tfdt"]).forEach(l=>{const d=l[0],h=t*o;if(h){let c=N(l,4);if(d===0)c-=h,c=Math.max(c,0),ot(l,4,c);else{c*=Math.pow(2,32),c+=N(l,8),c-=h,c=Math.max(c,0);const u=Math.floor(c/(Be+1)),f=Math.floor(c%(Be+1));ot(l,4,u),ot(l,8,f)}}})})})}function $s(a){const e={valid:null,remainder:null},t=G(a,["moof"]);if(t.length<2)return e.remainder=a,e;const i=t[t.length-1];return e.valid=Ae(a,0,i.byteOffset-8),e.remainder=Ae(a,i.byteOffset-8),e}function de(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function zt(a,e){const t=[],i=e.samples,s=e.timescale,r=e.id;let n=!1;return G(i,["moof"]).map(l=>{const d=l.byteOffset-8;G(l,["traf"]).map(c=>{const u=G(c,["tfdt"]).map(f=>{const m=f[0];let g=N(f,4);return m===1&&(g*=Math.pow(2,32),g+=N(f,8)),g/s})[0];return u!==void 0&&(a=u),G(c,["tfhd"]).map(f=>{const m=N(f,4),g=N(f,0)&16777215,p=(g&1)!==0,v=(g&2)!==0,L=(g&8)!==0;let y=0;const b=(g&16)!==0;let T=0;const I=(g&32)!==0;let A=8;m===r&&(p&&(A+=8),v&&(A+=4),L&&(y=N(f,A),A+=4),b&&(T=N(f,A),A+=4),I&&(A+=4),e.type==="video"&&(n=Gs(e.codec)),G(c,["trun"]).map(D=>{const P=D[0],_=N(D,0)&16777215,C=(_&1)!==0;let $=0;const M=(_&4)!==0,U=(_&256)!==0;let B=0;const V=(_&512)!==0;let W=0;const X=(_&1024)!==0,O=(_&2048)!==0;let F=0;const Y=N(D,4);let H=8;C&&($=N(D,H),H+=4),M&&(H+=4);let q=$+d;for(let se=0;se<Y;se++){if(U?(B=N(D,H),H+=4):B=y,V?(W=N(D,H),H+=4):W=T,X&&(H+=4),O&&(P===0?F=N(D,H):F=Yt(D,H),H+=4),e.type===Q.VIDEO){let le=0;for(;le<W;){const re=N(i,q);if(q+=4,Vs(n,i[q])){const be=i.subarray(q,q+re);qt(be,n?2:1,a+F/s,t)}q+=re,le+=re+4}}a+=B/s}}))})})}),t}function Gs(a){if(!a)return!1;const e=a.indexOf("."),t=e<0?a:a.substring(0,e);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function Vs(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function qt(a,e,t,i){const s=Xt(a);let r=0;r+=e;let n=0,o=0,l=0;for(;r<s.length;){n=0;do{if(r>=s.length)break;l=s[r++],n+=l}while(l===255);o=0;do{if(r>=s.length)break;l=s[r++],o+=l}while(l===255);const d=s.length-r;let h=r;if(o<d)r+=o;else if(o>d){S.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(n===4){if(s[h++]===181){const u=Kt(s,h);if(h+=2,u===49){const f=N(s,h);if(h+=4,f===1195456820){const m=s[h++];if(m===3){const g=s[h++],p=31&g,v=64&g,L=v?2+p*3:0,y=new Uint8Array(L);if(v){y[0]=g;for(let b=1;b<L;b++)y[b]=s[h++]}i.push({type:m,payloadType:n,pts:t,bytes:y})}}}}}else if(n===5&&o>16){const c=[];for(let m=0;m<16;m++){const g=s[h++].toString(16);c.push(g.length==1?"0"+g:g),(m===3||m===5||m===7||m===9)&&c.push("-")}const u=o-16,f=new Uint8Array(u);for(let m=0;m<u;m++)f[m]=s[h++];i.push({payloadType:n,pts:t,uuid:c.join(""),userData:ye(f),userDataBytes:f})}}}function Xt(a){const e=a.byteLength,t=[];let i=1;for(;i<e-2;)a[i]===0&&a[i+1]===0&&a[i+2]===3?(t.push(i+2),i+=2):i++;if(t.length===0)return a;const s=e-t.length,r=new Uint8Array(s);let n=0;for(i=0;i<s;n++,i++)n===t[0]&&(n++,t.shift()),r[i]=a[n];return r}function Hs(a){const e=a[0];let t="",i="",s=0,r=0,n=0,o=0,l=0,d=0;if(e===0){for(;ee(a.subarray(d,d+1))!=="\0";)t+=ee(a.subarray(d,d+1)),d+=1;for(t+=ee(a.subarray(d,d+1)),d+=1;ee(a.subarray(d,d+1))!=="\0";)i+=ee(a.subarray(d,d+1)),d+=1;i+=ee(a.subarray(d,d+1)),d+=1,s=N(a,12),r=N(a,16),o=N(a,20),l=N(a,24),d=28}else if(e===1){d+=4,s=N(a,d),d+=4;const c=N(a,d);d+=4;const u=N(a,d);for(d+=4,n=2**32*c+u,hs(n)||(n=Number.MAX_SAFE_INTEGER,S.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=N(a,d),d+=4,l=N(a,d),d+=4;ee(a.subarray(d,d+1))!=="\0";)t+=ee(a.subarray(d,d+1)),d+=1;for(t+=ee(a.subarray(d,d+1)),d+=1;ee(a.subarray(d,d+1))!=="\0";)i+=ee(a.subarray(d,d+1)),d+=1;i+=ee(a.subarray(d,d+1)),d+=1}const h=a.subarray(d,a.byteLength);return{schemeIdUri:t,value:i,timeScale:s,presentationTime:n,presentationTimeDelta:r,eventDuration:o,id:l,payload:h}}class _t{static clearKeyUriToKeyIdMap(){}constructor(e,t,i,s=[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=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&e!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES"}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof e!="number"&&(this.method==="AES-128"&&!this.iv&&S.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const t=Ks(e);return new _t(this.method,this.uri,"identity",this.keyFormatVersions,t)}return this}}function Ks(a){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=a>>8*(15-t)&255;return e}function Re(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ws(a){return typeof self<"u"&&a===self.ManagedMediaSource}const $e={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 Ys(a,e){const t=$e[e];return!!t&&!!t[a.slice(0,4)]}function dt(a,e,t=!0){return!a.split(",").some(i=>!Qt(i,e,t))}function Qt(a,e,t=!0){var i;const s=Re(t);return(i=s?.isTypeSupported(ht(a,e)))!=null?i:!1}function ht(a,e){return`${e}/mp4;codecs="${a}"`}function Jt(a){if(a){const e=a.substring(0,4);return $e.video[e]}return 2}function Ge(a){return a.split(",").reduce((e,t)=>{const i=$e.video[t];return i?(i*2+e)/(e?3:2):($e.audio[t]+e)/(e?2:1)},0)}const ct={};function js(a,e=!0){if(ct[a])return ct[a];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[a];for(let i=0;i<t.length;i++)if(Qt(t[i],"audio",e))return ct[a]=t[i],t[i];return a}const zs=/flac|opus/i;function Ve(a,e=!0){return a.replace(zs,t=>js(t.toLowerCase(),e))}function Zt(a,e){return a&&a!=="mp4a"?a:e&&e.split(",")[0]}function qs(a){const e=a.split(".");if(e.length>2){let t=e.shift()+".";return t+=parseInt(e.shift()).toString(16),t+=("000"+parseInt(e.shift()).toString(16)).slice(-4),t}return a}const ei=/#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,ti=/#EXT-X-MEDIA:(.*)/g,Xs=/^#EXT(?:INF|-X-TARGETDURATION):/m,ii=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Qs=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 ge{static findGroup(e,t){for(let i=0;i<e.length;i++){const s=e[i];if(s.id===t)return s}}static resolve(e,t){return it.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Xs.test(e)}static parseMasterPlaylist(e,t){const s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:!1},r=[];ei.lastIndex=0;let n;for(;(n=ei.exec(e))!=null;)if(n[1]){var o;const d=new Z(n[1]),h=n[2],c={attrs:d,bitrate:d.decimalInteger("BANDWIDTH")||d.decimalInteger("AVERAGE-BANDWIDTH"),name:d.NAME,url:ge.resolve(h,t)},u=d.decimalResolution("RESOLUTION");u&&(c.width=u.width,c.height=u.height),Js(d.CODECS,c),(o=c.unknownCodecs)!=null&&o.length||r.push(c),s.levels.push(c)}else if(n[3]){const d=n[3],h=n[4];switch(d){case"SESSION-DATA":{const c=new Z(h),u=c["DATA-ID"];u&&(s.sessionData===null&&(s.sessionData={}),s.sessionData[u]=c);break}case"SESSION-KEY":{const c=si(h,t);c.encrypted&&c.isSupported()?(s.sessionKeys===null&&(s.sessionKeys=[]),s.sessionKeys.push(c)):S.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":break;case"CONTENT-STEERING":{const c=new Z(h);s.contentSteering={uri:ge.resolve(c["SERVER-URI"],t),pathwayId:c["PATHWAY-ID"]||"."};break}case"START":{s.startTimeOffset=ri(h);break}}}const l=r.length>0&&r.length<s.levels.length;return s.levels=l?r:s.levels,s.levels.length===0&&(s.playlistParsingError=new Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,i){let s;const r={},n=i.levels,o={AUDIO:n.map(d=>({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:n.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(ti.lastIndex=0;(s=ti.exec(e))!==null;){const d=new Z(s[1]),h=d.TYPE;if(h){const c=o[h],u=r[h]||[];r[h]=u;const f=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],g=d.CHANNELS,p=d.CHARACTERISTICS,v=d["INSTREAM-ID"],L={attrs:d,bitrate:0,id:l++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:h,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?ge.resolve(d.URI,t):""};if(m&&(L.assocLang=m),g&&(L.channels=g),p&&(L.characteristics=p),v&&(L.instreamId=v),c!=null&&c.length){const y=ge.findGroup(c,L.groupId)||c[0];ni(L,y,"audioCodec"),ni(L,y,"textCodec")}u.push(L)}}return r}static parseLevelPlaylist(e,t,i,s,r,n){const o=new Es(t),l=o.fragments;let d=null,h=0,c=0,u=0,f=0,m=null,g=new rt(s,t),p,v,L,y=-1,b=!1,T=null;for(ii.lastIndex=0,o.m3u8=e,o.hasVariableRefs=!1;(p=ii.exec(e))!==null;){b&&(b=!1,g=new rt(s,t),g.start=u,g.sn=h,g.cc=f,g.level=i,d&&(g.initSegment=d,g.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null,T&&(g.setByteRange(T),T=null)));const P=p[1];if(P){g.duration=parseFloat(P);const _=(" "+p[2]).slice(1);g.title=_||null,g.tagList.push(_?["INF",P,_]:["INF",P])}else if(p[3]){if(k(g.duration)){g.start=u,L&&li(g,L,o),g.sn=h,g.level=i,g.cc=f,l.push(g);const _=(" "+p[3]).slice(1);g.relurl=_,ai(g,m),m=g,u+=g.duration,h++,c=0,b=!0}}else if(p[4]){const _=(" "+p[4]).slice(1);m?g.setByteRange(_,m):g.setByteRange(_)}else if(p[5])g.rawProgramDateTime=(" "+p[5]).slice(1),g.tagList.push(["PROGRAM-DATE-TIME",g.rawProgramDateTime]),y===-1&&(y=l.length);else{if(p=p[0].match(Qs),!p){S.warn("No matches on slow regex match for level playlist!");continue}for(v=1;v<p.length&&!(typeof p[v]<"u");v++);const _=(" "+p[v]).slice(1),C=(" "+p[v+1]).slice(1),$=p[v+2]?(" "+p[v+2]).slice(1):"";switch(_){case"PLAYLIST-TYPE":o.type=C.toUpperCase();break;case"MEDIA-SEQUENCE":h=o.startSN=parseInt(C);break;case"SKIP":{const M=new Z(C),U=M.decimalInteger("SKIPPED-SEGMENTS");if(k(U)){o.skippedSegments=U;for(let V=U;V--;)l.unshift(null);h+=U}const B=M.enumeratedString("RECENTLY-REMOVED-DATERANGES");B&&(o.recentlyRemovedDateranges=B.split(" "));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(C),1);break;case"VERSION":o.version=parseInt(C);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":o.live=!1;break;case"#":(C||$)&&g.tagList.push($?[C,$]:[C]);break;case"DISCONTINUITY":f++,g.tagList.push(["DIS"]);break;case"GAP":g.gap=!0,g.tagList.push([_]);break;case"BITRATE":g.tagList.push([_,C]);break;case"DATERANGE":{const M=new Z(C),U=new Mt(M,o.dateRanges[M.ID]);U.isValid||o.skippedSegments?o.dateRanges[U.id]=U:S.warn(`Ignoring invalid DATERANGE tag: "${C}"`),g.tagList.push(["EXT-X-DATERANGE",C]);break}case"DEFINE":break;case"DISCONTINUITY-SEQUENCE":f=parseInt(C);break;case"KEY":{const M=si(C,t);if(M.isSupported()){if(M.method==="NONE"){L=void 0;break}L||(L={}),L[M.keyFormat]&&(L=ae({},L)),L[M.keyFormat]=M}else S.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${C}"`);break}case"START":o.startTimeOffset=ri(C);break;case"MAP":{const M=new Z(C);if(g.duration){const U=new rt(s,t);oi(U,M,i,L),d=U,g.initSegment=d,d.rawProgramDateTime&&!g.rawProgramDateTime&&(g.rawProgramDateTime=d.rawProgramDateTime)}else{const U=g.byteRangeEndOffset;if(U){const B=g.byteRangeStartOffset;T=`${U-B}@${B}`}else T=null;oi(g,M,i,L),d=g,b=!0}break}case"SERVER-CONTROL":{const M=new Z(C);o.canBlockReload=M.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=M.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&M.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=M.optionalFloat("PART-HOLD-BACK",0),o.holdBack=M.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const M=new Z(C);o.partTarget=M.decimalFloatingPoint("PART-TARGET");break}case"PART":{let M=o.partList;M||(M=o.partList=[]);const U=c>0?M[M.length-1]:void 0,B=c++,V=new Z(C),W=new vs(V,g,t,B,U);M.push(W),g.duration+=W.duration;break}case"PRELOAD-HINT":{const M=new Z(C);o.preloadHint=M;break}case"RENDITION-REPORT":{const M=new Z(C);o.renditionReports=o.renditionReports||[],o.renditionReports.push(M);break}default:S.warn(`line parsed but not handled: ${p}`);break}}}m&&!m.relurl?(l.pop(),u-=m.duration,o.partList&&(o.fragmentHint=m)):o.partList&&(ai(g,m),g.cc=f,o.fragmentHint=g,L&&li(g,L,o));const I=l.length,A=l[0],D=l[I-1];if(u+=o.skippedSegments*o.targetduration,u>0&&I&&D){o.averagetargetduration=u/I;const P=D.sn;o.endSN=P!=="initSegment"?P:0,o.live||(D.endList=!0),A&&(o.startCC=A.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(u+=o.fragmentHint.duration),o.totalduration=u,o.endCC=f,y>0&&Zs(l,y),o}}function si(a,e,t){var i,s;const r=new Z(a),n=(i=r.METHOD)!=null?i:"",o=r.URI,l=r.hexadecimalInteger("IV"),d=r.KEYFORMATVERSIONS,h=(s=r.KEYFORMAT)!=null?s:"identity";o&&r.IV&&!l&&S.error(`Invalid IV: ${r.IV}`);const c=o?ge.resolve(o,e):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new _t(n,c,h,u,l)}function ri(a){const t=new Z(a).decimalFloatingPoint("TIME-OFFSET");return k(t)?t:null}function Js(a,e){let t=(a||"").split(/[ ,]+/).filter(i=>i);["video","audio","text"].forEach(i=>{const s=t.filter(r=>Ys(r,i));s.length&&(e[`${i}Codec`]=s.join(","),t=t.filter(r=>s.indexOf(r)===-1))}),e.unknownCodecs=t}function ni(a,e,t){const i=e[t];i&&(a[t]=i)}function Zs(a,e){let t=a[e];for(let i=e;i--;){const s=a[i];if(!s)return;s.programDateTime=t.programDateTime-s.duration*1e3,t=s}}function ai(a,e){a.rawProgramDateTime?a.programDateTime=Date.parse(a.rawProgramDateTime):e!=null&&e.programDateTime&&(a.programDateTime=e.endProgramDateTime),k(a.programDateTime)||(a.programDateTime=null,a.rawProgramDateTime=null)}function oi(a,e,t,i){a.relurl=e.URI,e.BYTERANGE&&a.setByteRange(e.BYTERANGE),a.level=t,a.sn="initSegment",i&&(a.levelkeys=i),a.initSegment=null}function li(a,e,t){a.levelkeys=e;const{encryptedFragments:i}=t;(!i.length||i[i.length-1].levelkeys!==e)&&Object.keys(e).some(s=>e[s].isCommonEncryption)&&i.push(a)}var j={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},z={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function di(a){const{type:e}=a;switch(e){case j.AUDIO_TRACK:return z.AUDIO;case j.SUBTITLE_TRACK:return z.SUBTITLE;default:return z.MAIN}}function ut(a,e){let t=a.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class er{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(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.LEVEL_LOADING,this.onLevelLoading,this),e.on(x.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(x.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.LEVEL_LOADING,this.onLevelLoading,this),e.off(x.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(x.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,r=i||s,n=new r(t);return this.loaders[e.type]=n,n}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:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:j.MANIFEST,url:i,deliveryDirectives:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:o}=t;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:j.LEVEL,url:n,deliveryDirectives:o})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:j.AUDIO_TRACK,url:r,deliveryDirectives:n})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:r,deliveryDirectives:n}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:j.SUBTITLE_TRACK,url:r,deliveryDirectives:n})}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const d=s.context;if(d&&d.url===e.url&&d.level===e.level){S.trace("[playlist-loader]: playlist request ongoing");return}S.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let r;if(e.type===j.MANIFEST?r=i.manifestLoadPolicy.default:r=ae({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),k((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===j.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===j.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===j.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const h=d.partTarget,c=d.targetduration;if(h&&c){const u=Math.max(h*3,c*.8)*1e3;r=ae({},r,{maxTimeToFirstByteMs:Math.min(u,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},l={onSuccess:(d,h,c,u)=>{const f=this.getInternalLoader(c);this.resetInternalLoader(c.type);const m=d.data;if(m.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(d,c,new Error("no EXTM3U delimiter"),u||null,h);return}h.parsing.start=performance.now(),ge.isMediaPlaylist(m)?this.handleTrackOrLevelPlaylist(d,h,c,u||null,f):this.handleMasterPlaylist(d,h,c,u)},onError:(d,h,c,u)=>{this.handleNetworkError(h,c,!1,d,u)},onTimeout:(d,h,c)=>{this.handleNetworkError(h,c,!0,void 0,d)}};s.load(e,o,l)}handleMasterPlaylist(e,t,i,s){const r=this.hls,n=e.data,o=ut(e,i),l=ge.parseMasterPlaylist(n,o);if(l.playlistParsingError){this.handleManifestParsingError(e,i,l.playlistParsingError,s,t);return}const{contentSteering:d,levels:h,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:m}=l;this.variableList=m;const{AUDIO:g=[],SUBTITLES:p,"CLOSED-CAPTIONS":v}=ge.parseMasterPlaylistMedia(n,o,l);g.length&&!g.some(y=>!y.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(S.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 Z({}),bitrate:0,url:""})),r.trigger(x.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:p,captions:v,contentSteering:d,url:o,stats:t,networkDetails:s,sessionData:c,sessionKeys:u,startTimeOffset:f,variableList:m})}handleTrackOrLevelPlaylist(e,t,i,s,r){const n=this.hls,{id:o,level:l,type:d}=i,h=ut(e,i),c=0,u=k(l)?l:k(o)?o:0,f=di(i),m=ge.parseLevelPlaylist(e.data,h,u,f,c,this.variableList);if(d===j.MANIFEST){const g={attrs:new Z({}),bitrate:0,details:m,name:"",url:h};n.trigger(x.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:h,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=m,this.handlePlaylistLoaded(m,e,t,i,s,r)}handleManifestParsingError(e,t,i,s,r){this.hls.trigger(x.ERROR,{type:K.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===j.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:r})}handleNetworkError(e,t,i=!1,s,r){let n=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===j.LEVEL?n+=`: ${e.level} id: ${e.id}`:(e.type===j.AUDIO_TRACK||e.type===j.SUBTITLE_TRACK)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(n);S.warn(`[playlist-loader]: ${n}`);let l=R.UNKNOWN,d=!1;const h=this.getInternalLoader(e);switch(e.type){case j.MANIFEST:l=i?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,d=!0;break;case j.LEVEL:l=i?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,d=!1;break;case j.AUDIO_TRACK:l=i?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case j.SUBTITLE_TRACK:l=i?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,d=!1;break}h&&this.resetInternalLoader(e.type);const c={type:K.NETWORK_ERROR,details:l,fatal:d,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(s){const u=t?.url||e.url;c.response=oe({url:u,data:void 0},s)}this.hls.trigger(x.ERROR,c)}handlePlaylistLoaded(e,t,i,s,r,n){const o=this.hls,{type:l,level:d,id:h,groupId:c,deliveryDirectives:u}=s,f=ut(t,s),m=di(s),g=typeof s.level=="number"&&m===z.MAIN?d:void 0;if(!e.fragments.length){const v=new Error("No Segments found in Playlist");o.trigger(x.ERROR,{type:K.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:f,error:v,reason:v.message,response:t,context:s,level:g,parent:m,networkDetails:r,stats:i});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const p=e.playlistParsingError;if(p){o.trigger(x.ERROR,{type:K.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:f,error:p,reason:p.message,response:t,context:s,level:g,parent:m,networkDetails:r,stats:i});return}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case j.MANIFEST:case j.LEVEL:o.trigger(x.LEVEL_LOADED,{details:e,level:g||0,id:h||0,stats:i,networkDetails:r,deliveryDirectives:u});break;case j.AUDIO_TRACK:o.trigger(x.AUDIO_TRACK_LOADED,{details:e,id:h||0,groupId:c||"",stats:i,networkDetails:r,deliveryDirectives:u});break;case j.SUBTITLE_TRACK:o.trigger(x.SUBTITLE_TRACK_LOADED,{details:e,id:h||0,groupId:c||"",stats:i,networkDetails:r,deliveryDirectives:u});break}}}function tr(a,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=a,e.dispatchEvent(t)}function ir(a){const e=a.mode;if(e==="disabled"&&(a.mode="hidden"),a.cues)for(let t=a.cues.length;t--;)a.removeCue(a.cues[t]);e==="disabled"&&(a.mode=e)}function sr(a,e,t,i){const s=a.mode;if(s==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const r=nr(a.cues,e,t);for(let n=0;n<r.length;n++)(!i||i(r[n]))&&a.removeCue(r[n])}s==="disabled"&&(a.mode=s)}function rr(a,e){if(e<a[0].startTime)return 0;const t=a.length-1;if(e>a[t].endTime)return-1;let i=0,s=t;for(;i<=s;){const r=Math.floor((s+i)/2);if(e<a[r].startTime)s=r-1;else if(e>a[r].startTime&&i<t)i=r+1;else return r}return a[i].startTime-e<e-a[s].startTime?i:s}function nr(a,e,t){const i=[],s=rr(a,e);if(s>-1)for(let r=s,n=a.length;r<n;r++){const o=a[r];if(o.startTime>=e&&o.endTime<=t)i.push(o);else if(o.startTime>t)return i}return i}var he={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const ar=.25;function ft(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function hi(a,e,t,i,s){let r=new a(e,t,"");try{r.value=i,s&&(r.type=s)}catch{r=new a(e,t,JSON.stringify(s?oe({type:s},i):i))}return r}const He=(()=>{const a=ft();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function mt(a,e){return a.getTime()/1e3-e}function or(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class lr{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(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(ir(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 i=e[t];if(i.kind==="metadata"&&i.label==="id3")return tr(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:i,enableID3MetadataCues:s}}}=this;if(!i&&!s)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=ft();if(n)for(let o=0;o<r.length;o++){const l=r[o].type;if(l===he.emsg&&!i||!s)continue;const d=Gt(r[o].data);if(d){const h=r[o].pts;let c=h+r[o].duration;c>He&&(c=He),c-h<=0&&(c=h+ar);for(let f=0;f<d.length;f++){const m=d[f];if(!$t(m)){this.updateId3CueEnds(h,l);const g=hi(n,h,c,m,l);g&&this.id3Track.addCue(g)}}}}}updateId3CueEnds(e,t){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let r=s.length;r--;){const n=s[r];n.type===t&&n.startTime<e&&n.endTime===He&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=n;if(r&&(o||l)){let d;s==="audio"?d=h=>h.type===he.audioId3&&l:s==="video"?d=h=>h.type===he.emsg&&o:d=h=>h.type===he.audioId3&&l||h.type===he.emsg&&o,sr(r,t,i,d)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:i,id3Track:s}=this,{dateRanges:r}=t,n=Object.keys(r);if(s){const h=Object.keys(i).filter(c=>!n.includes(c));for(let c=h.length;c--;){const u=h[c];Object.keys(i[u].cues).forEach(f=>{s.removeCue(i[u].cues[f])}),delete i[u]}}const o=t.fragments[t.fragments.length-1];if(n.length===0||!k(o?.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,d=ft();for(let h=0;h<n.length;h++){const c=n[h],u=r[c],f=mt(u.startDate,l),m=i[c],g=m?.cues||{};let p=m?.durationKnown||!1,v=He;const L=u.endDate;if(L)v=mt(L,l),p=!0;else if(u.endOnNext&&!p){const b=n.reduce((T,I)=>{if(I!==u.id){const A=r[I];if(A.class===u.class&&A.startDate>u.startDate&&(!T||u.startDate<T.startDate))return A}return T},null);b&&(v=mt(b.startDate,l),p=!0)}const y=Object.keys(u.attr);for(let b=0;b<y.length;b++){const T=y[b];if(!ps(T))continue;const I=g[T];if(I)p&&!m.durationKnown&&(I.endTime=v);else if(d){let A=u.attr[T];xs(T)&&(A=or(A));const D=hi(d,f,v,{key:T,data:A},he.dateRange);D&&(D.id=c,this.id3Track.addCue(D),g[T]=D)}}i[c]={cues:g,dateRange:u,durationKnown:p}}}}class dr{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 e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let d=o&&i||t;(l.liveSyncDuration||l.liveSyncDurationCount||d===0)&&(d=r!==void 0?r:n*s);const h=s;return d+Math.min(this.stallCount*1,h)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,i=this.levelDetails;if(e===null||t===null||i===null)return null;const s=i.edge,r=e-t-this.edgeStalled,n=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),o)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(x.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(x.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(x.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(x.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(x.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(x.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var i;t.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,(i=this.levelDetails)!=null&&i.live&&S.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 i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:r}=this.config;if(!s||r===1||!t.live)return;const n=this.targetLatency;if(n===null)return;const o=i-n,l=Math.min(this.maxLatency,n+t.targetduration);if(o<l&&o>.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,r)),c=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(h,Math.max(1,c))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const gt=["NONE","TYPE-0","TYPE-1",null];function hr(a){return gt.indexOf(a)>-1}const Ke=["SDR","PQ","HLG"];function cr(a){return!!a&&Ke.indexOf(a)>-1}var We={No:"",Yes:"YES",v2:"v2"};function ci(a){const{canSkipUntil:e,canSkipDateRanges:t,age:i}=a,s=i<e/2;return e&&s?t?We.v2:We.Yes:We.No}class ui{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class pt{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 fi(this._audioGroups,e)}hasSubtitleGroup(e){return fi(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let i=this._audioGroups;i||(i=this._audioGroups=[]),i.indexOf(t)===-1&&i.push(t)}else if(e==="text"){let i=this._subtitleGroups;i||(i=this._subtitleGroups=[]),i.indexOf(t)===-1&&i.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(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function fi(a,e){return!e||!a?!1:a.indexOf(e)!==-1}function xt(a,e){const t=e.startPTS;if(k(t)){let i=0,s;e.sn>a.sn?(i=t-a.start,s=a):(i=a.start-t,s=e),s.duration!==i&&(s.duration=i)}else e.sn>a.sn?a.cc===e.cc&&a.minEndPTS?e.start=a.start+(a.minEndPTS-a.start):e.start=a.start+a.duration:e.start=Math.max(a.start-e.duration,0)}function mi(a,e,t,i,s,r){i-t<=0&&(S.warn("Fragment should have a positive duration",e),i=t+e.duration,r=s+e.duration);let o=t,l=i;const d=e.startPTS,h=e.endPTS;if(k(d)){const p=Math.abs(d-t);k(e.deltaPTS)?e.deltaPTS=Math.max(p,e.deltaPTS):e.deltaPTS=p,o=Math.max(t,d),t=Math.min(t,d),s=Math.min(s,e.startDTS),l=Math.min(i,h),i=Math.max(i,h),r=Math.max(r,e.endDTS)}const c=t-e.start;e.start!==0&&(e.start=t),e.duration=i-e.start,e.startPTS=t,e.maxStartPTS=o,e.startDTS=s,e.endPTS=i,e.minEndPTS=l,e.endDTS=r;const u=e.sn;if(!a||u<a.startSN||u>a.endSN)return 0;let f;const m=u-a.startSN,g=a.fragments;for(g[m]=e,f=m;f>0;f--)xt(g[f],g[f-1]);for(f=m;f<g.length-1;f++)xt(g[f],g[f+1]);return a.fragmentHint&&xt(g[g.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,c}function ur(a,e){let t=null;const i=a.fragments;for(let l=i.length-1;l>=0;l--){const d=i[l].initSegment;if(d){t=d;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let s=0,r;if(gr(a,e,(l,d)=>{l.relurl&&(s=l.cc-d.cc),k(l.startPTS)&&k(l.endPTS)&&(d.start=d.startPTS=l.startPTS,d.startDTS=l.startDTS,d.maxStartPTS=l.maxStartPTS,d.endPTS=l.endPTS,d.endDTS=l.endDTS,d.minEndPTS=l.minEndPTS,d.duration=l.endPTS-l.startPTS,d.duration&&(r=d),e.PTSKnown=e.alignedSliding=!0),d.elementaryStreams=l.elementaryStreams,d.loader=l.loader,d.stats=l.stats,l.initSegment&&(d.initSegment=l.initSegment,t=l.initSegment)}),t&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(d=>{var h;d&&(!d.initSegment||d.initSegment.relurl===((h=t)==null?void 0:h.relurl))&&(d.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){S.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=fr(a.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const n=e.fragments;if(s){S.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<n.length;l++)n[l].cc+=s}e.skippedSegments&&(e.startCC=e.fragments[0].cc),mr(a.partList,e.partList,(l,d)=>{d.elementaryStreams=l.elementaryStreams,d.stats=l.stats}),r?mi(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):gi(a,e),n.length&&(e.totalduration=e.edge-n[0].start),e.driftStartTime=a.driftStartTime,e.driftStart=a.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const l=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=l),e.driftEndTime=o,e.driftEnd=l}else e.driftEndTime=a.driftEndTime,e.driftEnd=a.driftEnd,e.advancedDateTime=a.advancedDateTime}function fr(a,e,t){const i=ae({},a);return t&&t.forEach(s=>{delete i[s]}),Object.keys(e).forEach(s=>{const r=new Mt(e[s].attr,i[s]);r.isValid?i[s]=r:S.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[s].attr)}"`)}),i}function mr(a,e,t){if(a&&e){let i=0;for(let s=0,r=a.length;s<=r;s++){const n=a[s],o=e[s+i];n&&o&&n.index===o.index&&n.fragment.sn===o.fragment.sn?t(n,o):i--}}}function gr(a,e,t){const i=e.skippedSegments,s=Math.max(a.startSN,e.startSN)-e.startSN,r=(a.fragmentHint?1:0)+(i?e.endSN:Math.min(a.endSN,e.endSN))-e.startSN,n=e.startSN-a.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let d=s;d<=r;d++){const h=l[n+d];let c=o[d];i&&!c&&d<i&&(c=e.fragments[d]=h),h&&c&&t(h,c)}}function gi(a,e){const t=e.startSN+e.skippedSegments-a.startSN,i=a.fragments;t<0||t>=i.length||pr(e,i[t].start)}function pr(a,e){if(e){const t=a.fragments;for(let i=a.skippedSegments;i<t.length;i++)t[i].start+=e;a.fragmentHint&&(a.fragmentHint.start+=e)}}function xr(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const i=a.fragments;if(i.length&&t*4>e){const r=i[i.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function vr(a,e,t){if(!(a!=null&&a.details))return null;const i=a.details;let s=i.fragments[e-i.startSN];return s||(s=i.fragmentHint,s&&s.sn===e)?s:e<i.startSN&&t&&t.sn===e?t:null}function pi(a,e,t){var i;return a!=null&&a.details?xi((i=a.details)==null?void 0:i.partList,e,t):null}function xi(a,e,t){if(a)for(let i=a.length;i--;){const s=a[i];if(s.index===t&&s.fragment.sn===e)return s}return null}function vi(a){a.forEach((e,t)=>{const{details:i}=e;i!=null&&i.fragments&&i.fragments.forEach(s=>{s.level=t})})}function Ye(a){switch(a.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function yi(a,e){const t=Ye(e);return a.default[`${t?"timeout":"error"}Retry`]}function vt(a,e){const t=a.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*a.retryDelayMs,a.maxRetryDelayMs)}function Ei(a){return oe(oe({},a),{errorRetry:null,timeoutRetry:null})}function je(a,e,t,i){if(!a)return!1;const s=i?.code,r=e<a.maxNumRetry&&(yr(s)||!!t);return a.shouldRetry?a.shouldRetry(a,e,t,i,r):r}function yr(a){return a===0&&navigator.onLine===!1||!!a&&(a<400||a>499)}const Ti={search:function(a,e){let t=0,i=a.length-1,s=null,r=null;for(;t<=i;){s=(t+i)/2|0,r=a[s];const n=e(r);if(n>0)t=s+1;else if(n<0)i=s-1;else return r}return null}};function Er(a,e,t){if(e===null||!Array.isArray(a)||!a.length||!k(e))return null;const i=a[0].programDateTime;if(e<(i||0))return null;const s=a[a.length-1].endProgramDateTime;if(e>=(s||0))return null;t=t||0;for(let r=0;r<a.length;++r){const n=a[r];if(Tr(e,t,n))return n}return null}function Si(a,e,t=0,i=0){let s=null;if(a){s=e[a.sn-e[0].sn+1]||null;const n=a.endDTS-t;n>0&&n<15e-7&&(t+=15e-7)}else t===0&&e[0].start===0&&(s=e[0]);if(s&&(!a||a.level===s.level)&&Li(t,i,s)===0)return s;const r=Ti.search(e,Li.bind(null,t,i));return r&&(r!==a||!s)?r:s}function Li(a=0,e=0,t){if(t.start<=a&&t.start+t.duration>a)return 0;const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-i<=a?1:t.start-i>a&&t.start?-1:0}function Tr(a,e,t){const i=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-i>a}function Sr(a,e){return Ti.search(a,t=>t.cc<e?1:t.cc>e?-1:0)}var ie={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},ce={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class Lr{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=S.log.bind(S,"[info]:"),this.warn=S.warn.bind(S,"[warning]:"),this.error=S.error.bind(S,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(x.ERROR,this.onError,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(x.ERROR,this.onError,this),e.off(x.ERROR,this.onErrorOut,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===z.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,s;if(t.fatal)return;const r=this.hls,n=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case R.FRAG_PARSING_ERROR:if((i=t.frag)!=null&&i.gap){t.errorAction={action:ie.DoNothing,flags:ce.None};return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ie.SendAlternateToPenaltyBox;return}case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var o,l;const d=t.parent===z.MAIN?t.level:r.loadLevel;t.details===R.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(l=o.levelDetails)!=null&&l.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,d):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,d))}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const d=r.levels[r.loadLevel];if(d&&(n.type===j.AUDIO_TRACK&&d.hasAudioGroup(n.groupId)||n.type===j.SUBTITLE_TRACK&&d.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=ie.SendAlternateToPenaltyBox,t.errorAction.flags=ce.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const d=r.levels[r.loadLevel],h=d?.attrs["HDCP-LEVEL"];h?t.errorAction={action:ie.SendAlternateToPenaltyBox,flags:ce.MoveAllAlternatesMatchingHDCP,hdcpLevel:h}:this.keySystemError(t)}return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:t.errorAction=this.getLevelSwitchAction(t,(s=t.level)!=null?s:r.loadLevel);return;case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:t.errorAction={action:ie.DoNothing,flags:ce.None};return}t.type===K.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=this.hls,s=yi(i.config.playlistLoadPolicy,e),r=this.playlistError++;if(je(s,r,Ye(e),e.response))return{action:ie.RetryRequest,flags:ce.None,retryConfig:s,retryCount:r};const o=this.getLevelSwitchAction(e,t);return s&&(o.retryConfig=s,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,i=this.getVariantLevelIndex(e.frag),s=t.levels[i],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,o=yi(e.details.startsWith("key")?n:r,e),l=t.levels.reduce((h,c)=>h+c.fragmentError,0);if(s&&(e.details!==R.FRAG_GAP&&s.fragmentError++,je(o,l,Ye(e),e.response)))return{action:ie.RetryRequest,flags:ce.None,retryConfig:o,retryCount:l};const d=this.getLevelSwitchAction(e,i);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(e,t){const i=this.hls;t==null&&(t=i.loadLevel);const s=this.hls.levels[t];if(s){var r,n;const d=e.details;s.loadError++,d===R.BUFFER_APPEND_ERROR&&s.fragmentError++;let h=-1;const{levels:c,loadLevel:u,minAutoLevel:f,maxAutoLevel:m}=i;i.autoLevelEnabled||(i.loadLevel=-1);const g=(r=e.frag)==null?void 0:r.type,v=(g===z.AUDIO&&d===R.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(d===R.BUFFER_ADD_CODEC_ERROR||d===R.BUFFER_APPEND_ERROR))&&c.some(({audioCodec:I})=>s.audioCodec!==I),y=e.sourceBufferName==="video"&&(d===R.BUFFER_ADD_CODEC_ERROR||d===R.BUFFER_APPEND_ERROR)&&c.some(({codecSet:I,audioCodec:A})=>s.codecSet!==I&&s.audioCodec===A),{type:b,groupId:T}=(n=e.context)!=null?n:{};for(let I=c.length;I--;){const A=(I+u)%c.length;if(A!==u&&A>=f&&A<=m&&c[A].loadError===0){var o,l;const D=c[A];if(d===R.FRAG_GAP&&e.frag){const P=c[A].details;if(P){const _=Si(e.frag,P.fragments,e.frag.start);if(_!=null&&_.gap)continue}}else{if(b===j.AUDIO_TRACK&&D.hasAudioGroup(T)||b===j.SUBTITLE_TRACK&&D.hasSubtitleGroup(T))continue;if(g===z.AUDIO&&(o=s.audioGroups)!=null&&o.some(P=>D.hasAudioGroup(P))||g===z.SUBTITLE&&(l=s.subtitleGroups)!=null&&l.some(P=>D.hasSubtitleGroup(P))||v&&s.audioCodec===D.audioCodec||!v&&s.audioCodec!==D.audioCodec||y&&s.codecSet===D.codecSet)continue}h=A;break}}if(h>-1&&i.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:ie.SendAlternateToPenaltyBox,flags:ce.None,nextAutoLevel:h}}return{action:ie.SendAlternateToPenaltyBox,flags:ce.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var i;switch((i=t.errorAction)==null?void 0:i.action){case ie.DoNothing:break;case ie.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==R.FRAG_GAP?t.fatal=!0:/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());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,i=e.errorAction;if(!i)return;const{flags:s,hdcpLevel:r,nextAutoLevel:n}=i;switch(s){case ce.None:this.switchLevel(e,n);break;case ce.MoveAllAlternatesMatchingHDCP:r&&(t.maxHdcpLevel=gt[gt.indexOf(r)-1],i.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}i.resolved||this.switchLevel(e,n)}switchLevel(e,t){t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}}class Ar{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=S.log.bind(S,`${t}:`),this.warn=S.warn.bind(S,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(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,i){const s=t?.renditionReports;if(s){let r=-1;for(let n=0;n<s.length;n++){const o=s[n];let l;try{l=new self.URL(o.URI,t.url).href}catch(d){S.warn(`Could not construct new URL for Rendition Report: ${d}`),l=o.URI||""}if(l===e){r=n;break}else l===e.substring(0,l.length)&&(r=n)}if(r!==-1){const n=s[r],o=parseInt(n["LAST-MSN"])||t?.lastPartSn;let l=parseInt(n["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 d=i&&ci(i);return new ui(o,l>=0?l:void 0,d)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,i){const{details:s,stats:r}=t,n=self.performance.now(),o=r.loading.first?Math.max(0,n-r.loading.first):0;if(s.advancedDateTime=Date.now()-o,s.live||i!=null&&i.live){if(s.reloaded(i),i&&this.log(`live playlist ${e} ${s.advanced?"REFRESHED "+s.lastPartSn+"-"+s.lastPartIndex:s.updated?"UPDATED":"MISSED"}`),i&&s.fragments.length>0&&ur(i,s),!this.canLoad||!s.live)return;let l,d,h;if(s.canBlockReload&&s.endSN&&s.advanced){const p=this.hls.config.lowLatencyMode,v=s.lastPartSn,L=s.endSN,y=s.lastPartIndex,b=y!==-1,T=v===L,I=p?0:y;b?(d=T?L+1:v,h=T?I:y+1):d=L+1;const A=s.age,D=A+s.ageHeader;let P=Math.min(D-s.partTarget,s.targetduration*1.5);if(P>0){if(i&&P>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${P} with playlist age: ${s.age}`),P=0;else{const _=Math.floor(P/s.targetduration);if(d+=_,h!==void 0){const C=Math.round(P%s.targetduration/s.partTarget);h+=C}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${A.toFixed(2)}s goal: ${P} skip sn ${_} to part ${h}`)}s.tuneInGoal=P}if(l=this.getDeliveryDirectives(s,t.deliveryDirectives,d,h),p||!T){this.loadPlaylist(l);return}}else(s.canBlockReload||s.canSkipUntil)&&(l=this.getDeliveryDirectives(s,t.deliveryDirectives,d,h));const c=this.hls.mainForwardBufferInfo,u=c?c.end-c.len:0,f=(s.edge-u)*1e3,m=xr(s,f);s.updated&&n>this.requestScheduled+m&&(this.requestScheduled=r.loading.start),d!==void 0&&s.canBlockReload?this.requestScheduled=r.loading.first+m-(s.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+m<n?this.requestScheduled=n:this.requestScheduled-n<=0&&(this.requestScheduled+=m);let g=this.requestScheduled-n;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,i,s){let r=ci(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,s=t.part,r=We.No),new ui(i,s,r)}checkRetry(e){const t=e.details,i=Ye(e),s=e.errorAction,{action:r,retryCount:n=0,retryConfig:o}=s||{},l=!!s&&!!o&&(r===ie.RetryRequest||!s.resolved&&r===ie.SendAlternateToPenaltyBox);if(l){var d;if(this.requestScheduled=-1,n>=o.maxNumRetry)return!1;if(i&&(d=e.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=vt(o,n);this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,s.resolved=!0}return l}}class Ie{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){const i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Rr{constructor(e,t,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ie(e),this.fast_=new Ie(t),this.defaultTTFB_=s,this.ttfb_=new Ie(e)}update(e,t){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==e&&(this.slow_=new Ie(e,i.getEstimate(),i.getTotalWeight())),s.halfLife!==t&&(this.fast_=new Ie(t,s.getEstimate(),s.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new Ie(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const i=8*t,s=e/1e3,r=i/s;this.fast_.sample(s,r),this.slow_.sample(s,r)}sampleTTFB(e){const t=e/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(i,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(){}}function br(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(a.media!==e.media)return a.matches===!0}return!1}function Ir(a,e){let t=!1,i=[];return a&&(t=a!=="SDR",i=[a]),e&&(i=e.allowedVideoRanges||Ke.slice(0),t=e.preferHDR!==void 0?e.preferHDR:br(),t?i=i.filter(s=>s!=="SDR"):i=["SDR"]),{preferHDR:t,allowedVideoRanges:i}}function Dr(a,e,t,i,s){const r=Object.keys(a),n=i?.channels,o=i?.audioCodec,l=n&&parseInt(n)===2;let d=!0,h=!1,c=1/0,u=1/0,f=1/0,m=0,g=[];const{preferHDR:p,allowedVideoRanges:v}=Ir(e,s);for(let T=r.length;T--;){const I=a[r[T]];d=I.channels[2]>0,c=Math.min(c,I.minHeight),u=Math.min(u,I.minFramerate),f=Math.min(f,I.minBitrate);const A=v.filter(D=>I.videoRanges[D]>0);A.length>0&&(h=!0,g=A)}c=k(c)?c:0,u=k(u)?u:0;const L=Math.max(1080,c),y=Math.max(30,u);return f=k(f)?f:t,t=Math.max(f,t),h||(e=void 0,g=[]),{codecSet:r.reduce((T,I)=>{const A=a[I];if(I===T)return T;if(A.minBitrate>t)return pe(I,`min bitrate of ${A.minBitrate} > current estimate of ${t}`),T;if(!A.hasDefaultAudio)return pe(I,"no renditions with default or auto-select sound found"),T;if(o&&I.indexOf(o.substring(0,4))%5!==0)return pe(I,`audio codec preference "${o}" not found`),T;if(n&&!l){if(!A.channels[n])return pe(I,`no renditions with ${n} channel sound found (channels options: ${Object.keys(A.channels)})`),T}else if((!o||l)&&d&&A.channels[2]===0)return pe(I,"no renditions with stereo sound found"),T;return A.minHeight>L?(pe(I,`min resolution of ${A.minHeight} > maximum of ${L}`),T):A.minFramerate>y?(pe(I,`min framerate of ${A.minFramerate} > maximum of ${y}`),T):g.some(D=>A.videoRanges[D]>0)?A.maxScore<m?(pe(I,`max score of ${A.maxScore} < selected max of ${m}`),T):T&&(Ge(I)>=Ge(T)||A.fragmentError>a[T].fragmentError)?T:(m=A.maxScore,I):(pe(I,`no variants with VIDEO-RANGE of ${JSON.stringify(g)} found`),T)},void 0),videoRanges:g,preferHDR:p,minFramerate:u,minBitrate:f}}function pe(a,e){S.log(`[abr] start candidates with "${a}" ignored because ${e}`)}function Cr(a){return a.reduce((e,t)=>{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);const s=t.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function _r(a,e,t,i){return a.slice(t,i+1).reduce((s,r)=>{if(!r.codecSet)return s;const n=r.audioGroups;let o=s[r.codecSet];o||(s[r.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,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,s},{})}class wr{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:i,hls:s}=this,{autoLevelEnabled:r,media:n}=s;if(!t||!n)return;const o=performance.now(),l=i?i.stats:t.stats,d=i?i.duration:t.duration,h=o-l.loading.start,c=s.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||t.level<=c){this.clearTimer(),this._nextAutoLevel=-1;return}if(!r||n.paused||!n.playbackRate||!n.readyState)return;const u=s.mainForwardBufferInfo;if(u===null)return;const f=this.bwEstimator.getEstimateTTFB(),m=Math.abs(n.playbackRate);if(h<=Math.max(f,1e3*(d/(m*2))))return;const g=u.len/m,p=l.loading.first?l.loading.first-l.loading.start:-1,v=l.loaded&&p>-1,L=this.getBwEstimate(),y=s.levels,b=y[t.level],T=l.total||Math.max(l.loaded,Math.round(d*b.averageBitrate/8));let I=v?h-p:h;I<1&&v&&(I=Math.min(h,l.loaded*8/L));const A=v?l.loaded*1e3/I:0,D=A?(T-l.loaded)/A:T*8/L+f/1e3;if(D<=g)return;const P=A?A*8:L;let _=Number.POSITIVE_INFINITY,C;for(C=t.level-1;C>c;C--){const M=y[C].maxBitrate;if(_=this.getTimeToLoadFrag(f/1e3,P,d*M,!y[C].details),_<g)break}if(_>=D||_>d*10)return;s.nextLoadLevel=s.nextAutoLevel=C,v?this.bwEstimator.sample(h-Math.min(f,p),l.loaded):this.bwEstimator.sampleTTFB(h);const $=y[C].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>$&&this.resetEstimator($),this.clearTimer(),S.warn(`[abr] Fragment ${t.sn}${i?" part "+i.index:""} of level ${t.level} is loading too slowly;
2
- Time to underbuffer: ${g.toFixed(3)} s
3
- Estimated load time for current fragment: ${D.toFixed(3)} s
4
- Estimated load time for down switch fragment: ${_.toFixed(3)} s
5
- TTFB estimate: ${p|0} ms
6
- Current BW estimate: ${k(L)?L|0:"Unknown"} bps
7
- New BW estimate: ${this.getBwEstimate()|0} bps
8
- Switching to level ${C} @ ${$|0} bps`),s.trigger(x.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:i,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(S.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 Rr(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.FRAG_LOADING,this.onFragLoading,this),e.on(x.FRAG_LOADED,this.onFragLoaded,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this),e.on(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.FRAG_LOADING,this.onFragLoading,this),e.off(x.FRAG_LOADED,this.onFragLoaded,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this),e.off(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(x.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 i=t.frag;if(!this.ignoreFragment(i)){if(!i.bitrateTest){var s;this.fragCurrent=i,this.partCurrent=(s=t.part)!=null?s: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 R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:{const i=t.frag,{fragCurrent:s,partCurrent:r}=this;if(i&&s&&i.sn===s.sn&&i.level===s.level){const n=performance.now(),o=r?r.stats:i.stats,l=n-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){const c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(c,d),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,i,s){const r=e+i/t,n=s?this.lastLevelLoadSec:0;return r+n}onLevelLoaded(e,t){const i=this.hls.config,{loading:s}=t.stats,r=s.end-s.start;k(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:i}){const s=i?i.stats:t.stats;if(t.type===z.MAIN&&this.bwEstimator.sampleTTFB(s.loading.first-s.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=i?i.duration:t.duration,n=this.hls.levels[t.level],o=(n.loaded?n.loaded.bytes:0)+s.loaded,l=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:o,duration:l},n.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const r={stats:s,frag:t,part:i,id:t.type};this.onFragBuffered(x.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:i,part:s}=t,r=s!=null&&s.stats.loaded?s.stats:i.stats;if(r.aborted||this.ignoreFragment(i))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==z.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),s=this.hls.config.maxStarvationDelay,r=this.findBestLevel(i,t,e,0,s,1,1);if(r>-1)return r;const n=this.hls.firstLevel,o=Math.min(Math.max(n,t),e);return S.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,i=this.bwEstimator.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!i||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=i&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[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:i}=this,{maxAutoLevel:s,config:r,minAutoLevel:n}=i,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),d=this.getStarvationDelay();let h=r.abrBandWidthFactor,c=r.abrBandWidthUpFactor;if(d){const p=this.findBestLevel(l,n,s,d,0,h,c);if(p>=0)return p}let u=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!d){const p=this.bitrateTestDelay;p&&(u=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-p,S.info(`[abr] bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=c=1)}const f=this.findBestLevel(l,n,s,d,u,h,c);if(S.info(`[abr] ${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`),f>-1)return f;const m=i.levels[n],g=i.levels[i.loadLevel];return m?.bitrate<g?.bitrate?n:i.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const i=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,s,r,n,o){var l;const d=s+r,h=this.lastLoadedFragLevel,c=h===-1?this.hls.firstLevel:h,{fragCurrent:u,partCurrent:f}=this,{levels:m,allAudioTracks:g,loadLevel:p,config:v}=this.hls;if(m.length===1)return 0;const L=m[c],y=!!(L!=null&&(l=L.details)!=null&&l.live),b=p===-1||h===-1;let T,I="SDR",A=L?.frameRate||0;const{audioPreference:D,videoPreference:P}=v,_=this.audioTracksByGroup||(this.audioTracksByGroup=Cr(g));if(b){if(this.firstSelection!==-1)return this.firstSelection;const B=this.codecTiers||(this.codecTiers=_r(m,_,t,i)),V=Dr(B,I,e,D,P),{codecSet:W,videoRanges:X,minFramerate:O,minBitrate:F,preferHDR:Y}=V;T=W,I=Y?X[X.length-1]:X[0],A=O,e=Math.max(e,F),S.log(`[abr] picked start tier ${JSON.stringify(V)}`)}else T=L?.codecSet,I=L?.videoRange;const C=f?f.duration:u?u.duration:0,$=this.bwEstimator.getEstimateTTFB()/1e3,M=[];for(let B=i;B>=t;B--){var U;const V=m[B],W=B>c;if(!V)continue;if(T&&V.codecSet!==T||I&&V.videoRange!==I||W&&A>V.frameRate||!W&&A>0&&A<V.frameRate||V.supportedResult&&!((U=V.supportedResult.decodingInfoResults)!=null&&U[0].smooth)){M.push(B);continue}const X=V.details,O=(f?X?.partTarget:X?.averagetargetduration)||C;let F;W?F=o*e:F=n*e;const Y=C&&s>=C*2&&r===0?m[B].averageBitrate:m[B].maxBitrate,H=this.getTimeToLoadFrag($,F,Y*O,X===void 0);if(F>=Y&&(B===h||V.loadError===0&&V.fragmentError===0)&&(H<=$||!k(H)||y&&!this.bitrateTestDelay||H<d)){const se=this.forcedAutoLevel;return B!==p&&(se===-1||se!==p)&&(M.length&&S.trace(`[abr] Skipped level(s) ${M.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${m[M[0]].codecs}" ${m[M[0]].videoRange}; not compatible with "${L.codecs}" ${I}`),S.info(`[abr] switch candidate:${c}->${B} adjustedbw(${Math.round(F)})-bitrate=${Math.round(F-Y)} ttfb:${$.toFixed(1)} avgDuration:${O.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${H.toFixed(1)} firstSelection:${b} codecSet:${T} videoRange:${I} hls.loadLevel:${p}`)),b&&(this.firstSelection=B),B}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:i}=this.hls,s=Math.min(Math.max(e,i),t);this._nextAutoLevel!==s&&(this.nextAutoLevelKey="",this._nextAutoLevel=s)}}const Pr={length:0,start:()=>0,end:()=>0};class J{static isBuffered(e,t){try{if(e){const i=J.getBuffered(e);for(let s=0;s<i.length;s++)if(t>=i.start(s)&&t<=i.end(s))return!0}}catch{}return!1}static bufferInfo(e,t,i){try{if(e){const s=J.getBuffered(e),r=[];let n;for(n=0;n<s.length;n++)r.push({start:s.start(n),end:s.end(n)});return this.bufferedInfo(r,t,i)}}catch{}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.sort(function(d,h){const c=d.start-h.start;return c||h.end-d.end});let s=[];if(i)for(let d=0;d<e.length;d++){const h=s.length;if(h){const c=s[h-1].end;e[d].start-c<i?e[d].end>c&&(s[h-1].end=e[d].end):s.push(e[d])}else s.push(e[d])}else s=e;let r=0,n,o=t,l=t;for(let d=0;d<s.length;d++){const h=s[d].start,c=s[d].end;if(t+i>=h&&t<c)o=h,l=c,r=l-t;else if(t+i<h){n=h;break}}return{len:r,start:o||0,end:l||0,nextStart:n}}static getBuffered(e){try{return e.buffered}catch(t){return S.log("failed to get media.buffered",t),Pr}}}class Fr{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,i){const s=this.queues[t];s.push(e),s.length===1&&!i&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const i=new Promise(r=>{t=r}),s={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(s,e),i}executeNext(e){const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(s){S.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${s}`),i.onError(s);const r=this.buffers[e];r!=null&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const Ai=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class Or{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=i=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=i=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:i,mediaSource:s}=this;this.log("Media source opened"),i&&(i.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(x.MEDIA_ATTACHED,{media:i,mediaSource:s})),s&&s.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:i,_objectUrl:s}=this;i!==s&&S.error(`Media element src was set while attaching MediaSource (${s} > ${i})`)},this.hls=e;const t="[buffer-controller]";this.appendSource=Ws(Re(e.config.preferManagedMediaSource)),this.log=S.log.bind(S,t),this.warn=S.warn.bind(S,t),this.error=S.error.bind(S,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(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.BUFFER_RESET,this.onBufferReset,this),e.on(x.BUFFER_APPENDING,this.onBufferAppending,this),e.on(x.BUFFER_CODECS,this.onBufferCodecs,this),e.on(x.BUFFER_EOS,this.onBufferEos,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(x.FRAG_PARSED,this.onFragParsed,this),e.on(x.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.BUFFER_RESET,this.onBufferReset,this),e.off(x.BUFFER_APPENDING,this.onBufferAppending,this),e.off(x.BUFFER_CODECS,this.onBufferCodecs,this),e.off(x.BUFFER_EOS,this.onBufferEos,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(x.FRAG_PARSED,this.onFragParsed,this),e.off(x.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new Fr(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 i=2;t.audio&&!t.video||t.altAudio,i=1,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=i,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const i=this.media=t.media,s=Re(this.appendSource);if(i&&s){var r;const n=this.mediaSource=new s;this.log(`created media source: ${(r=n.constructor)==null?void 0:r.name}`),n.addEventListener("sourceopen",this._onMediaSourceOpen),n.addEventListener("sourceended",this._onMediaSourceEnded),n.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.addEventListener("startstreaming",this._onStartStreaming),n.addEventListener("endstreaming",this._onEndStreaming));const o=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{i.removeAttribute("src");const l=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||l&&n instanceof l,Ri(i),kr(i,o),i.load()}catch{i.src=o}else i.src=o;i.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:i}=this;if(t){if(this.log("media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(s){this.warn(`onMediaDetaching: ${s.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),i&&self.URL.revokeObjectURL(i),this.mediaSrc===i?(e.removeAttribute("src"),this.appendSource&&Ri(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(x.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{this.resetBuffer(e)}),this._initSourceBuffer()}resetBuffer(e){const t=this.sourceBuffer[e];try{if(t){var i;this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}}catch(s){this.warn(`onBufferReset ${e}`,s)}}onBufferCodecs(e,t){const i=this.getSourceBufferTypes().length,s=Object.keys(t);if(s.forEach(n=>{if(i){const l=this.tracks[n];if(l&&typeof l.buffer.changeType=="function"){var o;const{id:d,codec:h,levelCodec:c,container:u,metadata:f}=t[n],m=Zt(l.codec,l.levelCodec),g=m?.replace(Ai,"$1");let p=Zt(h,c);const v=(o=p)==null?void 0:o.replace(Ai,"$1");if(p&&g!==v){n.slice(0,5)==="audio"&&(p=Ve(p,this.appendSource));const L=`${u};codecs=${p}`;this.appendChangeType(n,L),this.log(`switching codec ${m} to ${p}`),this.tracks[n]={buffer:l.buffer,codec:h,container:u,levelCodec:c,metadata:f,id:d}}}}else this.pendingTracks[n]=t[n]}),i)return;const r=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==r&&(this.log(`${r} bufferCodec event(s) expected ${s.join(",")}`),this.bufferCodecEventsExpected=r),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:i}=this,s={execute:()=>{const r=this.sourceBuffer[e];r&&(this.log(`changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),i.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:r=>{this.warn(`Failed to change ${e} SourceBuffer type`,r)}};i.append(s,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:i,operationQueue:s,tracks:r}=this,{data:n,type:o,frag:l,part:d,chunkMeta:h}=t,c=h.buffering[o],u=self.performance.now();c.start=u;const f=l.stats.buffering,m=d?d.stats.buffering:null;f.start===0&&(f.start=u),m&&m.start===0&&(m.start=u);const g=r.audio;let p=!1;o==="audio"&&g?.container==="audio/mpeg"&&(p=!this.lastMpegAudioChunk||h.id===1||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const v=l.start,L={execute:()=>{if(c.executeStart=self.performance.now(),p){const y=this.sourceBuffer[o];if(y){const b=v-y.timestampOffset;Math.abs(b)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${v} (delta: ${b}) sn: ${l.sn})`),y.timestampOffset=v)}}this.appendExecutor(n,o)},onStart:()=>{},onComplete:()=>{const y=self.performance.now();c.executeEnd=c.end=y,f.first===0&&(f.first=y),m&&m.first===0&&(m.first=y);const{sourceBuffer:b}=this,T={};for(const I in b)T[I]=J.getBuffered(b[I]);this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(x.BUFFER_APPENDED,{type:o,frag:l,part:d,chunkMeta:h,parent:l.type,timeRanges:T})},onError:y=>{const b={type:K.MEDIA_ERROR,parent:l.type,details:R.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:d,chunkMeta:h,error:y,err:y,fatal:!1};if(y.code===DOMException.QUOTA_EXCEEDED_ERR)b.details=R.BUFFER_FULL_ERROR;else{const T=++this.appendErrors[o];b.details=R.BUFFER_APPEND_ERROR,this.warn(`Failed ${T}/${i.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer`),T>=i.config.appendErrorMaxRetry&&(b.fatal=!0)}i.trigger(x.ERROR,b)}};s.append(L,o,!!this.pendingTracks[o])}onBufferFlushing(e,t){const{operationQueue:i}=this,s=r=>({execute:this.removeExecutor.bind(this,r,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(x.BUFFER_FLUSHED,{type:r})},onError:n=>{this.warn(`Failed to remove from ${r} SourceBuffer`,n)}});t.type?i.append(s(t.type),t.type):this.getSourceBufferTypes().forEach(r=>{i.append(s(r),r)})}onFragParsed(e,t){const{frag:i,part:s}=t,r=[],n=s?s.elementaryStreams:i.elementaryStreams;n[Q.AUDIOVIDEO]?r.push("audiovideo"):(n[Q.AUDIO]&&r.push("audio"),n[Q.VIDEO]&&r.push("video"));const o=()=>{const l=self.performance.now();i.stats.buffering.end=l,s&&(s.stats.buffering.end=l);const d=s?s.stats:i.stats;this.hls.trigger(x.FRAG_BUFFERED,{frag:i,part:s,stats:d,id:i.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(o,r)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((s,r)=>{const n=this.sourceBuffer[r];return n&&(!t.type||t.type===r)&&(n.ending=!0,n.ended||(n.ended=!0,this.log(`${r} sourceBuffer now EOS`))),s&&!!(!n||n.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(r=>{const n=this.sourceBuffer[r];n&&(n.ending=!1)});const{mediaSource:s}=this;if(!s||s.readyState!=="open"){s&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${s.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),s.endOfStream()}))}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:i}=this;if(!i||t===null||!this.getSourceBufferTypes().length)return;const r=e.config,n=i.currentTime,o=t.levelTargetDuration,l=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(k(l)&&l>0){const d=Math.max(l,o),h=Math.floor(n/o)*o-d;this.flushBackBuffer(n,o,h)}if(k(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const d=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),h=Math.max(d,o),c=Math.floor(n/o)*o+h;this.flushFrontBuffer(n,o,c)}}flushBackBuffer(e,t,i){const{details:s,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(o=>{const l=r[o];if(l){const d=J.getBuffered(l);if(d.length>0&&i>d.start(0)){if(this.hls.trigger(x.BACK_BUFFER_REACHED,{bufferEnd:i}),s!=null&&s.live)this.hls.trigger(x.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(l.ended&&d.end(d.length-1)-e<t*2){this.log(`Cannot flush ${o} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(x.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:o})}}})}flushFrontBuffer(e,t,i){const{sourceBuffer:s}=this;this.getSourceBufferTypes().forEach(n=>{const o=s[n];if(o){const l=J.getBuffered(o),d=l.length;if(d<2)return;const h=l.start(d-1),c=l.end(d-1);if(i>h||e>=h&&e<=c)return;if(o.ended&&e-c<2*t){this.log(`Cannot flush ${n} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(x.BUFFER_FLUSHING,{startOffset:h,endOffset:1/0,type:n})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:t,media:i,mediaSource:s}=this,r=e.fragments[0].start+e.totalduration,n=i.duration,o=k(s.duration)?s.duration:0;e.live&&t.config.liveDurationInfinity?(s.duration=1/0,this.updateSeekableRange(e)):(r>o&&r>n||!k(n))&&(this.log(`Updating Media Source duration to ${r.toFixed(3)}`),s.duration=r)}updateSeekableRange(e){const t=this.mediaSource,i=e.fragments;if(i.length&&e.live&&t!=null&&t.setLiveSeekableRange){const r=Math.max(0,i[0].start),n=Math.max(r,r+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${r}-${n}.`),t.setLiveSeekableRange(r,n)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:i}=this,s=Object.keys(i).length;if(s&&(!e||s===2||"audiovideo"in i)){this.createSourceBuffers(i),this.pendingTracks={};const r=this.getSourceBufferTypes();if(r.length)this.hls.trigger(x.BUFFER_CREATED,{tracks:this.tracks}),r.forEach(n=>{t.executeNext(n)});else{const n=new Error("could not create source buffer for media codec(s)");this.hls.trigger(x.ERROR,{type:K.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:n,reason:n.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(const r in e)if(!t[r]){var s;const n=e[r];if(!n)throw Error(`source buffer exists for track ${r}, however track does not`);let o=((s=n.levelCodec)==null?void 0:s.indexOf(","))===-1?n.levelCodec:n.codec;o&&r.slice(0,5)==="audio"&&(o=Ve(o,this.appendSource));const l=`${n.container};codecs=${o}`;this.log(`creating sourceBuffer(${l})`);try{const d=t[r]=i.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",(c,u)=>{const f=u.removedRanges;f!=null&&f.length&&this.hls.trigger(x.BUFFER_FLUSHED,{type:r})}),this.tracks[r]={buffer:d,codec:o,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(d){this.error(`error while trying to add sourceBuffer: ${d.message}`),this.hls.trigger(x.ERROR,{type:K.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:d,sourceBufferName:r,mimeType:l})}}}get mediaSrc(){var e;const t=((e=this.media)==null?void 0:e.firstChild)||this.media;return t?.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const{operationQueue:i}=this;i.current(e).onComplete(),i.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var i;const s=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(i=this.mediaSource)==null?void 0:i.readyState}`);this.error(`${s}`,t),this.hls.trigger(x.ERROR,{type:K.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});const r=this.operationQueue.current(e);r&&r.onError(s)}removeExecutor(e,t,i){const{media:s,mediaSource:r,operationQueue:n,sourceBuffer:o}=this,l=o[e];if(!s||!r||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),n.shiftAndExecuteNext(e);return}const d=k(s.duration)?s.duration:1/0,h=k(r.duration)?r.duration:1/0,c=Math.max(0,t),u=Math.min(i,d,h);u>c&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${c},${u}] from the ${e} SourceBuffer`),l.remove(c,u)):n.shiftAndExecuteNext(e)}appendExecutor(e,t){const i=this.sourceBuffer[t];if(!i){if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);return}i.ended=!1,i.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:i}=this,s=t.map(r=>i.appendBlocker(r));Promise.all(s).then(()=>{e(),t.forEach(r=>{const n=this.sourceBuffer[r];n!=null&&n.updating||i.shiftAndExecuteNext(r)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,i){const s=this.sourceBuffer[e];if(!s)return;const r=i.bind(this,e);this.listeners[e].push({event:t,listener:r}),s.addEventListener(t,r)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(i=>{t.removeEventListener(i.event,i.listener)})}}function Ri(a){const e=a.querySelectorAll("source");[].slice.call(e).forEach(t=>{a.removeChild(t)})}function kr(a,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,a.appendChild(t)}class wt{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(x.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.BUFFER_CODECS,this.onBufferCodecs,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(x.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.BUFFER_CODECS,this.onBufferCodecs,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&k(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){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&S.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,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 i=t.filter((s,r)=>this.isLevelAllowed(s)&&r<=e);return this.clientRect=null,wt.getMaxLevelByMediaSize(i,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 i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,!t.width&&!t.height&&(t.width=i.right-i.left||e.width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(i=>e.bitrate===i.bitrate&&e.width===i.width&&e.height===i.height)}static getMaxLevelByMediaSize(e,t,i){if(!(e!=null&&e.length))return-1;const s=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let r=e.length-1;const n=Math.max(t,i);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=n||l.height>=n)&&s(l,e[o+1])){r=o;break}}return r}}class Mr{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(x.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const i=this.hls.config;if(i.capLevelOnFPSDrop){const s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,i){const s=performance.now();if(t){if(this.lastTime){const r=s-this.lastTime,n=i-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*n/r,d=this.hls;if(d.trigger(x.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:i}),l>0&&n>d.config.fpsDroppedMonitoringThreshold*o){let h=d.currentLevel;S.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=h)&&(h=h-1,d.trigger(x.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:d.currentLevel}),d.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,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)}}const Nr=3e5;class Br{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=S.log.bind(S,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(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(i=>i!==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:i}=t;i!==null&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:i}=t;if(i?.action===ie.SendAlternateToPenaltyBox&&i.flags===ce.MoveAllAlternatesMatchingHost){const s=this.levels;let r=this.pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:d}=t.context;o&&s?n=this.getPathwayForGroupId(o,d,n):l&&(n=l)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&s&&(r=s.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==n),i.resolved||S.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${s&&s.length} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(r=>{s-i[r]>Nr&&delete i[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in i)continue;if(n===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,vi(t),this.hls.trigger(x.LEVELS_UPDATED,{levels:t});const d=this.hls.levels[o];l&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let r=0;r<s.length;r++)if(t===j.AUDIO_TRACK&&s[r].hasAudioGroup(e)||t===j.SUBTITLE_TRACK&&s[r].hasSubtitleGroup(e))return s[r].pathwayId;return i}clonePathways(e){const t=this.levels;if(!t)return;const i={},s={};e.forEach(r=>{const{ID:n,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(h=>h.pathwayId===n))return;const d=this.getLevelsForPathway(o).map(h=>{const c=new Z(h.attrs);c["PATHWAY-ID"]=n;const u=c.AUDIO&&`${c.AUDIO}_clone_${n}`,f=c.SUBTITLES&&`${c.SUBTITLES}_clone_${n}`;u&&(i[c.AUDIO]=u,c.AUDIO=u),f&&(s[c.SUBTITLES]=f,c.SUBTITLES=f);const m=Ii(h.uri,c["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),g=new pt({attrs:c,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 p=1;p<h.audioGroups.length;p++)g.addGroupId("audio",`${h.audioGroups[p]}_clone_${n}`);if(h.subtitleGroups)for(let p=1;p<h.subtitleGroups.length;p++)g.addGroupId("text",`${h.subtitleGroups[p]}_clone_${n}`);return g});t.push(...d),bi(this.audioTracks,i,l,n),bi(this.subtitleTracks,s,l,n)})}loadSteeringManifest(e){const t=this.hls.config,i=t.loader;this.loader&&this.loader.destroy(),this.loader=new i(t);let s;try{s=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(s.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;s.searchParams.set("_HLS_pathway",this.pathwayId),s.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:s.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},l={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(h,c,u,f)=>{this.log(`Loaded steering manifest: "${s}"`);const m=h.data;if(m.VERSION!==1){this.log(`Steering VERSION ${m.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=m.TTL;const{"RELOAD-URI":g,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":v}=m;if(g)try{this.uri=new self.URL(g,s).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${g}`);return}this.scheduleRefresh(this.uri||u.url),p&&this.clonePathways(p);const L={steeringManifest:m,url:s.toString()};this.hls.trigger(x.STEERING_MANIFEST_LOADED,L),v&&this.updatePathwayPriority(v)},onError:(h,c,u,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${c.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${c.url} no longer available`);return}let m=this.timeToLoad*1e3;if(h.code===429){const g=this.loader;if(typeof g?.getResponseHeader=="function"){const p=g.getResponseHeader("Retry-After");p&&(m=parseFloat(p)*1e3)}this.log(`Steering manifest ${c.url} rate limited`);return}this.scheduleRefresh(this.uri||c.url,m)},onTimeout:(h,c,u)=>{this.log(`Timeout loading steering manifest (${c.url})`),this.scheduleRefresh(this.uri||c.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,l,d)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var i;const s=(i=this.hls)==null?void 0:i.media;if(s&&!s.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function bi(a,e,t,i){a&&Object.keys(e).forEach(s=>{const r=a.filter(n=>n.groupId===s).map(n=>{const o=ae({},n);return o.details=void 0,o.attrs=new Z(o.attrs),o.url=o.attrs.URI=Ii(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[s],o.attrs["PATHWAY-ID"]=i,o});a.push(...r)})}function Ii(a,e,t,i){const{HOST:s,PARAMS:r,[t]:n}=i;let o;e&&(o=n?.[e],o&&(a=o));const l=new self.URL(a);return s&&!o&&(l.host=s),r&&Object.keys(r).sort().forEach(d=>{d&&l.searchParams.set(d,r[d])}),l.href}const Ur=/^age:\s*[\d.]+\s*$/im;class Di{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 ke,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null,this.stats=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){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=i,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!this.stats.aborted)return r(i,t.url)}).catch(n=>(i.open("GET",t.url,!0),r(i,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(n=>{this.callbacks.onError({code:i.status,text:n.message},t,i,s)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);const s=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=i.loadPolicy;if(s)for(const o in s)e.setRequestHeader(o,s[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),i.timeout=r&&k(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:i}=this;if(!e||!t)return;const s=t.readyState,r=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.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-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const n=t.status,o=t.responseType!=="text";if(n>=200&&n<300&&(o&&t.response||t.responseText!==null)){i.loading.end=Math.max(self.performance.now(),i.loading.first);const l=o?t.response:t.responseText,d=t.responseType==="arraybuffer"?l.byteLength:l.length;if(i.loaded=i.total=d,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first),!this.callbacks)return;const h=this.callbacks.onProgress;if(h&&h(i,e,l,t),!this.callbacks)return;const c={url:t.responseURL,data:l,code:n};this.callbacks.onSuccess(c,i,e,t)}else{const l=r.loadPolicy.errorRetry,d=i.retry,h={url:e.url,data:void 0,code:n};je(l,d,!1,h)?this.retry(l):(S.error(`${n} while loading ${e.url}`),this.callbacks.onError({code:n,text:t.statusText},e,t,i))}}}loadtimeout(){var e;const t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,i=this.stats.retry;if(je(t,i,!0))this.retry(t);else{var s;S.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=vt(e,i.retry),i.retry++,S.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Ur.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}}class $r{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let i;if(e.length)e.length===1?i=e[0]:i=Gr(e,t);else return new Uint8Array(0);return this.reset(),i}reset(){this.chunks.length=0,this.dataLength=0}}function Gr(a,e){const t=new Uint8Array(e);let i=0;for(let s=0;s<a.length;s++){const r=a[s];t.set(r,i),i+=r.length}return t}function Vr(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Hr=/(\d+)-(\d+)\/(\d+)/;class Ci{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||jr,this.controller=new self.AbortController,this.stats=new ke}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(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now();const r=Kr(e,this.controller.signal),n=i.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=d&&k(d)?d:h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},t.timeout),self.fetch(this.request).then(c=>{this.response=this.loader=c;const u=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),i.onTimeout(s,e,this.response)},h-(u-s.loading.start)),!c.ok){const{status:f,statusText:m}=c;throw new zr(m||"fetch, bad network response",f,c)}return s.loading.first=u,s.total=Yr(c.headers)||s.total,n&&k(t.highWaterMark)?this.loadProgressively(c,s,e,t.highWaterMark,n):o?c.arrayBuffer():e.responseType==="json"?c.json():c.text()}).then(c=>{const u=this.response;if(!u)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const f=c[l];f&&(s.loaded=s.total=f);const m={url:u.url,data:c,code:u.status};n&&!k(t.highWaterMark)&&n(s,e,c,u),i.onSuccess(m,s,e,u)}).catch(c=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const u=c&&c.code||0,f=c?c.message:null;i.onError({code:u,text:f},e,c?c.details:null,s)})}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,i,s=0,r){const n=new $r,o=e.body.getReader(),l=()=>o.read().then(d=>{if(d.done)return n.dataLength&&r(t,i,n.flush(),e),Promise.resolve(new ArrayBuffer(0));const h=d.value,c=h.length;return t.loaded+=c,c<s||n.dataLength?(n.push(h),n.dataLength>=s&&r(t,i,n.flush(),e)):r(t,i,h,e),l()}).catch(()=>Promise.reject());return l()}}function Kr(a,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ae({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function Wr(a){const e=Hr.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Yr(a){const e=a.get("Content-Range");if(e){const i=Wr(e);if(k(i))return i}const t=a.get("Content-Length");if(t)return parseInt(t)}function jr(a,e){return new self.Request(a.url,e)}class zr extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const qr={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},_i=oe(oe({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:60*1e3*1e3,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:Di,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:wr,bufferController:Or,capLevelController:wt,errorController:Lr,fpsController:Mr,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:null,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!1,certLoadPolicy:{default:qr},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},Xr()),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:Br});function Xr(){return{cueHandler:Ts,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Qr(a,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(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const t=yt(a),i=["manifest","level","frag"],s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(r=>{const n=`${r==="level"?"playlist":r}LoadPolicy`,o=e[n]===void 0,l=[];s.forEach(d=>{const h=`${r}Loading${d}`,c=e[h];if(c!==void 0&&o){l.push(h);const u=t[n].default;switch(e[n]={default:u},d){case"TimeOut":u.maxLoadTimeMs=c,u.maxTimeToFirstByteMs=c;break;case"MaxRetry":u.errorRetry.maxNumRetry=c,u.timeoutRetry.maxNumRetry=c;break;case"RetryDelay":u.errorRetry.retryDelayMs=c,u.timeoutRetry.retryDelayMs=c;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=c,u.timeoutRetry.maxRetryDelayMs=c;break}}}),l.length&&S.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${n}": ${JSON.stringify(e[n])}`)}),oe(oe({},t),e)}function yt(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(yt):Object.keys(a).reduce((e,t)=>(e[t]=yt(a[t]),e),{}):a}function Jr(a){const e=a.loader;e!==Ci&&e!==Di?(S.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):Vr()&&(a.loader=Ci,a.progressive=!0,a.enableSoftwareAES=!0,S.log("[config]: Progressive streaming enabled, using FetchLoader"))}let Et;class Zr extends Ar{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(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this),e.on(x.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this),e.off(x.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 i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let o=!1,l=!1,d=!1;t.levels.forEach(h=>{var c,u;const f=h.attrs;let{audioCodec:m,videoCodec:g}=h;((c=m)==null?void 0:c.indexOf("mp4a.40.34"))!==-1&&(Et||(Et=/chrome|firefox/i.test(navigator.userAgent)),Et&&(h.audioCodec=m=void 0)),m&&(h.audioCodec=m=Ve(m,i)),((u=g)==null?void 0:u.indexOf("avc1"))===0&&(g=h.videoCodec=qs(g));const{width:p,height:v,unknownCodecs:L}=h;if(o||(o=!!(p&&v)),l||(l=!!g),d||(d=!!m),L!=null&&L.length||m&&!dt(m,"audio",i)||g&&!dt(g,"video",i))return;const{CODECS:y,"FRAME-RATE":b,"HDCP-LEVEL":T,"PATHWAY-ID":I,RESOLUTION:A,"VIDEO-RANGE":D}=f,_=`${`${I||"."}-`}${h.bitrate}-${A}-${b}-${y}-${D}-${T}`;if(r[_])if(r[_].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const C=n[_]+=1;h.attrs["PATHWAY-ID"]=new Array(C+1).join(".");const $=new pt(h);r[_]=$,s.push($)}else r[_].addGroupId("audio",f.AUDIO),r[_].addGroupId("text",f.SUBTITLES);else{const C=new pt(h);r[_]=C,n[_]=1,s.push(C)}}),this.filterAndSortMediaOptions(s,t,o,l,d)}filterAndSortMediaOptions(e,t,i,s,r){let n=[],o=[],l=e;if((i||s)&&r&&(l=l.filter(({videoCodec:m,videoRange:g,width:p,height:v})=>(!!m||!!(p&&v))&&cr(g))),l.length===0){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(x.ERROR,{type:K.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:m,reason:m.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:m}=this.hls.config;n=t.audioTracks.filter(g=>!g.audioCodec||dt(g.audioCodec,"audio",m)),wi(n)}t.subtitles&&(o=t.subtitles,wi(o));const d=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(i&&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 Ke.indexOf(m.videoRange)-Ke.indexOf(g.videoRange);if(m.videoCodec!==g.videoCodec){const p=Jt(m.videoCodec),v=Jt(g.videoCodec);if(p!==v)return v-p}if(m.uri===g.uri&&m.codecSet!==g.codecSet){const p=Ge(m.codecSet),v=Ge(g.codecSet);if(p!==v)return v-p}return m.averageBitrate!==g.averageBitrate?m.averageBitrate-g.averageBitrate:0});let h=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length)){for(let m=0;m<d.length;m++)if(d[m].pathwayId===l[0].pathwayId){h=d[m];break}}this._levels=l;for(let m=0;m<l.length;m++)if(l[m]===h){var c;this._firstLevel=m;const g=h.bitrate,p=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${g}`),((c=this.hls.userConfig)==null?void 0:c.abrEwmaDefaultEstimate)===void 0){const v=Math.min(g,this.hls.config.abrEwmaDefaultEstimateMax);v>p&&p===_i.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=v)}break}const u=r&&!s,f={levels:l,audioTracks:n,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:s,altAudio:!u&&n.some(m=>!!m.url)};this.hls.trigger(x.MANIFEST_PARSED,f),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),c=e<0;if(this.hls.trigger(x.ERROR,{type:K.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:c,error:h,reason:h.message}),c)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,r=s?s.attrs["PATHWAY-ID"]:void 0,n=t[e],o=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,i===e&&n.details&&s&&r===o)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${o?" with Pathway "+o:""} from level ${i}${r?" with Pathway "+r:""}`);const l={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(x.LEVEL_SWITCHING,l);const d=n.details;if(!d||d.live){const h=this.switchParams(n.uri,s?.details,d);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===j.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===z.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(r=>!!i[r]))return;const s=this._levels[t.level];s!=null&&s.loadError&&(this.log(`Resetting level error count of ${s.loadError} on frag buffered`),s.loadError=0)}}onLevelLoaded(e,t){var i;const{level:s,details:r}=t,n=this._levels[s];if(!n){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}s===this.currentLevelIndex?(n.fragmentError===0&&(n.loadError=0),this.playlistLoaded(s,t,n.details)):(i=t.deliveryDirectives)!=null&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,i=this.currentLevel;if(i&&this.shouldLoadPlaylist(i)){let s=i.uri;if(e)try{s=e.addDirectives(s)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}const r=i.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${e?.msn!==void 0?" at sn "+e.msn+" part "+e.part:""} with${r?" Pathway "+r:""} ${s}`),this.clearTimer(),this.hls.trigger(x.LEVEL_LOADING,{url:s,level:t,pathwayId:i.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const i=this._levels.filter((s,r)=>r!==e?!0:(this.steering&&this.steering.removeLevel(s),s===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,s.details&&s.details.fragments.forEach(n=>n.level=-1)),!1));vi(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(x.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(x.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function wi(a){const e={};a.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}var ne={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class en{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(x.BUFFER_APPENDED,this.onBufferAppended,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this),e.on(x.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(x.BUFFER_APPENDED,this.onBufferAppended,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this),e.off(x.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const i=this.activePartLists[t];if(i)for(let s=i.length;s--;){const r=i[s];if(!r)break;const n=r.end;if(r.start<=e&&n!==null&&e<=n)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:i}=this,s=Object.keys(i);for(let r=s.length;r--;){const n=i[s[r]];if(n?.body.type===t&&n.buffered){const o=n.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,i,s){this.timeRanges&&(this.timeRanges[e]=t);const r=s?.fragment.sn||-1;Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o||r>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===i&&this.removeFragment(o.body);return}const l=o.range[e];l&&l.time.some(d=>{const h=!this.isTimeBuffered(d.startPTS,d.endPTS,t);return h&&this.removeFragment(o.body),h})})}detectPartialFragments(e){const t=this.timeRanges,{frag:i,part:s}=e;if(!t||i.sn==="initSegment")return;const r=De(i),n=this.fragments[r];if(!n||n.buffered&&i.gap)return;const o=!i.relurl;Object.keys(t).forEach(l=>{const d=i.elementaryStreams[l];if(!d)return;const h=t[l],c=o||d.partial===!0;n.range[l]=this.getBufferedTimes(i,s,c,h)}),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=i.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),ze(n)||this.removeParts(i.sn-1,i.type)):this.removeFragment(n.body)}removeParts(e,t){const i=this.activePartLists[t];i&&(this.activePartLists[t]=i.filter(s=>s.fragment.sn>=e))}fragBuffered(e,t){const i=De(e);let s=this.fragments[i];!s&&t&&(s=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)}getBufferedTimes(e,t,i,s){const r={time:[],partial:i},n=e.start,o=e.end,l=e.minEndPTS||o,d=e.maxStartPTS||n;for(let h=0;h<s.length;h++){const c=s.start(h)-this.bufferPadding,u=s.end(h)+this.bufferPadding;if(d>=c&&l<=u){r.time.push({startPTS:Math.max(n,s.start(h)),endPTS:Math.min(o,s.end(h))});break}else if(n<u&&o>c){const f=Math.max(n,s.start(h)),m=Math.min(o,s.end(h));m>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:m}))}else if(o<=c)break}return r}getPartialFragment(e){let t=null,i,s,r,n=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(d=>{const h=l[d];h&&ze(h)&&(s=h.body.start-o,r=h.body.end+o,e>=s&&e<=r&&(i=Math.min(e-s,r-e),n<=i&&(t=h.body,n=i)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||ze(t))}getState(e){const t=De(e),i=this.fragments[t];return i?i.buffered?ze(i)?ne.PARTIAL:ne.OK:ne.APPENDING:ne.NOT_LOADED}isTimeBuffered(e,t,i){let s,r;for(let n=0;n<i.length;n++){if(s=i.start(n)-this.bufferPadding,r=i.end(n)+this.bufferPadding,e>=s&&t<=r)return!0;if(t<=s)return!1}return!1}onFragLoaded(e,t){const{frag:i,part:s}=t;if(i.sn==="initSegment"||i.bitrateTest)return;const r=s?null:t,n=De(i);this.fragments[n]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:i,part:s,timeRanges:r}=t;if(i.sn==="initSegment")return;const n=i.type;if(s){let o=this.activePartLists[n];o||(this.activePartLists[n]=o=[]),o.push(s)}this.timeRanges=r,Object.keys(r).forEach(o=>{const l=r[o];this.detectEvictedFragments(o,l,n,s)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=De(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o)return;const l=o.body;l.type!==i||s&&!l.gap||l.start<t&&l.end>e&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(e){const t=De(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const i=this.activePartLists[e.type];if(i){const s=e.sn;this.activePartLists[e.type]=i.filter(r=>r.fragment.sn!==s)}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 ze(a){var e,t,i;return a.buffered&&(a.body.gap||((e=a.range.video)==null?void 0:e.partial)||((t=a.range.audio)==null?void 0:t.partial)||((i=a.range.audiovideo)==null?void 0:i.partial))}function De(a){return`${a.type}_${a.level}_${a.sn}`}const Pi=Math.pow(2,17);class tn{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 i=e.url;if(!i)return Promise.reject(new xe({type:K.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(f=>f[0]==="GAP")){l(Oi(e));return}else e.gap=!1;const d=this.loader=e.loader=r?new r(s):new n(s),h=Fi(e),c=Ei(s.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Pi};e.stats=d.stats,d.load(h,u,{onSuccess:(f,m,g,p)=>{this.resetLoader(e,d);let v=f.data;g.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),o({frag:e,part:null,payload:v,networkDetails:p})},onError:(f,m,g,p)=>{this.resetLoader(e,d),l(new xe({type:K.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:oe({url:i,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:p}))},onAbort:(f,m,g)=>{this.resetLoader(e,d),l(new xe({type:K.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,d),l(new xe({type:K.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:g,stats:f}))},onProgress:(f,m,g,p)=>{t&&t({frag:e,part:null,payload:g,networkDetails:p})}})})}loadPart(e,t,i){this.abort();const s=this.config,r=s.fLoader,n=s.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(Oi(e,t));return}const d=this.loader=e.loader=r?new r(s):new n(s),h=Fi(e,t),c=Ei(s.fragLoadPolicy.default),u={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Pi};t.stats=d.stats,d.load(h,u,{onSuccess:(f,m,g,p)=>{this.resetLoader(e,d),this.updateStatsFromPart(e,t);const v={frag:e,part:t,payload:f.data,networkDetails:p};i(v),o(v)},onError:(f,m,g,p)=>{this.resetLoader(e,d),l(new xe({type:K.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:oe({url:h.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:g,stats:p}))},onAbort:(f,m,g)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,d),l(new xe({type:K.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:g,stats:f}))},onTimeout:(f,m,g)=>{this.resetLoader(e,d),l(new xe({type:K.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:g,stats:f}))}})})}updateStatsFromPart(e,t){const i=e.stats,s=t.stats,r=s.total;if(i.loaded+=s.loaded,r){const l=Math.round(e.duration/t.duration),d=Math.min(Math.round(i.loaded/r),l),c=(l-d)*Math.round(i.loaded/d);i.total=i.loaded+c}else i.total=Math.max(i.loaded,i.total);const n=i.loading,o=s.loading;n.start?n.first+=o.first-o.start:(n.start=o.start,n.first=o.first),n.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Fi(a,e=null){const t=e||a,i={frag:a,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},s=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(k(s)&&k(r)){var n;let o=s,l=r;if(a.sn==="initSegment"&&((n=a.decryptdata)==null?void 0:n.method)==="AES-128"){const d=r-s;d%16&&(l=r+(16-d%16)),s!==0&&(i.resetIV=!0,o=s-16)}i.rangeStart=o,i.rangeEnd=l}return i}function Oi(a,e){const t=new Error(`GAP ${a.gap?"tag":"attribute"} found`),i={type:K.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:a,error:t,networkDetails:null};return e&&(i.part=e),(e||a).stats.aborted=!0,new xe(i)}class xe extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class sn{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyUriToKeyInfo){const s=this.keyUriToKeyInfo[i].loader;if(s){var t;if(e&&e!==((t=s.context)==null?void 0:t.frag.type))return;s.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=R.KEY_LOAD_ERROR,i,s,r){return new xe({type:K.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:i,networkDetails:s})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:i,cc:s}=e;for(let r=0;r<t.length;r++){const n=t[r];if(s<=n.cc&&(i==="initSegment"||n.sn==="initSegment"||i<n.sn)){this.emeController.selectKeySystemFormat(n).then(o=>{n.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const d=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,R.KEY_LOAD_ERROR,d))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let o=this.keyUriToKeyInfo[n];if((i=o)!=null&&i.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((s=o)!=null&&s.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(d=>(r.key=d.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[n]={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 r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const s=this.emeController.loadKey(i);if(s)return(e.keyLoadPromise=s.then(r=>(e.mediaKeySessionContext=r,i))).catch(r=>{throw e.keyLoadPromise=null,r})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=i.loader,r=new s(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},d=i.keyLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(u,f,m,g)=>{const{frag:p,keyInfo:v,url:L}=m;if(!p.decryptdata||v!==this.keyUriToKeyInfo[L])return o(this.createKeyLoadError(p,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),g));v.decryptdata.key=p.decryptdata.key=new Uint8Array(u.data),p.keyLoader=null,v.loader=null,n({frag:p,keyInfo:v})},onError:(u,f,m,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),m,oe({url:l.url,data:void 0},u)))},onTimeout:(u,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(u,f,m)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};r.load(l,h,c)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,r=i.loader;t.keyLoader===r&&(t.keyLoader=null,i.loader=null),delete this.keyUriToKeyInfo[s],r&&r.destroy()}}class rn{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?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class ki{constructor(e,t,i,s=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=qe(),this.buffering={audio:qe(),video:qe(),audiovideo:qe()},this.level=e,this.sn=t,this.id=i,this.size=s,this.part=r,this.partial=n}}function qe(){return{start:0,executeStart:0,executeEnd:0,end:0}}function Xe(a,e){for(let i=0,s=a.length;i<s;i++){var t;if(((t=a[i])==null?void 0:t.cc)===e)return a[i]}return null}function nn(a,e,t){return!!(e&&(t.endCC>t.startCC||a&&a.cc<t.startCC))}function an(a,e){const t=a.fragments,i=e.fragments;if(!i.length||!t.length){S.log("No fragments to align");return}const s=Xe(t,i[0].cc);if(!s||s&&!s.startPTS){S.log("No frag in previous level to align on");return}return s}function Mi(a,e){if(a){const t=a.start+e;a.start=a.startPTS=t,a.endPTS=t+a.duration}}function Ni(a,e){const t=e.fragments;for(let i=0,s=t.length;i<s;i++)Mi(t[i],a);e.fragmentHint&&Mi(e.fragmentHint,a),e.alignedSliding=!0}function on(a,e,t){e&&(ln(a,t,e),!t.alignedSliding&&e&&dn(t,e),!t.alignedSliding&&e&&!t.skippedSegments&&gi(e,t))}function ln(a,e,t){if(nn(a,t,e)){const i=an(t,e);i&&k(i.start)&&(S.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),Ni(i.start,e))}}function dn(a,e){if(!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=a.fragments,i=e.fragments;if(!t.length||!i.length)return;let s,r;const n=Math.min(e.endCC,a.endCC);e.startCC<n&&a.startCC<n&&(s=Xe(i,n),r=Xe(t,n)),(!s||!r)&&(s=i[Math.floor(i.length/2)],r=Xe(t,s.cc)||t[Math.floor(t.length/2)]);const o=s.programDateTime,l=r.programDateTime;if(!o||!l)return;const d=(l-o)/1e3-(r.start-s.start);Ni(d,a)}class hn{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 cn{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function un(a){const e=a.byteLength,t=e&&new DataView(a.buffer).getUint8(e-1);return t?Ae(a,0,e-t):a}class fn{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),i=new Uint32Array(4);for(let s=0;s<4;s++)i[s]=t.getUint32(s*4);return i}initTable(){const e=this.sBox,t=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],o=i[3],l=this.invSubMix,d=l[0],h=l[1],c=l[2],u=l[3],f=new Uint32Array(256);let m=0,g=0,p=0;for(p=0;p<256;p++)p<128?f[p]=p<<1:f[p]=p<<1^283;for(p=0;p<256;p++){let v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^v&255^99,e[m]=v,t[v]=m;const L=f[m],y=f[L],b=f[y];let T=f[v]*257^v*16843008;s[m]=T<<24|T>>>8,r[m]=T<<16|T>>>16,n[m]=T<<8|T>>>24,o[m]=T,T=b*16843009^y*65537^L*257^m*16843008,d[v]=T<<24|T>>>8,h[v]=T<<16|T>>>16,c[v]=T<<8|T>>>24,u[v]=T,m?(m=L^f[f[f[b^L]]],g^=f[f[g]]):m=g=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let i=!0,s=0;for(;s<t.length&&i;)i=t[s]===this.key[s],s++;if(i)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const n=this.ksRows=(r+6+1)*4;let o,l;const d=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),c=this.sBox,u=this.rcon,f=this.invSubMix,m=f[0],g=f[1],p=f[2],v=f[3];let L,y;for(o=0;o<n;o++){if(o<r){L=d[o]=t[o];continue}y=L,o%r===0?(y=y<<8|y>>>24,y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[y&255],y^=u[o/r|0]<<24):r>6&&o%r===4&&(y=c[y>>>24]<<24|c[y>>>16&255]<<16|c[y>>>8&255]<<8|c[y&255]),d[o]=L=(d[o-r]^y)>>>0}for(l=0;l<n;l++)o=n-l,l&3?y=d[o]:y=d[o-4],l<4||o<=4?h[l]=y:h[l]=m[c[y>>>24]]^g[c[y>>>16&255]]^p[c[y>>>8&255]]^v[c[y&255]],h[l]=h[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,i){const s=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,o=this.invSubMix,l=o[0],d=o[1],h=o[2],c=o[3],u=this.uint8ArrayToUint32Array_(i);let f=u[0],m=u[1],g=u[2],p=u[3];const v=new Int32Array(e),L=new Int32Array(v.length);let y,b,T,I,A,D,P,_,C,$,M,U,B,V;const W=this.networkToHostOrderSwap;for(;t<v.length;){for(C=W(v[t]),$=W(v[t+1]),M=W(v[t+2]),U=W(v[t+3]),A=C^r[0],D=U^r[1],P=M^r[2],_=$^r[3],B=4,V=1;V<s;V++)y=l[A>>>24]^d[D>>16&255]^h[P>>8&255]^c[_&255]^r[B],b=l[D>>>24]^d[P>>16&255]^h[_>>8&255]^c[A&255]^r[B+1],T=l[P>>>24]^d[_>>16&255]^h[A>>8&255]^c[D&255]^r[B+2],I=l[_>>>24]^d[A>>16&255]^h[D>>8&255]^c[P&255]^r[B+3],A=y,D=b,P=T,_=I,B=B+4;y=n[A>>>24]<<24^n[D>>16&255]<<16^n[P>>8&255]<<8^n[_&255]^r[B],b=n[D>>>24]<<24^n[P>>16&255]<<16^n[_>>8&255]<<8^n[A&255]^r[B+1],T=n[P>>>24]<<24^n[_>>16&255]<<16^n[A>>8&255]<<8^n[D&255]^r[B+2],I=n[_>>>24]<<24^n[A>>16&255]<<16^n[D>>8&255]<<8^n[P&255]^r[B+3],L[t]=W(y^f),L[t+1]=W(I^m),L[t+2]=W(T^g),L[t+3]=W(b^p),f=C,m=$,g=M,p=U,t=t+4}return L.buffer}}const mn=16;class Tt{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 i=self.crypto;i&&(this.subtle=i.subtle||i.webkitSubtle)}catch{}this.subtle===null&&(this.useSoftware=!0)}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const i=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?un(i):i}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i){return this.useSoftware?new Promise((s,r)=>{this.softwareDecrypt(new Uint8Array(e),t,i);const n=this.flush();n?s(n.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i)}softwareDecrypt(e,t,i){const{currentIV:s,currentResult:r,remainderData:n}=this;this.logOnce("JS AES decrypt"),n&&(e=de(n,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;s&&(i=s);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new fn),l.expandKey(t);const d=r;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=Ae(o,-16).buffer,d||null}webCryptoDecrypt(e,t,i){const s=this.subtle;return(this.key!==t||!this.fastAesKey)&&(this.key=t,this.fastAesKey=new cn(s,t)),this.fastAesKey.expandKey().then(r=>s?(this.logOnce("WebCrypto AES decrypt"),new hn(s,new Uint8Array(i)).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(S.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,i)))}onWebCryptoError(e,t,i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i);const s=this.flush();if(s)return s.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const i=e.length-e.length%mn;return i!==e.length&&(t=Ae(e,0,i),this.remainderData=Ae(e,i)),t}logOnce(e){this.logEnabled&&(S.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const gn={toString:function(a){let e="";const t=a.length;for(let i=0;i<t;i++)e+=`[${a.start(i).toFixed(3)}-${a.end(i).toFixed(3)}]`;return e}},w={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class pn extends rn{constructor(e,t,i,s,r){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=w.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=r,this.logPrefix=s,this.log=S.log.bind(S,`${s}:`),this.warn=S.warn.bind(S,`${s}:`),this.hls=e,this.fragmentLoader=new tn(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Tt(e.config),e.on(x.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=w.STOPPED}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const i=t.partList;if(i!=null&&i.length){const r=i[i.length-1];return J.isBuffered(this.media,r.start+r.duration/2)}const s=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(s)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}onMediaAttached(e,t){const i=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),i.addEventListener("seeking",this.onvseeking),i.addEventListener("ended",this.onvended);const s=this.config;this.levels&&s.autoStartLoad&&this.state===w.STOPPED&&this.startLoad(s.startPosition)}onMediaDetaching(){const e=this.media;e!=null&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:i,mediaBuffer:s,state:r}=this,n=i?i.currentTime:0,o=J.bufferInfo(s||i,n,e.maxBufferHole);if(this.log(`media seeking to ${k(n)?n.toFixed(3):n}, state: ${r}`),this.state===w.ENDED)this.resetLoadingState();else if(t){const l=e.maxFragLookUpTolerance,d=t.start-l,h=t.start+t.duration+l;if(!o.len||h<o.start||d>o.end){const c=n>h;(n<d||c)&&(c&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}i&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),this.lastCurrentTime=n),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=n),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=w.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){const s=r=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${r.part?" p: "+r.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,i,s).then(r=>{if(!r)return;const n=this.state;if(this.fragContextChanged(e)){(n===w.FRAG_LOADING||!this.fragCurrent&&n===w.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=w.IDLE);return}"payload"in r&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(x.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===w.STOPPED||this.state===w.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:i}=this;if(i.getState(e)===ne.APPENDING){const r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,n?n.len:this.config.maxBufferLength);this.reduceMaxBufferLength(o)&&i.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===ne.PARTIAL&&i.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,i=null){if(!(e-t))return;const s={startOffset:e,endOffset:t,type:i};this.hls.trigger(x.BUFFER_FLUSHING,s)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(i=>{if(!i||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return i}).then(i=>{const{hls:s}=this,{payload:r}=i,n=e.decryptdata;if(r&&r.byteLength>0&&n!=null&&n.key&&n.iv&&n.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer).catch(l=>{throw s.trigger(x.ERROR,{type:K.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const d=self.performance.now();return s.trigger(x.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:d}}),i.payload=l,this.completeInitSegmentLoad(i)})}return this.completeInitSegmentLoad(i)}).catch(i=>{this.state===w.STOPPED||this.state===w.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const i=e.frag.stats;this.state=w.IDLE,e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.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 i,s,r,n;const o=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===z.MAIN?"level":"track"} ${e.level} (frag:[${((i=e.startPTS)!=null?i:NaN).toFixed(3)}-${((s=e.endPTS)!=null?s:NaN).toFixed(3)}] > buffer:${o?gn.toString(J.getBuffered(o)):"(detached)"})`),e.sn!=="initSegment"){var l;if(e.type!==z.SUBTITLE){const h=e.elementaryStreams;if(!Object.keys(h).some(c=>!!h[c])){this.state=w.IDLE;return}}const d=(l=this.levels)==null?void 0:l[e.level];d!=null&&d.fragmentError&&(this.log(`Resetting level fragment error count of ${d.fragmentError} on frag buffered`),d.fragmentError=0)}this.state=w.IDLE,o&&(!this.loadedmetadata&&e.type==z.MAIN&&o.buffered.length&&((r=this.fragCurrent)==null?void 0:r.sn)===((n=this.fragPrevious)==null?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:i,part:s,partsLoaded:r}=e,n=!r||r.length===0||r.some(l=>!l),o=new ki(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,s){var r;const n=t?.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=w.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(x.KEY_LOADED,h),this.state===w.KEY_LOADING&&(this.state=w.IDLE),h}),this.hls.trigger(x.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(e,n.encryptedFragments),i=Math.max(e.start,i||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const h=n.partList;if(h&&s){i>e.end&&n.fragmentHint&&(e=n.fragmentHint);const c=this.getNextPart(h,e,i);if(c>-1){const u=h[c];this.log(`Loading part sn: ${e.sn} p: ${u.index} cc: ${e.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${c}-${h.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=u.start+u.duration,this.state=w.FRAG_LOADING;let f;return o?f=o.then(m=>!m||this.fragContextChanged(m.frag)?null:this.doFragPartsLoad(e,u,t,s)).catch(m=>this.handleFragLoadError(m)):f=this.doFragPartsLoad(e,u,t,s).catch(m=>this.handleFragLoadError(m)),this.hls.trigger(x.FRAG_LOADING,{frag:e,part:u,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}else if(!e.url||this.loadedEndOfParts(h,i))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(i.toFixed(3))}`),k(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=w.FRAG_LOADING;const l=this.config.progressive;let d;return l&&o?d=o.then(h=>!h||this.fragContextChanged(h?.frag)?null:this.fragmentLoader.load(e,s)).catch(h=>this.handleFragLoadError(h)):d=Promise.all([this.fragmentLoader.load(e,l?s:void 0),o]).then(([h])=>(!l&&h&&s&&s(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(x.FRAG_LOADING,{frag:e,targetBufferTime:i}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,i,s){return new Promise((r,n)=>{var o;const l=[],d=(o=i.details)==null?void 0:o.partList,h=c=>{this.fragmentLoader.loadPart(e,c,s).then(u=>{l[c.index]=u;const f=u.part;this.hls.trigger(x.FRAG_LOADED,u);const m=pi(i,e.sn,c.index+1)||xi(d,e.sn,c.index+1);if(m)h(m);else return r({frag:e,part:f,partsLoaded:l})}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(x.ERROR,t)}else this.hls.trigger(x.ERROR,{type:K.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==w.PARSING){!this.fragCurrent&&this.state!==w.STOPPED&&this.state!==w.ERROR&&(this.state=w.IDLE);return}const{frag:i,part:s,level:r}=t,n=self.performance.now();i.stats.parsing.end=n,s&&(s.stats.parsing.end=n),this.updateLevelTiming(i,s,r,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:i}=this,{level:s,sn:r,part:n}=e;if(!(t!=null&&t[s]))return this.warn(`Levels object was unset while buffering fragment ${r} of level ${s}. The current chunk will not be buffered.`),null;const o=t[s],l=n>-1?pi(o,r,n):null,d=l?l.fragment:vr(o,r,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:o}):null}bufferFragmentData(e,t,i,s,r){var n;if(!e||this.state!==w.PARSING)return;const{data1:o,data2:l}=e;let d=o;if(o&&l&&(d=de(o,l)),!((n=d)!=null&&n.length))return;const h={type:e.type,frag:t,part:i,chunkMeta:s,parent:t.type,data:d};if(this.hls.trigger(x.BUFFER_APPENDING,h),e.dropped&&e.independent&&!i){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!J.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const i=t.currentTime,s=J.bufferInfo(t,i,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-n,s.end-n),i+n);e.start-o>n&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const i=this.getLoadPosition();return k(i)?this.getFwdBufferInfoAtPos(e,i,t):null}getFwdBufferInfoAtPos(e,t,i){const{config:{maxBufferHole:s}}=this,r=J.bufferInfo(e,t,s);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,i);if(n&&r.nextStart<n.end)return J.bufferInfo(e,t,Math.max(r.nextStart,s))}return r}getMaxBufferLength(e){const{config:t}=this;let i;return e?i=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):i=t.maxBufferLength,Math.min(i,t.maxMaxBufferLength)}reduceMaxBufferLength(e){const t=this.config,i=e||t.maxBufferLength;return t.maxMaxBufferLength>=i?(t.maxMaxBufferLength/=2,this.warn(`Reduce max buffer length to ${t.maxMaxBufferLength}s`),!0):!1}getAppendedFrag(e,t=z.MAIN){const i=this.fragmentTracker.getAppendedFrag(e,z.MAIN);return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){const i=t.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=i[0].start;let o;if(t.live){const l=r.initialLiveManifestSize;if(s<l)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${l})`),null;(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n)&&(o=this.getInitialLiveFragment(t,i),this.startPosition=this.nextLoadPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=n&&(o=i[0]);if(!o){const l=r.lowLatencyMode?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,l,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const i=this.fragmentTracker.getState(e);return(i===ne.OK||i===ne.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,i,s,r){const n=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(o===null)return o;if(e=o,n&&e&&!e.gap&&i.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s);if(l!==null&&i.len+l.len>=r)return this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,i){let s=-1,r=!1,n=!0;for(let o=0,l=e.length;o<l;o++){const d=e[o];if(n=n&&!d.independent,s>-1&&i<d.start)break;const h=d.loaded;h?s=-1:(r||d.independent||n)&&d.fragment===t&&(s=o),r=h}return s}loadedEndOfParts(e,t){const i=e[e.length-1];return i&&t>i.start&&i.loaded}getInitialLiveFragment(e,t){const i=this.fragPrevious;let s=null;if(i){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),s=Er(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance)),!s){const r=i.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];i.cc===n.cc&&(s=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${s.sn}`))}s||(s=Sr(t,i.cc),s&&this.log(`Live playlist, switching playlist, load frag with same CC: ${s.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(s=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return s}getFragmentAtPosition(e,t,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:n,endSN:o}=i;const{fragmentHint:l}=i,d=s.maxFragLookUpTolerance,h=i.partList,c=!!(s.lowLatencyMode&&h!=null&&h.length&&l);c&&l&&!this.bitrateTest&&(n=n.concat(l),o=l.sn);let u;if(e<t){const f=e>t-d?0:d;u=Si(r,n,e,f)}else u=n[n.length-1];if(u){const f=u.sn-i.startSN,m=this.fragmentTracker.getState(u);if((m===ne.OK||m===ne.PARTIAL&&u.gap)&&(r=u),r&&u.sn===r.sn&&(!c||h[0].fragment.sn>u.sn)&&r&&u.level===r.level){const p=n[f+1];u.sn<o&&this.fragmentTracker.getState(p)!==ne.OK?u=p:u=null}}return u}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=i.currentTime,n=e.fragments[0].start,o=e.edge,l=r>=n-t.maxFragLookUpTolerance&&r<=o;if(s!==null&&i.duration>s&&(r<s||!l)){const d=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!l&&i.readyState<4||r<o-d)&&(this.loadedmetadata||(this.nextLoadPosition=s),i.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),i.currentTime=s))}}alignPlaylists(e,t,i){const s=e.fragments.length;if(!s)return this.warn("No fragments in live playlist"),0;const r=e.fragments[0].start,n=!t,o=e.alignedSliding&&k(r);if(n||!o&&!r){const{fragPrevious:l}=this;on(l,i,e);const d=e.fragments[0].start;return this.log(`Live playlist sliding: ${d.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${l?l.sn:"na"} fragments: ${s}`),d}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let i=this.startPosition;if(i<t&&(i=-1),i===-1||this.lastCurrentTime===-1){const s=this.startTimeOffset!==null,r=s?this.startTimeOffset:e.startTimeOffset;r!==null&&k(r)?(i=t+r,r<0&&(i+=e.totalduration),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Start time offset ${r} found in ${s?"multivariant":"media"} playlist, adjust startPosition to ${i}`),this.startPosition=i):e.live?i=this.hls.liveSyncPosition||t:this.startPosition=i=0,this.lastCurrentTime=i}this.nextLoadPosition=i}getLoadPosition(){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&&e.sn!=="initSegment"&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==w.FRAG_LOADING_WAITING_RETRY)&&(this.state=w.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const h=this.getCurrentContext(t.chunkMeta);h&&(t.frag=h.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var s;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const r=t.details===R.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(i,!0);const n=t.errorAction,{action:o,retryCount:l=0,retryConfig:d}=n||{};if(n&&o===ie.RetryRequest&&d){this.resetStartWhenNotLoaded(this.levelLastLoaded);const h=vt(d,l);this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${l+1}/${d.maxNumRetry} in ${h}ms`),n.resolved=!0,this.retryDate=self.performance.now()+h,this.state=w.FRAG_LOADING_WAITING_RETRY}else if(d&&n)if(this.resetFragmentErrors(e),l<d.maxNumRetry)!r&&o!==ie.RemoveAlternatePermanently&&(n.resolved=!0);else{S.warn(`${t.details} reached or exceeded max retry (${l})`);return}else n?.action===ie.SendAlternateToPenaltyBox?this.state=w.WAITING_LEVEL:this.state=w.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===w.PARSING||this.state===w.PARSED){const t=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,t),s=i&&i.len>.5;s&&this.reduceMaxBufferLength(i.len);const r=!s;return r&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${t} buffer`),e.frag&&(this.fragmentTracker.removeFragment(e.frag),this.nextLoadPosition=e.frag.start),this.resetLoadingState(),r}return!1}resetFragmentErrors(e){e===z.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==w.STOPPED&&(this.state=w.IDLE)}afterBufferFlushed(e,t,i){if(!e)return;const s=J.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,i),this.state===w.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=w.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,s){var r;const n=i.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,d)=>{const h=e.elementaryStreams[d];if(h){const c=h.endPTS-h.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${c})`),l||!1;const u=s?0:mi(n,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(x.LEVEL_PTS_UPDATED,{details:n,level:i,drift:u,type:d,frag:e,start:h.startPTS,end:h.endPTS}),!0}return l},!1)&&((r=this.transmuxer)==null?void 0:r.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(i.fragmentError===0&&(i.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(x.ERROR,{type:K.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=w.PARSED,this.hls.trigger(x.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(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}}function Bi(){return self.SourceBuffer||self.WebKitSourceBuffer}function Ui(){if(!Re())return!1;const e=Bi();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function xn(){if(!Ui())return!1;const a=Re();return typeof a?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>a.isTypeSupported(ht(e,"video")))||["mp4a.40.2","fLaC"].some(e=>a.isTypeSupported(ht(e,"audio"))))}function vn(){var a;const e=Bi();return typeof(e==null||(a=e.prototype)==null?void 0:a.changeType)=="function"}function yn(){return typeof __HLS_WORKER_BUNDLE__=="function"}function En(){const a=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(a);return{worker:new self.Worker(e),objectURL:e}}function Tn(a){const e=new self.URL(a,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function me(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class $i{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=de(this.cachedData,e),this.cachedData=null);let i=Me(e,0),s=i?i.length:0,r;const n=this._audioTrack,o=this._id3Track,l=i?Ut(i):void 0,d=e.length;for((this.basePTS===null||this.frameIndex===0&&k(l))&&(this.basePTS=Sn(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),i&&i.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:he.audioId3,duration:Number.POSITIVE_INFINITY});s<d;){if(this.canParse(e,s)){const h=this.appendFrame(n,e,s);h?(this.frameIndex++,this.lastPTS=h.sample.pts,s+=h.length,r=s):s=d}else Ss(e,s)?(i=Me(e,s),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:he.audioId3,duration:Number.POSITIVE_INFINITY}),s+=i.length,r=s):s++;if(s===d&&r!==d){const h=Ae(e,r);this.cachedData?this.cachedData=de(this.cachedData,h):this.cachedData=h}}return{audioTrack:n,videoTrack:me(),id3Track:o,textTrack:me()}}demuxSampleAes(e,t,i){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:me(),id3Track:this._id3Track,textTrack:me()}}destroy(){}}const Sn=(a,e,t)=>{if(k(a))return a*90;const i=t?t.baseTime*9e4/t.timescale:0;return e*9e4+i};function Ln(a,e,t,i){let s,r,n,o;const l=navigator.userAgent.toLowerCase(),d=i,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=((e[t+2]&192)>>>6)+1;const c=(e[t+2]&60)>>>2;if(c>h.length-1){const u=new Error(`invalid ADTS sampling index:${c}`);a.emit(x.ERROR,x.ERROR,{type:K.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:u,reason:u.message});return}return n=(e[t+2]&1)<<2,n|=(e[t+3]&192)>>>6,S.log(`manifest codec:${i}, ADTS type:${s}, samplingIndex:${c}`),/firefox/i.test(l)?c>=6?(s=5,o=new Array(4),r=c-3):(s=2,o=new Array(2),r=c):l.indexOf("android")!==-1?(s=2,o=new Array(2),r=c):(s=5,o=new Array(4),i&&(i.indexOf("mp4a.40.29")!==-1||i.indexOf("mp4a.40.5")!==-1)||!i&&c>=6?r=c-3:((i&&i.indexOf("mp4a.40.2")!==-1&&(c>=6&&n===1||/vivaldi/i.test(l))||!i&&n===1)&&(s=2,o=new Array(2)),r=c)),o[0]=s<<3,o[0]|=(c&14)>>1,o[1]|=(c&1)<<7,o[1]|=n<<3,s===5&&(o[1]|=(r&14)>>1,o[2]=(r&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:h[c],channelCount:n,codec:"mp4a.40."+s,manifestCodec:d}}function Gi(a,e){return a[e]===255&&(a[e+1]&246)===240}function Vi(a,e){return a[e+1]&1?7:9}function St(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function An(a,e){return e+5<a.length}function Qe(a,e){return e+1<a.length&&Gi(a,e)}function Rn(a,e){return An(a,e)&&Gi(a,e)&&St(a,e)<=a.length-e}function bn(a,e){if(Qe(a,e)){const t=Vi(a,e);if(e+t>=a.length)return!1;const i=St(a,e);if(i<=t)return!1;const s=e+i;return s===a.length||Qe(a,s)}return!1}function Hi(a,e,t,i,s){if(!a.samplerate){const r=Ln(e,t,i,s);if(!r)return;a.config=r.config,a.samplerate=r.samplerate,a.channelCount=r.channelCount,a.codec=r.codec,a.manifestCodec=r.manifestCodec,S.log(`parsed codec:${a.codec}, rate:${r.samplerate}, channels:${r.channelCount}`)}}function Ki(a){return 1024*9e4/a}function In(a,e){const t=Vi(a,e);if(e+t<=a.length){const i=St(a,e)-t;if(i>0)return{headerLength:t,frameLength:i}}}function Wi(a,e,t,i,s){const r=Ki(a.samplerate),n=i+s*r,o=In(e,t);let l;if(o){const{frameLength:c,headerLength:u}=o,f=u+c,m=Math.max(0,t+f-e.length);m?(l=new Uint8Array(f-u),l.set(e.subarray(t+u,e.length),0)):l=e.subarray(t+u,t+f);const g={unit:l,pts:n};return m||a.samples.push(g),{sample:g,length:f,missing:m}}const d=e.length-t;return l=new Uint8Array(d),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:n},length:d,missing:-1}}let Je=null;const Dn=[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],Cn=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],_n=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],wn=[0,1,1,4];function Yi(a,e,t,i,s){if(t+24>e.length)return;const r=ji(e,t);if(r&&t+r.frameLength<=e.length){const n=r.samplesPerFrame*9e4/r.sampleRate,o=i+s*n,l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=r.channelCount,a.samplerate=r.sampleRate,a.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function ji(a,e){const t=a[e+1]>>3&3,i=a[e+1]>>1&3,s=a[e+2]>>4&15,r=a[e+2]>>2&3;if(t!==1&&s!==0&&s!==15&&r!==3){const n=a[e+2]>>1&1,o=a[e+3]>>6,l=t===3?3-i:i===3?3:4,d=Dn[l*14+s-1]*1e3,c=Cn[(t===3?0:t===2?1:2)*3+r],u=o===3?1:2,f=_n[t][i],m=wn[i],g=f*8*m,p=Math.floor(f*d/c+n)*m;if(Je===null){const y=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Je=y?parseInt(y[1]):0}return!!Je&&Je<=87&&i===2&&d>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:c,channelCount:u,frameLength:p,samplesPerFrame:g}}}function Lt(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function zi(a,e){return e+1<a.length&&Lt(a,e)}function Pn(a,e){return Lt(a,e)&&4<=a.length-e}function qi(a,e){if(e+1<a.length&&Lt(a,e)){const i=ji(a,e);let s=4;i!=null&&i.frameLength&&(s=i.frameLength);const r=e+s;return r===a.length||zi(a,r)}return!1}class Fn extends $i{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Me(e,0);let i=t?.length||0;if(qi(e,i))return!1;for(let s=e.length;i<s;i++)if(bn(e,i))return S.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Rn(e,t)}appendFrame(e,t,i){Hi(e,this.observer,t,i,e.manifestCodec);const s=Wi(e,t,i,this.basePTS,this.frameIndex);if(s&&s.missing===0)return s}}const On=/\/emsg[-/]ID3/i;class kn{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,s){const r=this.videoTrack=me("video",1),n=this.audioTrack=me("audio",1),o=this.txtTrack=me("text",1);if(this.id3Track=me("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=jt(e);if(l.video){const{id:d,timescale:h,codec:c}=l.video;r.id=d,r.timescale=o.timescale=h,r.codec=c}if(l.audio){const{id:d,timescale:h,codec:c}=l.audio;n.id=d,n.timescale=h,n.codec=c}o.id=Ht.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(e){return ws(e)}demux(e,t){this.timeOffset=t;let i=e;const s=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=de(this.remainderData,e));const o=$s(i);this.remainderData=o.remainder,s.samples=o.valid||new Uint8Array}else s.samples=i;const n=this.extractID3Track(s,t);return r.samples=zt(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const s=this.extractID3Track(t,this.timeOffset);return i.samples=zt(e,t),{videoTrack:t,audioTrack:me(),id3Track:s,textTrack:me()}}extractID3Track(e,t){const i=this.id3Track;if(e.samples.length){const s=G(e.samples,["emsg"]);s&&s.forEach(r=>{const n=Hs(r);if(On.test(n.schemeIdUri)){const o=k(n.presentationTime)?n.presentationTime/n.timeScale:t+n.presentationTimeDelta/n.timeScale;let l=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const d=n.payload;i.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:he.emsg,duration:l})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const Mn=(a,e)=>{let t=0,i=5;e+=i;const s=new Uint32Array(1),r=new Uint32Array(1),n=new Uint8Array(1);for(;i>0;){n[0]=a[e];const o=Math.min(i,8),l=8-o;r[0]=4278190080>>>24+l<<l,s[0]=(n[0]&r[0])>>l,t=t?t<<o|s[0]:s[0],e+=1,i-=o}return t};class Nn{constructor(){this.VideoSample=null}createVideoSample(e,t,i,s){return{key:e,frame:!1,pts:t,dts:i,units:[],debug:s,length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,s;if((!i||i.units.length===0)&&(i=e[e.length-1]),(t=i)!=null&&t.units){const r=i.units;s=r[r.length-1]}return s}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const i=t.samples,s=i.length;if(s){const r=i[s-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}e.debug.length&&S.log(e.pts+"/"+e.dts+":"+e.debug)}}class Xi{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,i=e.byteLength-t,s=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");s.set(e.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const i=this.word>>>32-t;if(e>32&&S.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)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 this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t=8,i=8,s;for(let r=0;r<e;r++)i!==0&&(s=this.readEG(),i=(t+s+256)%256),t=i===0?t:i}readSPS(){let e=0,t=0,i=0,s=0,r,n,o;const l=this.readUByte.bind(this),d=this.readBits.bind(this),h=this.readUEG.bind(this),c=this.readBoolean.bind(this),u=this.skipBits.bind(this),f=this.skipEG.bind(this),m=this.skipUEG.bind(this),g=this.skipScalingList.bind(this);l();const p=l();if(d(5),u(3),l(),m(),p===100||p===110||p===122||p===244||p===44||p===83||p===86||p===118||p===128){const I=h();if(I===3&&u(1),m(),m(),u(1),c())for(n=I!==3?8:12,o=0;o<n;o++)c()&&(o<6?g(16):g(64))}m();const v=h();if(v===0)h();else if(v===1)for(u(1),f(),f(),r=h(),o=0;o<r;o++)f();m(),u(1);const L=h(),y=h(),b=d(1);b===0&&u(1),u(1),c()&&(e=h(),t=h(),i=h(),s=h());let T=[1,1];if(c()&&c())switch(l()){case 1:T=[1,1];break;case 2:T=[12,11];break;case 3:T=[10,11];break;case 4:T=[16,11];break;case 5:T=[40,33];break;case 6:T=[24,11];break;case 7:T=[20,11];break;case 8:T=[32,11];break;case 9:T=[80,33];break;case 10:T=[18,11];break;case 11:T=[15,11];break;case 12:T=[64,33];break;case 13:T=[160,99];break;case 14:T=[4,3];break;case 15:T=[3,2];break;case 16:T=[2,1];break;case 255:{T=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((L+1)*16-e*2-t*2),height:(2-b)*(y+1)*16-(b?2:4)*(i+s),pixelRatio:T}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class Bn extends Nn{parseAVCPES(e,t,i,s,r){const n=this.parseAVCNALu(e,i.data);let o=this.VideoSample,l,d=!1;i.data=null,o&&n.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts,"")),n.forEach(h=>{var c;switch(h.type){case 1:{let g=!1;l=!0;const p=h.data;if(d&&p.length>4){const v=new Xi(p).readSliceType();(v===2||v===4||v===7||v===9)&&(g=!0)}if(g){var u;(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.frame=!0,o.key=g;break}case 5:l=!0,(c=o)!=null&&c.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts,"")),o.key=!0,o.frame=!0;break;case 6:{l=!0,qt(h.data,1,i.pts,t.samples);break}case 7:{var f,m;l=!0,d=!0;const g=h.data,v=new Xi(g).readSPS();if(!e.sps||e.width!==v.width||e.height!==v.height||((f=e.pixelRatio)==null?void 0:f[0])!==v.pixelRatio[0]||((m=e.pixelRatio)==null?void 0:m[1])!==v.pixelRatio[1]){e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.sps=[g],e.duration=r;const L=g.subarray(1,4);let y="avc1.";for(let b=0;b<3;b++){let T=L[b].toString(16);T.length<2&&(T="0"+T),y+=T}e.codec=y}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,i.pts,i.dts,"");break;case 12:l=!0;break;default:l=!1,o&&(o.debug+="unknown NAL "+h.type+" ");break}o&&l&&o.units.push(h)}),s&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){const i=t.byteLength;let s=e.naluState||0;const r=s,n=[];let o=0,l,d,h,c=-1,u=0;for(s===-1&&(c=0,u=t[0]&31,s=0,o=1);o<i;){if(l=t[o++],!s){s=l?0:1;continue}if(s===1){s=l?0:2;continue}if(!l)s=3;else if(l===1){if(d=o-s-1,c>=0){const f={data:t.subarray(c,d),type:u};n.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)),d>0&&(f.data=de(f.data,t.subarray(0,d)),f.state=0))}o<i?(h=t[o]&31,c=o,u=h,s=0):s=-1}else s=0}if(c>=0&&s>=0){const f={data:t.subarray(c,i),type:u,state:s};n.push(f)}if(n.length===0){const f=this.getLastNalUnit(e.samples);f&&(f.data=de(f.data,t))}return e.naluState=s,n}}class Un{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Tt(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,i){const s=e[t].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(o=>{const l=new Uint8Array(o);s.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)})}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length){i();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,i=new Int8Array(t);let s=0;for(let r=32;r<e.length-16;r+=160,s+=16)i.set(e.subarray(r,r+16),s);return i}getAvcDecryptedUnit(e,t){const i=new Uint8Array(t);let s=0;for(let r=32;r<e.length-16;r+=160,s+=16)e.set(i.subarray(s,s+16),r);return e}decryptAvcSample(e,t,i,s,r){const n=Xt(r.data),o=this.getAvcEncryptedData(n);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(n,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,s)})}decryptAvcSamples(e,t,i,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length){s();return}const r=e[t].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,i,s,n),!this.decrypter.isSync()))return}}}}const te=188;class Te{constructor(e,t,i){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=i,this.videoParser=new Bn}static probe(e){const t=Te.syncOffset(e);return t>0&&S.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),t!==-1}static syncOffset(e){const t=e.length;let i=Math.min(te*5,t-te)+1,s=0;for(;s<i;){let r=!1,n=-1,o=0;for(let l=s;l<t;l+=te)if(e[l]===71&&(t-l===te||e[l+te]===71)){if(o++,n===-1&&(n=l,n!==0&&(i=Math.min(n+te*99,e.length-te)+1)),r||(r=At(e,l)===0),r&&o>1&&(n===0&&o>2||l+te>i))return n}else{if(o)return-1;break}s++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Ht[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,i,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Te.createTrack("video"),this._audioTrack=Te.createTrack("audio",s),this._id3Track=Te.createTrack("id3"),this._txtTrack=Te.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i,this._duration=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,s=!1){i||(this.sampleAes=null);let r;const n=this._videoTrack,o=this._audioTrack,l=this._id3Track,d=this._txtTrack;let h=n.pid,c=n.pesData,u=o.pid,f=l.pid,m=o.pesData,g=l.pesData,p=null,v=this.pmtParsed,L=this._pmtId,y=e.length;if(this.remainderData&&(e=de(this.remainderData,e),y=e.length,this.remainderData=null),y<te&&!s)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:l,textTrack:d};const b=Math.max(0,Te.syncOffset(e));y-=(y-b)%te,y<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,y,e.buffer.byteLength-y));let T=0;for(let A=b;A<y;A+=te)if(e[A]===71){const D=!!(e[A+1]&64),P=At(e,A),_=(e[A+3]&48)>>4;let C;if(_>1){if(C=A+5+e[A+4],C===A+te)continue}else C=A+4;switch(P){case h:D&&(c&&(r=Ce(c))&&this.videoParser.parseAVCPES(n,d,r,!1,this._duration),c={data:[],size:0}),c&&(c.data.push(e.subarray(C,A+te)),c.size+=A+te-C);break;case u:if(D){if(m&&(r=Ce(m)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break}m={data:[],size:0}}m&&(m.data.push(e.subarray(C,A+te)),m.size+=A+te-C);break;case f:D&&(g&&(r=Ce(g))&&this.parseID3PES(l,r),g={data:[],size:0}),g&&(g.data.push(e.subarray(C,A+te)),g.size+=A+te-C);break;case 0:D&&(C+=e[C]+1),L=this._pmtId=$n(e,C);break;case L:{D&&(C+=e[C]+1);const $=Gn(e,C,this.typeSupported,i);h=$.videoPid,h>0&&(n.pid=h,n.segmentCodec=$.segmentVideoCodec),u=$.audioPid,u>0&&(o.pid=u,o.segmentCodec=$.segmentAudioCodec),f=$.id3Pid,f>0&&(l.pid=f),p!==null&&!v&&(S.warn(`MPEG-TS PMT found at ${A} after unknown PID '${p}'. Backtracking to sync byte @${b} to parse all TS packets.`),p=null,A=b-188),v=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=P;break}}else T++;if(T>0){const A=new Error(`Found ${T} TS packet/s that do not start with 0x47`);this.observer.emit(x.ERROR,x.ERROR,{type:K.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:A,reason:A.message})}n.pesData=c,o.pesData=m,l.pesData=g;const I={audioTrack:o,videoTrack:n,id3Track:l,textTrack:d};return s&&this.extractRemainingSamples(I),I}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={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:i,id3Track:s,textTrack:r}=e,n=i.pesData,o=t.pesData,l=s.pesData;let d;if(n&&(d=Ce(n))?(this.videoParser.parseAVCPES(i,r,d,!0,this._duration),i.pesData=null):i.pesData=n,o&&(d=Ce(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,d);break;case"mp3":this.parseMPEGPES(t,d);break}t.pesData=null}else o!=null&&o.size&&S.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(d=Ce(l))?(this.parseID3PES(s,d),s.pesData=null):s.pesData=l}demuxSampleAes(e,t,i){const s=this.demux(e,i,!0,!this.config.progressive),r=this.sampleAes=new Un(this.observer,this.config,t);return this.decrypt(s,r)}decrypt(e,t){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=e;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{i(e)}):i(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{i(e)})})}destroy(){this._duration=0}parseAACPES(e,t){let i=0;const s=this.aacOverFlow;let r=t.data;if(s){this.aacOverFlow=null;const c=s.missing,u=s.sample.unit.byteLength;if(c===-1)r=de(s.sample.unit,r);else{const f=u-c;s.sample.unit.set(r.subarray(0,c),f),e.samples.push(s.sample),i=s.missing}}let n,o;for(n=i,o=r.length;n<o-1&&!Qe(r,n);n++);if(n!==i){let c;const u=n<o-1;u?c=`AAC PES did not start with ADTS header,offset:${n}`:c="No ADTS header found in AAC PES";const f=new Error(c);if(S.warn(`parsing error: ${c}`),this.observer.emit(x.ERROR,x.ERROR,{type:K.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:u,error:f,reason:c}),!u)return}Hi(e,this.observer,r,n,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(s){const c=Ki(e.samplerate);l=s.sample.pts+c}else{S.warn("[tsdemuxer]: AAC PES unknown PTS");return}let d=0,h;for(;n<o;)if(h=Wi(e,r,n,l,d),n+=h.length,h.missing){this.aacOverFlow=h;break}else for(d++;n<o-1&&!Qe(r,n);n++);}parseMPEGPES(e,t){const i=t.data,s=i.length;let r=0,n=0;const o=t.pts;if(o===void 0){S.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;n<s;)if(zi(i,n)){const l=Yi(e,i,n,o,r);if(l)n+=l.length,r++;else break}else n++}parseAC3PES(e,t){}parseID3PES(e,t){if(t.pts===void 0){S.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const i=ae({},t,{type:this._videoTrack?he.emsg:he.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(i)}}function At(a,e){return((a[e+1]&31)<<8)+a[e+2]}function $n(a,e){return(a[e+10]&31)<<8|a[e+11]}function Gn(a,e,t,i){const s={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},r=(a[e+1]&15)<<8|a[e+2],n=e+3+r-4,o=(a[e+10]&15)<<8|a[e+11];for(e+=12+o;e<n;){const l=At(a,e),d=(a[e+3]&15)<<8|a[e+4];switch(a[e]){case 207:if(!i){Rt("ADTS AAC");break}case 15:s.audioPid===-1&&(s.audioPid=l);break;case 21:s.id3Pid===-1&&(s.id3Pid=l);break;case 219:if(!i){Rt("H.264");break}case 27:s.videoPid===-1&&(s.videoPid=l,s.segmentVideoCodec="avc");break;case 3:case 4:!t.mpeg&&!t.mp3?S.log("MPEG audio found, not supported in this browser"):s.audioPid===-1&&(s.audioPid=l,s.segmentAudioCodec="mp3");break;case 193:if(!i){Rt("AC-3");break}case 129:S.warn("AC-3 in M2TS support not included in build");break;case 6:if(s.audioPid===-1&&d>0){let h=e+5,c=d;for(;c>2;){switch(a[h]){case 106:S.warn("AC-3 in M2TS support not included in build");break}const f=a[h+1]+2;h+=f,c-=f}}break;case 194:case 135:S.warn("Unsupported EC-3 in M2TS found");break;case 36:S.warn("Unsupported HEVC in M2TS found");break}e+=d+5}return s}function Rt(a){S.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function Ce(a){let e=0,t,i,s,r,n;const o=a.data;if(!a||a.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=de(o[0],o[1]),o.splice(1,1);if(t=o[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(i=(t[4]<<8)+t[5],i&&i>a.size-6)return null;const d=t[7];d&192&&(r=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,d&64?(n=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,r-n>60*9e4&&(S.warn(`${Math.round((r-n)/9e4)}s delta between PTS and DTS, align them`),r=n)):n=r),s=t[8];let h=s+9;if(a.size<=h)return null;a.size-=h;const c=new Uint8Array(a.size);for(let u=0,f=o.length;u<f;u++){t=o[u];let m=t.byteLength;if(h)if(h>m){h-=m;continue}else t=t.subarray(h),m-=h,h=0;c.set(t,e),e+=m}return i&&(i-=s+3),{data:c,pts:r,dts:n,len:i}}return null}class Vn extends $i{resetInitSegment(e,t,i,s){super.resetInitSegment(e,t,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:s,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Me(e,0);let i=t?.length||0;if(t&&e[i]===11&&e[i+1]===119&&Ut(t)!==void 0&&Mn(e,i)<=16)return!1;for(let s=e.length;i<s;i++)if(qi(e,i))return S.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Pn(e,t)}appendFrame(e,t,i){if(this.basePTS!==null)return Yi(e,t,i,this.basePTS,this.frameIndex)}}class Qi{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)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(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const Ee=Math.pow(2,32)-1;class E{static init(){E.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:[]};let e;for(e in E.types)E.types.hasOwnProperty(e)&&(E.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),i=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);E.HDLR_TYPES={video:t,audio:i};const s=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);E.STTS=E.STSC=E.STCO=r,E.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),E.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),E.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),E.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);E.FTYP=E.box(E.types.ftyp,n,l,n,o),E.DINF=E.box(E.types.dinf,E.box(E.types.dref,s))}static box(e,...t){let i=8,s=t.length;const r=s;for(;s--;)i+=t[s].byteLength;const n=new Uint8Array(i);for(n[0]=i>>24&255,n[1]=i>>16&255,n[2]=i>>8&255,n[3]=i&255,n.set(e,4),s=0,i=8;s<r;s++)n.set(t[s],i),i+=t[s].byteLength;return n}static hdlr(e){return E.box(E.types.hdlr,E.HDLR_TYPES[e])}static mdat(e){return E.box(E.types.mdat,e)}static mdhd(e,t){t*=e;const i=Math.floor(t/(Ee+1)),s=Math.floor(t%(Ee+1));return E.box(E.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(e){return E.box(E.types.mdia,E.mdhd(e.timescale,e.duration),E.hdlr(e.type),E.minf(e))}static mfhd(e){return E.box(E.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?E.box(E.types.minf,E.box(E.types.smhd,E.SMHD),E.DINF,E.stbl(e)):E.box(E.types.minf,E.box(E.types.vmhd,E.VMHD),E.DINF,E.stbl(e))}static moof(e,t,i){return E.box(E.types.moof,E.mfhd(e),E.traf(i,t))}static moov(e){let t=e.length;const i=[];for(;t--;)i[t]=E.trak(e[t]);return E.box.apply(null,[E.types.moov,E.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(E.mvex(e)))}static mvex(e){let t=e.length;const i=[];for(;t--;)i[t]=E.trex(e[t]);return E.box.apply(null,[E.types.mvex,...i])}static mvhd(e,t){t*=e;const i=Math.floor(t/(Ee+1)),s=Math.floor(t%(Ee+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,i>>24,i>>16&255,i>>8&255,i&255,s>>24,s>>16&255,s>>8&255,s&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return E.box(E.types.mvhd,r)}static sdtp(e){const t=e.samples||[],i=new Uint8Array(4+t.length);let s,r;for(s=0;s<t.length;s++)r=t[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return E.box(E.types.sdtp,i)}static stbl(e){return E.box(E.types.stbl,E.stsd(e),E.box(E.types.stts,E.STTS),E.box(E.types.stsc,E.STSC),E.box(E.types.stsz,E.STSZ),E.box(E.types.stco,E.STCO))}static avc1(e){let t=[],i=[],s,r,n;for(s=0;s<e.sps.length;s++)r=e.sps[s],n=r.byteLength,t.push(n>>>8&255),t.push(n&255),t=t.concat(Array.prototype.slice.call(r));for(s=0;s<e.pps.length;s++)r=e.pps[s],n=r.byteLength,i.push(n>>>8&255),i.push(n&255),i=i.concat(Array.prototype.slice.call(r));const o=E.box(E.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,d=e.height,h=e.pixelRatio[0],c=e.pixelRatio[1];return E.box(E.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,E.box(E.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),E.box(E.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,c>>24,c>>16&255,c>>8&255,c&255])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return E.box(E.types.mp4a,E.audioStsd(e),E.box(E.types.esds,E.esds(e)))}static mp3(e){return E.box(E.types[".mp3"],E.audioStsd(e))}static ac3(e){return E.box(E.types["ac-3"],E.audioStsd(e),E.box(E.types.dac3,e.config))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?E.box(E.types.stsd,E.STSD,E.mp3(e)):e.segmentCodec==="ac3"?E.box(E.types.stsd,E.STSD,E.ac3(e)):E.box(E.types.stsd,E.STSD,E.mp4a(e)):E.box(E.types.stsd,E.STSD,E.avc1(e))}static tkhd(e){const t=e.id,i=e.duration*e.timescale,s=e.width,r=e.height,n=Math.floor(i/(Ee+1)),o=Math.floor(i%(Ee+1));return E.box(E.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,s&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const i=E.sdtp(e),s=e.id,r=Math.floor(t/(Ee+1)),n=Math.floor(t%(Ee+1));return E.box(E.types.traf,E.box(E.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),E.box(E.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),E.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||4294967295,E.box(E.types.trak,E.tkhd(e),E.mdia(e))}static trex(e){const t=e.id;return E.box(E.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const i=e.samples||[],s=i.length,r=12+16*s,n=new Uint8Array(r);let o,l,d,h,c,u;for(t+=8+r,n.set([e.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<s;o++)l=i[o],d=l.duration,h=l.size,c=l.flags,u=l.cts,n.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,c.isLeading<<2|c.dependsOn,c.isDependedOn<<6|c.hasRedundancy<<4|c.paddingValue<<1|c.isNonSync,c.degradPrio&61440,c.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return E.box(E.types.trun,n)}static initSegment(e){E.types||E.init();const t=E.moov(e);return de(E.FTYP,t)}}E.types=void 0,E.HDLR_TYPES=void 0,E.STTS=void 0,E.STSC=void 0,E.STCO=void 0,E.STSZ=void 0,E.VMHD=void 0,E.SMHD=void 0,E.STSD=void 0,E.FTYP=void 0,E.DINF=void 0;const Hn=9e4;function Kn(a,e,t=1,i=!1){const s=a*e*t;return i?Math.round(s):s}function Oe(a,e=!1){return Kn(a,1e3,1/Hn,e)}const Wn=10*1e3,Ji=1024,Yn=1152,jn=1536;let _e=null,bt=null;class It{constructor(e,t,i,s=""){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=i,this.ISGenerated=!1,_e===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);_e=n?parseInt(n[1]):0}if(bt===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);bt=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){S.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){S.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){S.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const i=e.reduce((s,r)=>{const n=r.pts-s;return n<-4294967296?(t=!0,ue(s,r.pts)):n>0?s:r.pts},e[0].pts);return t&&S.debug("PTS rollover detected"),i}remux(e,t,i,s,r,n,o,l){let d,h,c,u,f,m,g=r,p=r;const v=e.pid>-1,L=t.pid>-1,y=t.samples.length,b=e.samples.length>0,T=o&&y>0||y>1;if((!v||b)&&(!L||T)||this.ISGenerated||o){if(this.ISGenerated){var A,D,P,_;const U=this.videoTrackConfig;U&&(t.width!==U.width||t.height!==U.height||((A=t.pixelRatio)==null?void 0:A[0])!==((D=U.pixelRatio)==null?void 0:D[0])||((P=t.pixelRatio)==null?void 0:P[1])!==((_=U.pixelRatio)==null?void 0:_[1]))&&this.resetInitSegment()}else c=this.generateIS(e,t,r,n);const C=this.isVideoContiguous;let $=-1,M;if(T&&($=zn(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,$>0){S.warn(`[mp4-remuxer]: Dropped ${$} out of ${y} video samples due to a missing keyframe`);const U=this.getVideoStartPts(t.samples);t.samples=t.samples.slice($),t.dropped+=$,p+=(t.samples[0].pts-U)/t.inputTimeScale,M=p}else $===-1&&(S.warn(`[mp4-remuxer]: No keyframe found out of ${y} video samples`),m=!1);if(this.ISGenerated){if(b&&T){const U=this.getVideoStartPts(t.samples),V=(ue(e.samples[0].pts,U)-U)/t.inputTimeScale;g+=Math.max(0,V),p+=Math.max(0,-V)}if(b){if(e.samplerate||(S.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,g,this.isAudioContiguous,n,L||T||l===z.AUDIO?p:void 0),T){const U=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(S.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(e,t,r,n)),d=this.remuxVideo(t,p,C,U)}}else T&&(d=this.remuxVideo(t,p,C,0));d&&(d.firstKeyFrame=$,d.independent=$!==-1,d.firstKeyFramePTS=M)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=Zi(i,r,this._initPTS,this._initDTS)),s.samples.length&&(u=es(s,r,this._initPTS))),{audio:h,video:d,initSegment:c,independent:m,text:u,id3:f}}generateIS(e,t,i,s){const r=e.samples,n=t.samples,o=this.typeSupported,l={},d=this._initPTS;let h=!d||s,c="audio/mp4",u,f,m;if(h&&(u=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(c="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):E.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(m=e.inputTimeScale,!d||m!==d.timescale?u=f=r[0].pts-Math.round(m*i):h=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:E.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(m=t.inputTimeScale,!d||m!==d.timescale){const g=this.getVideoStartPts(n),p=Math.round(m*i);f=Math.min(f,ue(n[0].dts,g)-p),u=Math.min(u,g-p)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:u,timescale:m},this._initDTS={baseTime:f,timescale:m}):u=m=void 0,{tracks:l,initPTS:u,timescale:m}}remuxVideo(e,t,i,s){const r=e.inputTimeScale,n=e.samples,o=[],l=n.length,d=this._initPTS;let h=this.nextAvcDts,c=8,u=this.videoSampleDuration,f,m,g=Number.POSITIVE_INFINITY,p=Number.NEGATIVE_INFINITY,v=!1;if(!i||h===null){const O=t*r,F=n[0].pts-ue(n[0].dts,n[0].pts);_e&&h!==null&&Math.abs(O-F-h)<15e3?i=!0:h=O-F}const L=d.baseTime*r/d.timescale;for(let O=0;O<l;O++){const F=n[O];F.pts=ue(F.pts-L,h),F.dts=ue(F.dts-L,h),F.dts<n[O>0?O-1:O].dts&&(v=!0)}v&&n.sort(function(O,F){const Y=O.dts-F.dts,H=O.pts-F.pts;return Y||H}),f=n[0].dts,m=n[n.length-1].dts;const y=m-f,b=y?Math.round(y/(l-1)):u||e.inputTimeScale/30;if(i){const O=f-h,F=O>b,Y=O<-1;if((F||Y)&&(F?S.warn(`AVC: ${Oe(O,!0)} ms (${O}dts) hole between fragments detected at ${t.toFixed(3)}`):S.warn(`AVC: ${Oe(-O,!0)} ms (${O}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!Y||h>=n[0].pts||_e)){f=h;const H=n[0].pts-O;if(F)n[0].dts=f,n[0].pts=H;else for(let q=0;q<n.length&&!(n[q].dts>H);q++)n[q].dts-=O,n[q].pts-=O;S.log(`Video: Initial PTS/DTS adjusted: ${Oe(H,!0)}/${Oe(f,!0)}, delta: ${Oe(O,!0)} ms`)}}f=Math.max(0,f);let T=0,I=0,A=f;for(let O=0;O<l;O++){const F=n[O],Y=F.units,H=Y.length;let q=0;for(let se=0;se<H;se++)q+=Y[se].data.length;I+=q,T+=H,F.length=q,F.dts<A?(F.dts=A,A+=b/4|0||1):A=F.dts,g=Math.min(F.pts,g),p=Math.max(F.pts,p)}m=n[l-1].dts;const D=I+4*T+8;let P;try{P=new Uint8Array(D)}catch(O){this.observer.emit(x.ERROR,x.ERROR,{type:K.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:D,reason:`fail allocating video mdat ${D}`});return}const _=new DataView(P.buffer);_.setUint32(0,D),P.set(E.types.mdat,4);let C=!1,$=Number.POSITIVE_INFINITY,M=Number.POSITIVE_INFINITY,U=Number.NEGATIVE_INFINITY,B=Number.NEGATIVE_INFINITY;for(let O=0;O<l;O++){const F=n[O],Y=F.units;let H=0;for(let le=0,re=Y.length;le<re;le++){const be=Y[le],we=be.data,tt=be.data.byteLength;_.setUint32(c,tt),c+=4,P.set(we,c),c+=tt,H+=4+tt}let q;if(O<l-1)u=n[O+1].dts-F.dts,q=n[O+1].pts-F.pts;else{const le=this.config,re=O>0?F.dts-n[O-1].dts:b;if(q=O>0?F.pts-n[O-1].pts:b,le.stretchShortVideoTrack&&this.nextAudioPts!==null){const be=Math.floor(le.maxBufferHole*r),we=(s?g+s*r:this.nextAudioPts)-F.pts;we>be?(u=we-re,u<0?u=re:C=!0,S.log(`[mp4-remuxer]: It is approximately ${we/90} ms to the next segment; using duration ${u/90} ms for the last video frame.`)):u=re}else u=re}const se=Math.round(F.pts-F.dts);$=Math.min($,u),U=Math.max(U,u),M=Math.min(M,q),B=Math.max(B,q),o.push(new ts(F.key,u,H,se))}if(o.length){if(_e){if(_e<70){const O=o[0].flags;O.dependsOn=2,O.isNonSync=0}}else if(bt&&B-M<U-$&&b/U<.025&&o[0].cts===0){S.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let O=f;for(let F=0,Y=o.length;F<Y;F++){const H=O+o[F].duration,q=O+o[F].cts;if(F<Y-1){const se=H+o[F+1].cts;o[F].duration=se-q}else o[F].duration=F?o[F-1].duration:b;o[F].cts=0,O=H}}}u=C||!u?b:u,this.nextAvcDts=h=m+u,this.videoSampleDuration=u,this.isVideoContiguous=!0;const X={data1:E.moof(e.sequenceNumber++,f,ae({},e,{samples:o})),data2:P,startPTS:g/r,endPTS:(p+u)/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,X}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Yn;case"ac3":return jn;default:return Ji}}remuxAudio(e,t,i,s,r){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,l=n/o,d=this.getSamplesPerFrame(e),h=d*l,c=this._initPTS,u=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],m=r!==void 0;let g=e.samples,p=u?0:8,v=this.nextAudioPts||-1;const L=t*n,y=c.baseTime*n/c.timescale;if(this.isAudioContiguous=i=i||g.length&&v>0&&(s&&Math.abs(L-v)<9e3||Math.abs(ue(g[0].pts-y,L)-v)<20*h),g.forEach(function(V){V.pts=ue(V.pts-y,L)}),!i||v<0){if(g=g.filter(V=>V.pts>=0),!g.length)return;r===0?v=0:s&&!m?v=Math.max(0,L):v=g[0].pts}if(e.segmentCodec==="aac"){const V=this.config.maxAudioFramesDrift;for(let W=0,X=v;W<g.length;W++){const O=g[W],F=O.pts,Y=F-X,H=Math.abs(1e3*Y/n);if(Y<=-V*h&&m)W===0&&(S.warn(`Audio frame @ ${(F/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*Y/n)} ms.`),this.nextAudioPts=v=X=F);else if(Y>=V*h&&H<Wn&&m){let q=Math.round(Y/h);X=F-q*h,X<0&&(q--,X+=h),W===0&&(this.nextAudioPts=v=X),S.warn(`[mp4-remuxer]: Injecting ${q} audio frame @ ${(X/n).toFixed(3)}s due to ${Math.round(1e3*Y/n)} ms gap.`);for(let se=0;se<q;se++){const le=Math.max(X,0);let re=Qi.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);re||(S.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),re=O.unit.subarray()),g.splice(W,0,{unit:re,pts:le}),X+=h,W++}}O.pts=X,X+=h}}let b=null,T=null,I,A=0,D=g.length;for(;D--;)A+=g[D].unit.byteLength;for(let V=0,W=g.length;V<W;V++){const X=g[V],O=X.unit;let F=X.pts;if(T!==null){const H=f[V-1];H.duration=Math.round((F-T)/l)}else if(i&&e.segmentCodec==="aac"&&(F=v),b=F,A>0){A+=p;try{I=new Uint8Array(A)}catch(H){this.observer.emit(x.ERROR,x.ERROR,{type:K.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:H,bytes:A,reason:`fail allocating audio mdat ${A}`});return}u||(new DataView(I.buffer).setUint32(0,A),I.set(E.types.mdat,4))}else return;I.set(O,p);const Y=O.byteLength;p+=Y,f.push(new ts(!0,d,Y,0)),T=F}const P=f.length;if(!P)return;const _=f[f.length-1];this.nextAudioPts=v=T+l*_.duration;const C=u?new Uint8Array(0):E.moof(e.sequenceNumber++,b/l,ae({},e,{samples:f}));e.samples=[];const $=b/n,M=v/n,B={data1:C,data2:I,startPTS:$,endPTS:M,startDTS:$,endDTS:M,type:"audio",hasAudio:!0,hasVideo:!1,nb:P};return this.isAudioContiguous=!0,B}remuxEmptyAudio(e,t,i,s){const r=e.inputTimeScale,n=e.samplerate?e.samplerate:r,o=r/n,l=this.nextAudioPts,d=this._initDTS,h=d.baseTime*9e4/d.timescale,c=(l!==null?l:s.startDTS*r)+h,u=s.endDTS*r+h,f=o*Ji,m=Math.ceil((u-c)/f),g=Qi.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(S.warn("[mp4-remuxer]: remux empty Audio"),!g){S.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const p=[];for(let v=0;v<m;v++){const L=c+v*f;p.push({unit:g,pts:L,dts:L})}return e.samples=p,this.remuxAudio(e,t,i,!1)}}function ue(a,e){let t;if(e===null)return a;for(e<a?t=-8589934592:t=8589934592;Math.abs(a-e)>4294967296;)a+=t;return a}function zn(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function Zi(a,e,t,i){const s=a.samples.length;if(!s)return;const r=a.inputTimeScale;for(let o=0;o<s;o++){const l=a.samples[o];l.pts=ue(l.pts-t.baseTime*r/t.timescale,e*r)/r,l.dts=ue(l.dts-i.baseTime*r/i.timescale,e*r)/r}const n=a.samples;return a.samples=[],{samples:n}}function es(a,e,t){const i=a.samples.length;if(!i)return;const s=a.inputTimeScale;for(let n=0;n<i;n++){const o=a.samples[n];o.pts=ue(o.pts-t.baseTime*s/t.timescale,e*s)/s}a.samples.sort((n,o)=>n.pts-o.pts);const r=a.samples;return a.samples=[],{samples:r}}class ts{constructor(e,t,i,s){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=i,this.cts=s,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class qn{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,i,s){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(Os(e,s)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const s=this.initData=jt(e);s.audio&&(t=is(s.audio,Q.AUDIO)),s.video&&(i=is(s.video,Q.VIDEO));const r={};s.audio&&s.video?r.audiovideo={container:"video/mp4",codec:t+","+i,initSegment:e,id:"main"}:s.audio?r.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:s.video?r.video={container:"video/mp4",codec:i,initSegment:e,id:"main"}:S.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(e,t,i,s,r,n){var o,l;let{initPTS:d,lastEndTime:h}=this;const c={audio:void 0,video:void 0,text:s,id3:i,initSegment:void 0};k(h)||(h=this.lastEndTime=r||0);const u=t.samples;if(!(u!=null&&u.length))return c;const f={initPTS:void 0,timescale:1};let m=this.initData;if((o=m)!=null&&o.length||(this.generateInitSegment(u),m=this.initData),!((l=m)!=null&&l.length))return S.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const g=Ns(u,m),p=Ms(m,u),v=p===null?r:p;(Xn(d,v,r,g)||f.timescale!==d.timescale&&n)&&(f.initPTS=v-r,d&&d.timescale===1&&S.warn(`Adjusting initPTS by ${f.initPTS-d.baseTime}`),this.initPTS=d={baseTime:f.initPTS,timescale:1});const L=e?v-d.baseTime/d.timescale:h,y=L+g;Us(m,u,d.baseTime/d.timescale),g>0?this.lastEndTime=y:(S.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const b=!!m.audio,T=!!m.video;let I="";b&&(I+="audio"),T&&(I+="video");const A={data1:u,startPTS:L,startDTS:L,endPTS:y,endDTS:y,type:I,hasAudio:b,hasVideo:T,nb:1,dropped:0};return c.audio=A.type==="audio"?A:void 0,c.video=A.type!=="audio"?A:void 0,c.initSegment=f,c.id3=Zi(i,r,d,d),s.samples.length&&(c.text=es(s,r,d)),c}}function Xn(a,e,t,i){if(a===null)return!0;const s=Math.max(i,1),r=e-a.baseTime/a.timescale;return Math.abs(r-t)>s}function is(a,e){const t=a?.codec;if(t&&t.length>4)return t;if(e===Q.AUDIO){if(t==="ec-3"||t==="ac-3"||t==="alac")return t;if(t==="fLaC"||t==="Opus")return Ve(t,!1);const i="mp4a.40.5";return S.info(`Parsed audio codec "${t}" or audio object type not handled. Using "${i}"`),i}return S.warn(`Unhandled video codec "${t}"`),t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":"avc1.42e01e"}const ss=typeof self<"u"?self:void 0;let ve;try{ve=self.performance.now.bind(self.performance)}catch{S.debug("Unable to use Performance API on this environment"),ve=ss?.Date.now}const Dt=[{demux:kn,remux:qn},{demux:Te,remux:It},{demux:Fn,remux:It},{demux:Vn,remux:It}];class rs{constructor(e,t,i,s,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=i,this.vendor=s,this.id=r}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,i,s){const r=i.transmuxing;r.executeStart=ve();let n=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;s&&(this.currentTransmuxState=s);const{contiguous:d,discontinuity:h,trackSwitch:c,accurateTimeOffset:u,timeOffset:f,initSegmentChange:m}=s||o,{audioCodec:g,videoCodec:p,defaultInitPts:v,duration:L,initSegmentData:y}=l,b=Qn(n,t);if(b&&b.method==="AES-128"){const D=this.getDecrypter();if(D.isSync()){let P=D.softwareDecrypt(n,b.key.buffer,b.iv.buffer);if(i.part>-1&&(P=D.flush()),!P)return r.executeEnd=ve(),Ct(i);n=new Uint8Array(P)}else return this.decryptionPromise=D.webCryptoDecrypt(n,b.key.buffer,b.iv.buffer).then(P=>{const _=this.push(P,null,i);return this.decryptionPromise=null,_}),this.decryptionPromise}const T=this.needsProbing(h,c);if(T){const D=this.configureTransmuxer(n);if(D)return S.warn(`[transmuxer] ${D.message}`),this.observer.emit(x.ERROR,x.ERROR,{type:K.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:D,reason:D.message}),r.executeEnd=ve(),Ct(i)}(h||c||m||T)&&this.resetInitSegment(y,g,p,L,t),(h||m||T)&&this.resetInitialTimestamp(v),d||this.resetContiguity();const I=this.transmux(n,b,f,u,i),A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=ve(),I}flush(e){const t=e.transmuxing;t.executeStart=ve();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return r.then(()=>this.flush(e));const n=[],{timeOffset:o}=s;if(i){const c=i.flush();c&&n.push(this.push(c,null,e))}const{demuxer:l,remuxer:d}=this;if(!l||!d)return t.executeEnd=ve(),[Ct(e)];const h=l.flush(o);return Ze(h)?h.then(c=>(this.flushRemux(n,c,e),n)):(this.flushRemux(n,h,e),n)}flushRemux(e,t,i){const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:d}=this.currentTransmuxState;S.log(`[transmuxer.ts]: Flushed fragment ${i.sn}${i.part>-1?" p: "+i.part:""} of level ${i.level}`);const h=this.remuxer.remux(s,r,n,o,d,l,!0,this.id);e.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=ve()}resetInitialTimestamp(e){const{demuxer:t,remuxer:i}=this;!t||!i||(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,s,r){const{demuxer:n,remuxer:o}=this;!n||!o||(n.resetInitSegment(e,t,i,s),o.resetInitSegment(e,t,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,s,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,i,s,r):n=this.transmuxUnencrypted(e,i,s,r),n}transmuxUnencrypted(e,t,i,s){const{audioTrack:r,videoTrack:n,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,o,l,t,i,!1,this.id),chunkMeta:s}}transmuxSampleAes(e,t,i,s,r){return this.demuxer.demuxSampleAes(e,t,i).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,i,s,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:i,typeSupported:s,vendor:r}=this;let n;for(let u=0,f=Dt.length;u<f;u++){var o;if((o=Dt[u].demux)!=null&&o.probe(e)){n=Dt[u];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,d=this.remuxer,h=n.remux,c=n.demux;(!d||!(d instanceof h))&&(this.remuxer=new h(i,t,s,r)),(!l||!(l instanceof c))&&(this.demuxer=new c(i,t,s),this.probe=c.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Tt(this.config)),e}}function Qn(a,e){let t=null;return a.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Ct=a=>({remuxResult:{},chunkMeta:a});function Ze(a){return"then"in a&&a.then instanceof Function}class Jn{constructor(e,t,i,s,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=i,this.duration=s,this.defaultInitPts=r||null}}class Zn{constructor(e,t,i,s,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}var ns={exports:{}};(function(a){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(l,d,h){this.fn=l,this.context=d,this.once=h||!1}function r(l,d,h,c,u){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new s(h,c||l,u),m=t?t+d:d;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 n(l,d){--l._eventsCount===0?l._events=new i:delete l._events[d]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],h,c;if(this._eventsCount===0)return d;for(c in h=this._events)e.call(h,c)&&d.push(t?c.slice(1):c);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(h)):d},o.prototype.listeners=function(d){var h=t?t+d:d,c=this._events[h];if(!c)return[];if(c.fn)return[c.fn];for(var u=0,f=c.length,m=new Array(f);u<f;u++)m[u]=c[u].fn;return m},o.prototype.listenerCount=function(d){var h=t?t+d:d,c=this._events[h];return c?c.fn?1:c.length:0},o.prototype.emit=function(d,h,c,u,f,m){var g=t?t+d:d;if(!this._events[g])return!1;var p=this._events[g],v=arguments.length,L,y;if(p.fn){switch(p.once&&this.removeListener(d,p.fn,void 0,!0),v){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,h),!0;case 3:return p.fn.call(p.context,h,c),!0;case 4:return p.fn.call(p.context,h,c,u),!0;case 5:return p.fn.call(p.context,h,c,u,f),!0;case 6:return p.fn.call(p.context,h,c,u,f,m),!0}for(y=1,L=new Array(v-1);y<v;y++)L[y-1]=arguments[y];p.fn.apply(p.context,L)}else{var b=p.length,T;for(y=0;y<b;y++)switch(p[y].once&&this.removeListener(d,p[y].fn,void 0,!0),v){case 1:p[y].fn.call(p[y].context);break;case 2:p[y].fn.call(p[y].context,h);break;case 3:p[y].fn.call(p[y].context,h,c);break;case 4:p[y].fn.call(p[y].context,h,c,u);break;default:if(!L)for(T=1,L=new Array(v-1);T<v;T++)L[T-1]=arguments[T];p[y].fn.apply(p[y].context,L)}}return!0},o.prototype.on=function(d,h,c){return r(this,d,h,c,!1)},o.prototype.once=function(d,h,c){return r(this,d,h,c,!0)},o.prototype.removeListener=function(d,h,c,u){var f=t?t+d:d;if(!this._events[f])return this;if(!h)return n(this,f),this;var m=this._events[f];if(m.fn)m.fn===h&&(!u||m.once)&&(!c||m.context===c)&&n(this,f);else{for(var g=0,p=[],v=m.length;g<v;g++)(m[g].fn!==h||u&&!m[g].once||c&&m[g].context!==c)&&p.push(m[g]);p.length?this._events[f]=p.length===1?p[0]:p:n(this,f)}return this},o.prototype.removeAllListeners=function(d){var h;return d?(h=t?t+d:d,this._events[h]&&n(this,h)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,a.exports=o})(ns);var ea=ns.exports,as=Pt(ea);class ta{constructor(e,t,i,s){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=i,this.onFlush=s;const n=(h,c)=>{c=c||{},c.frag=this.frag,c.id=this.id,h===x.ERROR&&(this.error=c.error),this.hls.trigger(h,c)};this.observer=new as,this.observer.on(x.FRAG_DECRYPTED,n),this.observer.on(x.ERROR,n);const o=Re(r.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1},d=navigator.vendor;if(this.useWorker&&typeof Worker<"u"&&(r.workerPath||yn())){try{r.workerPath?(S.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Tn(r.workerPath)):(S.log(`injecting Web Worker for "${t}"`),this.workerContext=En()),this.onwmsg=u=>this.onWorkerMessage(u);const{worker:c}=this.workerContext;c.addEventListener("message",this.onwmsg),c.onerror=u=>{const f=new Error(`${u.message} (${u.filename}:${u.lineno})`);r.enableWorker=!1,S.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(x.ERROR,{type:K.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:f})},c.postMessage({cmd:"init",typeSupported:l,vendor:d,id:t,config:JSON.stringify(r)})}catch(c){S.warn(`Error setting up "${t}" Web Worker, fallback to inline`,c),this.resetWorker(),this.error=null,this.transmuxer=new rs(this.observer,l,r,d,t)}return}this.transmuxer=new rs(this.observer,l,r,d,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,i,s,r,n,o,l,d,h){var c,u;d.transmuxing.start=self.performance.now();const{transmuxer:f}=this,m=n?n.start:r.start,g=r.decryptdata,p=this.frag,v=!(p&&r.cc===p.cc),L=!(p&&d.level===p.level),y=p?d.sn-p.sn:-1,b=this.part?d.part-this.part.index:-1,T=y===0&&d.id>1&&d.id===p?.stats.chunkCount,I=!L&&(y===1||y===0&&(b===1||T&&b<=0)),A=self.performance.now();(L||y||r.stats.parsing.start===0)&&(r.stats.parsing.start=A),n&&(b||!I)&&(n.stats.parsing.start=A);const D=!(p&&((c=r.initSegment)==null?void 0:c.url)===((u=p.initSegment)==null?void 0:u.url)),P=new Zn(v,I,l,L,m,D);if(!I||v||D){S.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${d.sn} p: ${d.part} level: ${d.level} id: ${d.id}
9
- discontinuity: ${v}
10
- trackSwitch: ${L}
11
- contiguous: ${I}
12
- accurateTimeOffset: ${l}
13
- timeOffset: ${m}
14
- initSegmentChange: ${D}`);const _=new Jn(i,s,t,o,h);this.configureTransmuxer(_)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:g,chunkMeta:d,state:P},e instanceof ArrayBuffer?[e]:[]);else if(f){const _=f.push(e,g,d,P);Ze(_)?(f.async=!0,_.then(C=>{this.handleTransmuxComplete(C)}).catch(C=>{this.transmuxerError(C,d,"transmuxer-interface push error")})):(f.async=!1,this.handleTransmuxComplete(_))}}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 i=t.flush(e);Ze(i)||t.async?(Ze(i)||(i=Promise.resolve(i)),i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(i,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(x.ERROR,{type:K.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(i=>{this.handleTransmuxComplete(i)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data,i=this.hls;switch(t.event){case"init":{var s;const r=(s=this.workerContext)==null?void 0:s.objectURL;r&&self.URL.revokeObjectURL(r);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":S[t.data.logType]&&S[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,i.trigger(t.event,t.data);break}}}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)}}const ia=250,et=2,sa=.1,ra=.05;class na{constructor(e,t,i,s){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=i,this.hls=s}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:i,media:s,stalled:r}=this;if(s===null)return;const{currentTime:n,seeking:o}=s,l=this.seeking&&!o,d=!this.seeking&&o;if(this.seeking=o,n!==e){if(this.moved=!0,o||(this.nudgeRetry=0),r!==null){if(this.stallReported){const p=self.performance.now()-r;S.warn(`playback not stuck anymore @${n}, after ${Math.round(p)}ms`),this.stallReported=!1}this.stalled=null}return}if(d||l){this.stalled=null;return}if(s.paused&&!o||s.ended||s.playbackRate===0||!J.getBuffered(s).length){this.nudgeRetry=0;return}const h=J.bufferInfo(s,n,0),c=h.nextStart||0;if(o){const p=h.len>et,v=!c||t&&t.start<=n||c-n>et&&!this.fragmentTracker.getPartialFragment(n);if(p||v)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var u;if(!(h.len>0)&&!c)return;const v=Math.max(c,h.start||0)-n,L=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,b=(L==null||(u=L.details)==null?void 0:u.live)?L.details.targetduration*2:et,T=this.fragmentTracker.getPartialFragment(n);if(v>0&&(v<=b||T)){s.paused||this._trySkipBufferHole(T);return}}const f=self.performance.now();if(r===null){this.stalled=f;return}const m=f-r;if(!o&&m>=ia&&(this._reportStall(h),!this.media))return;const g=J.bufferInfo(s,n,i.maxBufferHole);this._tryFixBufferStall(g,m)}_tryFixBufferStall(e,t){const{config:i,fragmentTracker:s,media:r}=this;if(r===null)return;const n=r.currentTime,o=s.getPartialFragment(n);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>i.maxBufferHole||e.nextStart&&e.nextStart-n<i.maxBufferHole)&&t>i.highBufferWatchdogPeriod*1e3&&(S.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:i,stallReported:s}=this;if(!s&&i){this.stallReported=!0;const r=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${JSON.stringify(e)})`);S.warn(r.message),t.trigger(x.ERROR,{type:K.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:i,media:s}=this;if(s===null)return 0;const r=s.currentTime,n=J.bufferInfo(s,r,0),o=r<n.start?n.start:n.nextStart;if(o){const l=n.len<=t.maxBufferHole,d=n.len>0&&n.len<1&&s.readyState<3,h=o-r;if(h>0&&(l||d)){if(h>t.maxBufferHole){const{fragmentTracker:u}=this;let f=!1;if(r===0){const m=u.getAppendedFrag(0,z.MAIN);m&&o<m.end&&(f=!0)}if(!f){const m=e||u.getAppendedFrag(r,z.MAIN);if(m){let g=!1,p=m.end;for(;p<o;){const v=u.getPartialFragment(p);if(v)p+=v.duration;else{g=!0;break}}if(g)return 0}}}const c=Math.max(o+ra,r+sa);if(S.warn(`skipping hole, adjusting currentTime from ${r} to ${c}`),this.moved=!0,this.stalled=null,s.currentTime=c,e&&!e.gap){const u=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${c}`);i.trigger(x.ERROR,{type:K.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:e})}return c}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:i,nudgeRetry:s}=this;if(i===null)return;const r=i.currentTime;if(this.nudgeRetry++,s<e.nudgeMaxRetry){const n=r+(s+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${r} to ${n}`);S.warn(o.message),i.currentTime=n,t.trigger(x.ERROR,{type:K.MEDIA_ERROR,details:R.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const n=new Error(`Playhead still not moving while enough data buffered @${r} after ${e.nudgeMaxRetry} nudges`);S.error(n.message),t.trigger(x.ERROR,{type:K.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:n,fatal:!0})}}}const aa=100;class oa extends pn{constructor(e,t,i){super(e,t,i,"[stream-controller]",z.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(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.LEVEL_LOADING,this.onLevelLoading,this),e.on(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(x.ERROR,this.onError,this),e.on(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(x.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(x.BUFFER_CREATED,this.onBufferCreated,this),e.on(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(x.ERROR,this.onError,this),e.off(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(x.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(x.BUFFER_CREATED,this.onBufferCreated,this),e.off(x.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:i}=this;if(this.stopLoad(),this.setInterval(aa),this.level=-1,!this.startFragRequested){let s=i.startLevel;s===-1&&(i.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=i.firstAutoLevel),i.nextLoadLevel=s,this.level=i.loadLevel,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=w.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=w.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case w.WAITING_LEVEL:{const{levels:t,level:i}=this,s=t?.[i],r=s?.details;if(r&&(!r.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(r))break;this.state=w.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=w.IDLE;break}break}case w.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),i=this.retryDate;if(!i||t>=i||(e=this.media)!=null&&e.seeking){const{levels:s,level:r}=this,n=s?.[r];this.resetStartWhenNotLoaded(n||null),this.state=w.IDLE}}break}this.state===w.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=e.nextLoadLevel;if(!(i!=null&&i[r]))return;const n=i[r],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const g={};this.altAudio&&(g.type="video"),this.hls.trigger(x.BUFFER_EOS,g),this.state=w.ENDED;return}e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const d=n.details;if(!d||this.state===w.WAITING_LEVEL||d.live&&this.levelLastLoaded!==n){this.level=r,this.state=w.WAITING_LEVEL;return}const h=o.len,c=this.getMaxBufferLength(n.maxBitrate);if(h>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(u,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==ne.OK){var m;const p=((m=this.backtrackFragment)!=null?m:f).sn-d.startSN,v=d.fragments[p-1];v&&f.cc===v.cc&&(f=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,u)){if(!f.gap){const p=this.audioOnly&&!this.altAudio?Q.AUDIO:Q.VIDEO,v=(p===Q.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,p,z.MAIN)}f=this.getNextFragmentLoopLoading(f,d,o,z.MAIN,c)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,n,u))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);this.fragCurrent=e,s===ne.NOT_LOADED||s===ne.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,i)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,z.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(t!=null&&t.readyState){let i;const s=this.getAppendedFrag(t.currentTime);s&&s.start>1&&this.flushMainBuffer(0,s.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],d=this.fragLastKbps;d&&this.fragCurrent?i=this.fragCurrent.duration*l.maxBitrate/(1e3*d)+1:i=0}else i=0;const n=this.getBufferedFrag(t.currentTime+i);if(n){const o=this.followingBufferedFrag(n);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,d=o.duration,h=Math.max(n.end,l+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,d*(this.couldBacktrack?.5:.125)),d*(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 w.KEY_LOADING:case w.FRAG_LOADING:case w.FRAG_LOADING_WAITING_RETRY:case w.PARSING:case w.PARSED:this.state=w.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new na(this.config,i,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;k(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const i=this.getMainFwdBufferInfo();if(i===null||i.len===0){this.warn(`Main forward buffer length on "seeked" event ${i?i.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(x.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 i=!1,s=!1;t.levels.forEach(r=>{const n=r.audioCodec;n&&(i=i||n.indexOf("mp4a.40.2")!==-1,s=s||n.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=i&&s&&!vn(),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:i}=this;if(!i||this.state!==w.IDLE)return;const s=i[t.level];(!s.details||s.details.live&&this.levelLastLoaded!==s||this.waitForCdnTuneIn(s.details))&&(this.state=w.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s}=this,r=t.level,n=t.details,o=n.totalduration;if(!s){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${o}`);const l=s[r],d=this.fragCurrent;d&&(this.state===w.FRAG_LOADING||this.state===w.FRAG_LOADING_WAITING_RETRY)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let h=0;if(n.live||(i=l.details)!=null&&i.live){var c;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,l.details,(c=this.levelLastLoaded)==null?void 0:c.details)}if(l.details=n,this.levelLastLoaded=l,this.hls.trigger(x.LEVEL_UPDATED,{details:n,level:r}),this.state===w.WAITING_LEVEL){if(this.waitForCdnTuneIn(n))return;this.state=w.IDLE}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:i,part:s,payload:r}=e,{levels:n}=this;if(!n){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=n[i.level],l=o.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const d=o.videoCodec,h=l.PTSKnown||!l.live,c=(t=i.initSegment)==null?void 0:t.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new ta(this.hls,z.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=s?s.index:-1,g=m!==-1,p=new ki(i.level,i.sn,i.stats.chunkCount,r.byteLength,m,g),v=this.initPTS[i.cc];f.push(r,c,u,d,i,s,l.totalduration,h,p,v)}onAudioTrackSwitching(e,t){const i=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;i&&(r.trigger(x.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),r.trigger(x.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=t.id,s=!!this.hls.audioTracks[i].url;if(s){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=s,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,r,n=!1;for(const o in i){const l=i[o];if(l.id==="main"){if(r=o,s=l,o==="video"){const d=i[o];d&&(this.videoBuffer=d.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t;if(i&&i.type!==z.MAIN)return;if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===w.PARSED&&(this.state=w.IDLE);return}const r=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),i.sn!=="initSegment"&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}onError(e,t){var i;if(t.fatal){this.state=w.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(z.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===w.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===j.LEVEL&&(this.state=w.IDLE);break;case R.BUFFER_APPEND_ERROR:case R.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===R.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!J.getBuffered(e).length){const i=this.state!==w.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,i)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=w.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Q.AUDIO||this.audioOnly&&!this.altAudio){const i=(t===Q.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,t,z.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 i=this.startPosition;if(i>=0&&t<i){if(e.seeking){this.log(`could not seek to ${i}, already seeking at ${t}`);return}const s=J.getBuffered(e),n=(s.length?s.start(0):0)-i;n>0&&(n<this.config.maxBufferHole||n<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${n} to match buffer start`),i+=n,this.startPosition=i),this.log(`seek to target start position ${i} from current time ${t}`),e.currentTime=i}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(i=>{const{hls:s}=this;if(!i||this.fragContextChanged(e))return;t.fragmentError=0,this.state=w.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(),s.trigger(x.FRAG_LOADED,i),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const i="main",{hls:s}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:l,part:d,level:h}=o,{video:c,text:u,id3:f,initSegment:m}=r,{details:g}=h,p=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=w.PARSING,m){if(m!=null&&m.tracks){const y=l.initSegment||l;this._bufferInitSegment(h,m.tracks,y,n),s.trigger(x.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:i,tracks:m.tracks})}const v=m.initPTS,L=m.timescale;k(v)&&(this.initPTS[l.cc]={baseTime:v,timescale:L},s.trigger(x.INIT_PTS_FOUND,{frag:l,id:i,initPTS:v,timescale:L}))}if(c&&g&&l.sn!=="initSegment"){const v=g.fragments[l.sn-1-g.startSN],L=l.sn===g.startSN,y=!v||l.cc>v.cc;if(r.independent!==!1){const{startPTS:b,endPTS:T,startDTS:I,endDTS:A}=c;if(d)d.elementaryStreams[c.type]={startPTS:b,endPTS:T,startDTS:I,endDTS:A};else if(c.firstKeyFrame&&c.independent&&n.id===1&&!y&&(this.couldBacktrack=!0),c.dropped&&c.independent){const D=this.getMainFwdBufferInfo(),P=(D?D.end:this.getLoadPosition())+this.config.maxBufferHole,_=c.firstKeyFramePTS?c.firstKeyFramePTS:b;if(!L&&P<_-this.config.maxBufferHole&&!y){this.backtrack(l);return}else y&&(l.gap=!0);l.setElementaryStreamInfo(c.type,l.start,T,l.start,A,!0)}else L&&b>et&&(l.gap=!0);l.setElementaryStreamInfo(c.type,b,T,I,A),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(c,l,d,n,L||y)}else if(L||y)l.gap=!0;else{this.backtrack(l);return}}if(p){const{startPTS:v,endPTS:L,startDTS:y,endDTS:b}=p;d&&(d.elementaryStreams[Q.AUDIO]={startPTS:v,endPTS:L,startDTS:y,endDTS:b}),l.setElementaryStreamInfo(Q.AUDIO,v,L,y,b),this.bufferFragmentData(p,l,d,n)}if(g&&f!=null&&(t=f.samples)!=null&&t.length){const v={id:i,frag:l,details:g,samples:f.samples};s.trigger(x.FRAG_PARSING_METADATA,v)}if(g&&u){const v={id:i,frag:l,details:g,samples:u.samples};s.trigger(x.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(e,t,i,s){if(this.state!==w.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:r,video:n,audiovideo:o}=t;if(r){let l=e.audioCodec;const d=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),r.metadata.channelCount!==1&&d.indexOf("firefox")===-1&&(l="mp4a.40.5")),l&&l.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(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}]`)}n&&(n.levelCodec=e.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${n.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(x.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const h=t[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(x.BUFFER_APPENDING,{type:l,data:h,frag:i,part:null,chunkMeta:s,parent:i.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,z.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=w.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(J.isBuffered(e,i)?t=this.getAppendedFrag(i):J.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const s=this.fragPlaying,r=t.level;(!s||t.sn!==s.sn||s.level!==r)&&(this.fragPlaying=t,this.hls.trigger(x.FRAG_CHANGED,{frag:t}),(!s||s.level!==r)&&this.hls.trigger(x.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,i=this.currentFrag;if(i&&k(t)&&k(i.programDateTime)){const s=i.programDateTime+(t-i.start)*1e3;return new Date(s)}}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}}class Se{static get version(){return"1.5.8"}static isMSESupported(){return Ui()}static isSupported(){return xn()}static getMediaSource(){return Re()}static get Events(){return x}static get ErrorTypes(){return K}static get ErrorDetails(){return R}static get DefaultConfig(){return Se.defaultConfig?Se.defaultConfig:_i}static set DefaultConfig(e){Se.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new as,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,ms(e.debug||!1,"Hls instance");const t=this.config=Qr(Se.DefaultConfig,e);this.userConfig=e,t.progressive&&Jr(t);const{abrController:i,bufferController:s,capLevelController:r,errorController:n,fpsController:o}=t,l=new n(this),d=this.abrController=new i(this),h=this.bufferController=new s(this),c=this.capLevelController=new r(this),u=new o(this),f=new er(this),m=new lr(this),g=t.contentSteeringController,p=g?new g(this):null,v=this.levelController=new Zr(this,p),L=new en(this),y=new sn(this.config),b=this.streamController=new oa(this,L,y);c.setStreamController(b),u.setStreamController(b);const T=[f,v,b];p&&T.splice(1,0,p),this.networkControllers=T;const I=[d,h,c,u,m,L];this.audioTrackController=this.createController(t.audioTrackController,T);const A=t.audioStreamController;A&&T.push(new A(this,L,y)),this.subtitleTrackController=this.createController(t.subtitleTrackController,T);const D=t.subtitleStreamController;D&&T.push(new D(this,L,y)),this.createController(t.timelineController,I),y.emeController=this.emeController=this.createController(t.emeController,I),this.cmcdController=this.createController(t.cmcdController,I),this.latencyController=this.createController(dr,I),this.coreComponents=I,T.push(l);const P=l.onErrorOut;typeof P=="function"&&this.on(x.ERROR,P,l)}createController(e,t){if(e){const i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,s){this._emitter.off(e,t,i,s)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(i){if(S.error("An internal error happened while handling event "+e+'. Error message: "'+i.message+'". Here is a stacktrace:',i),!this.triggeringException){this.triggeringException=!0;const s=e===x.ERROR;this.trigger(x.ERROR,{type:K.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){S.log("destroy"),this.trigger(x.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){S.log("attachMedia"),this._media=e,this.trigger(x.MEDIA_ATTACHING,{media:e})}detachMedia(){S.log("detachMedia"),this.trigger(x.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,i=this.url,s=this.url=it.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,S.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(x.MANIFEST_LOADING,{url:e})}startLoad(e=-1){S.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){S.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){S.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){S.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){S.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){S.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){S.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){S.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){S.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(S.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){hr(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const i=e.length;for(let s=0;s<i;s++)if(e[s].maxBitrate>=t)return s;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:i}=this;let s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,i)for(let r=s;r--;){const n=e[r].attrs["HDCP-LEVEL"];if(n&&n<=i)return r}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Se.defaultConfig=void 0,Fe.KeySystemFormats,Fe.KeySystems,Fe.SubtitleStreamController,Fe.TimelineController;export{Se as Hls,Se as default};
1
+ function so(Fe){return Fe&&Fe.__esModule&&Object.prototype.hasOwnProperty.call(Fe,"default")?Fe.default:Fe}var Gi={exports:{}};(function(Fe,lo){(function er(tr){(function(yt,ge){Fe.exports=ge()})(this,function(){function yt(a,n){var i=Object.keys(a);if(Object.getOwnPropertySymbols){var e=Object.getOwnPropertySymbols(a);n&&(e=e.filter(function(t){return Object.getOwnPropertyDescriptor(a,t).enumerable})),i.push.apply(i,e)}return i}function ge(a){for(var n=1;n<arguments.length;n++){var i=arguments[n]!=null?arguments[n]:{};n%2?yt(Object(i),!0).forEach(function(e){Ki(a,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(i)):yt(Object(i)).forEach(function(e){Object.defineProperty(a,e,Object.getOwnPropertyDescriptor(i,e))})}return a}function Vi(a,n){if(typeof a!="object"||!a)return a;var i=a[Symbol.toPrimitive];if(i!==void 0){var e=i.call(a,n||"default");if(typeof e!="object")return e;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(a)}function rr(a){var n=Vi(a,"string");return typeof n=="symbol"?n:String(n)}function ir(a,n){for(var i=0;i<n.length;i++){var e=n[i];e.enumerable=e.enumerable||!1,e.configurable=!0,"value"in e&&(e.writable=!0),Object.defineProperty(a,rr(e.key),e)}}function he(a,n,i){return n&&ir(a.prototype,n),i&&ir(a,i),Object.defineProperty(a,"prototype",{writable:!1}),a}function Ki(a,n,i){return n=rr(n),n in a?Object.defineProperty(a,n,{value:i,enumerable:!0,configurable:!0,writable:!0}):a[n]=i,a}function ye(){return ye=Object.assign?Object.assign.bind():function(a){for(var n=1;n<arguments.length;n++){var i=arguments[n];for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(a[e]=i[e])}return a},ye.apply(this,arguments)}function Re(a,n){a.prototype=Object.create(n.prototype),a.prototype.constructor=a,We(a,n)}function Et(a){return Et=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(i){return i.__proto__||Object.getPrototypeOf(i)},Et(a)}function We(a,n){return We=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},We(a,n)}function Wi(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Xe(a,n,i){return Wi()?Xe=Reflect.construct.bind():Xe=function(t,r,s){var o=[null];o.push.apply(o,r);var l=Function.bind.apply(t,o),u=new l;return s&&We(u,s.prototype),u},Xe.apply(null,arguments)}function Yi(a){try{return Function.toString.call(a).indexOf("[native code]")!==-1}catch{return typeof a=="function"}}function ze(a){var n=typeof Map=="function"?new Map:void 0;return ze=function(e){if(e===null||!Yi(e))return e;if(typeof e!="function")throw new TypeError("Super expression must either be null or a function");if(typeof n<"u"){if(n.has(e))return n.get(e);n.set(e,t)}function t(){return Xe(e,arguments,Et(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),We(t,e)},ze(a)}function qi(a){if(a===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return a}function nr(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var ar={exports:{}};(function(a,n){(function(i){var e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,t=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,s=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,u,d){if(d=d||{},l=l.trim(),u=u.trim(),!u){if(!d.alwaysNormalize)return l;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");return f.path=o.normalizePath(f.path),o.buildURLFromParts(f)}var h=o.parseURL(u);if(!h)throw new Error("Error trying to parse relative URL.");if(h.scheme)return d.alwaysNormalize?(h.path=o.normalizePath(h.path),o.buildURLFromParts(h)):u;var c=o.parseURL(l);if(!c)throw new Error("Error trying to parse base URL.");if(!c.netLoc&&c.path&&c.path[0]!=="/"){var v=t.exec(c.path);c.netLoc=v[1],c.path=v[2]}c.netLoc&&!c.path&&(c.path="/");var m={scheme:c.scheme,netLoc:h.netLoc,path:null,params:h.params,query:h.query,fragment:h.fragment};if(!h.netLoc&&(m.netLoc=c.netLoc,h.path[0]!=="/"))if(!h.path)m.path=c.path,h.params||(m.params=c.params,h.query||(m.query=c.query));else{var g=c.path,p=g.substring(0,g.lastIndexOf("/")+1)+h.path;m.path=o.normalizePath(p)}return m.path===null&&(m.path=d.alwaysNormalize?o.normalizePath(h.path):h.path),o.buildURLFromParts(m)},parseURL:function(l){var u=e.exec(l);return u?{scheme:u[1]||"",netLoc:u[2]||"",path:u[3]||"",params:u[4]||"",query:u[5]||"",fragment:u[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(s,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};a.exports=o})()})(ar);var xt=ar.exports,O=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},ji=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=Xi},Xi=Number.MAX_SAFE_INTEGER||9007199254740991,x=function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a}({}),V=function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a}({}),_=function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.UNKNOWN="unknown",a}({}),Oe=function(){},Tt={trace:Oe,debug:Oe,log:Oe,warn:Oe,info:Oe,error:Oe},Ye=Tt;function zi(a){var n=self.console[a];return n?n.bind(self.console,"["+a+"] >"):Oe}function $i(a){for(var n=arguments.length,i=new Array(n>1?n-1:0),e=1;e<n;e++)i[e-1]=arguments[e];i.forEach(function(t){Ye[t]=a[t]?a[t].bind(a):zi(t)})}function sr(a,n){if(typeof console=="object"&&a===!0||typeof a=="object"){$i(a,"debug","log","info","warn","error");try{Ye.log('Debug logs enabled for "'+n+'" in hls.js version 1.5.8')}catch{Ye=Tt}}else Ye=Tt}var A=Ye,Qi=/^(\d+)x(\d+)$/,or=/(.+?)=(".*?"|.*?)(?:,|$)/g,ne=function(){function a(i){typeof i=="string"&&(i=a.parseAttrList(i)),ye(this,i)}var n=a.prototype;return n.decimalInteger=function(e){var t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t},n.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;for(var r=new Uint8Array(t.length/2),s=0;s<t.length/2;s++)r[s]=parseInt(t.slice(s*2,s*2+2),16);return r}else return null},n.hexadecimalIntegerAsNumber=function(e){var t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t},n.decimalFloatingPoint=function(e){return parseFloat(this[e])},n.optionalFloat=function(e,t){var r=this[e];return r?parseFloat(r):t},n.enumeratedString=function(e){return this[e]},n.bool=function(e){return this[e]==="YES"},n.decimalResolution=function(e){var t=Qi.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},a.parseAttrList=function(e){var t,r={},s='"';for(or.lastIndex=0;(t=or.exec(e))!==null;){var o=t[2];o.indexOf(s)===0&&o.lastIndexOf(s)===o.length-1&&(o=o.slice(1,-1));var l=t[1].trim();r[l]=o}return r},he(a,[{key:"clientAttrs",get:function(){return Object.keys(this).filter(function(e){return e.substring(0,2)==="X-"})}}]),a}();function Zi(a){return a!=="ID"&&a!=="CLASS"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function Ji(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"}var lr=function(){function a(n,i){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,i){var e=i.attr;for(var t in e)if(Object.prototype.hasOwnProperty.call(n,t)&&n[t]!==e[t]){A.warn('DATERANGE tag attribute: "'+t+'" does not match for tags with ID: "'+n.ID+'"'),this._badValueForSameId=t;break}n=ye(new ne({}),e,n)}if(this.attr=n,this._startDate=new Date(n["START-DATE"]),"END-DATE"in this.attr){var r=new Date(this.attr["END-DATE"]);O(r.getTime())&&(this._endDate=r)}}return he(a,[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){if(this._endDate)return this._endDate;var i=this.duration;return i!==null?new Date(this._startDate.getTime()+i*1e3):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var i=this.attr.decimalFloatingPoint("DURATION");if(O(i))return i}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&O(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}]),a}(),$e=function(){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}},$={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},ur=function(){function a(i){var e;this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams=(e={},e[$.AUDIO]=null,e[$.VIDEO]=null,e[$.AUDIOVIDEO]=null,e),this.baseurl=i}var n=a.prototype;return n.setByteRange=function(e,t){var r=e.split("@",2),s;r.length===1?s=t?.byteRangeEndOffset||0:s=parseInt(r[1]),this._byteRange=[s,parseInt(r[0])+s]},he(a,[{key:"byteRange",get:function(){return this._byteRange?this._byteRange:[]}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=xt.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(e){this._url=e}}]),a}(),St=function(a){Re(n,a);function n(e,t){var r;return r=a.call(this,t)||this,r._decryptdata=null,r.rawProgramDateTime=null,r.programDateTime=null,r.tagList=[],r.duration=0,r.sn=0,r.levelkeys=void 0,r.type=void 0,r.loader=null,r.keyLoader=null,r.level=-1,r.cc=0,r.startPTS=void 0,r.endPTS=void 0,r.startDTS=void 0,r.endDTS=void 0,r.start=0,r.deltaPTS=void 0,r.maxStartPTS=void 0,r.minEndPTS=void 0,r.stats=new $e,r.data=void 0,r.bitrateTest=!1,r.title=null,r.initSegment=null,r.endList=void 0,r.gap=void 0,r.urlId=0,r.type=e,r}var i=n.prototype;return i.setKeyFormat=function(t){if(this.levelkeys){var r=this.levelkeys[t];r&&!this._decryptdata&&(this._decryptdata=r.getDecryptData(this.sn))}},i.abortRequests=function(){var t,r;(t=this.loader)==null||t.abort(),(r=this.keyLoader)==null||r.abort()},i.setElementaryStreamInfo=function(t,r,s,o,l,u){u===void 0&&(u=!1);var d=this.elementaryStreams,f=d[t];if(!f){d[t]={startPTS:r,endPTS:s,startDTS:o,endDTS:l,partial:u};return}f.startPTS=Math.min(f.startPTS,r),f.endPTS=Math.max(f.endPTS,s),f.startDTS=Math.min(f.startDTS,o),f.endDTS=Math.max(f.endDTS,l)},i.clearElementaryStreamInfo=function(){var t=this.elementaryStreams;t[$.AUDIO]=null,t[$.VIDEO]=null,t[$.AUDIOVIDEO]=null},he(n,[{key:"decryptdata",get:function(){var t=this.levelkeys;if(!t&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var r=this.levelkeys.identity;if(r)this._decryptdata=r.getDecryptData(this.sn);else{var s=Object.keys(this.levelkeys);if(s.length===1)return this._decryptdata=this.levelkeys[s[0]].getDecryptData(this.sn)}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(this.programDateTime===null||!O(this.programDateTime))return null;var t=O(this.duration)?this.duration:0;return this.programDateTime+t*1e3}},{key:"encrypted",get:function(){var t;if((t=this._decryptdata)!=null&&t.encrypted)return!0;if(this.levelkeys){var r=Object.keys(this.levelkeys),s=r.length;if(s>1||s===1&&this.levelkeys[r[0]].encrypted)return!0}return!1}}]),n}(ur),en=function(a){Re(n,a);function n(i,e,t,r,s){var o;o=a.call(this,t)||this,o.fragOffset=0,o.duration=0,o.gap=!1,o.independent=!1,o.relurl=void 0,o.fragment=void 0,o.index=void 0,o.stats=new $e,o.duration=i.decimalFloatingPoint("DURATION"),o.gap=i.bool("GAP"),o.independent=i.bool("INDEPENDENT"),o.relurl=i.enumeratedString("URI"),o.fragment=e,o.index=r;var l=i.enumeratedString("BYTERANGE");return l&&o.setByteRange(l,s),s&&(o.fragOffset=s.fragOffset+s.duration),o}return he(n,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo)}}]),n}(ur),tn=10,rn=function(){function a(i){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=i}var n=a.prototype;return n.reloaded=function(e){if(!e){this.advanced=!0,this.updated=!0;return}var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&r>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay},he(a,[{key:"hasProgramDateTime",get:function(){return this.fragments.length?O(this.fragments[this.fragments.length-1].programDateTime):!1}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||tn}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;if(e>0){var t=this.driftEnd-this.driftStart;return t*1e3/e}return 1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}]),a}(),nn=void 0,an=nr(nn);function Me(a,n,i){return Uint8Array.prototype.slice?a.slice(n,i):new Uint8Array(Array.prototype.slice.call(a,n,i))}var Lt=function(n,i){return i+10<=n.length&&n[i]===73&&n[i+1]===68&&n[i+2]===51&&n[i+3]<255&&n[i+4]<255&&n[i+6]<128&&n[i+7]<128&&n[i+8]<128&&n[i+9]<128},fr=function(n,i){return i+10<=n.length&&n[i]===51&&n[i+1]===68&&n[i+2]===73&&n[i+3]<255&&n[i+4]<255&&n[i+6]<128&&n[i+7]<128&&n[i+8]<128&&n[i+9]<128},Qe=function(n,i){for(var e=i,t=0;Lt(n,i);){t+=10;var r=Ze(n,i+6);t+=r,fr(n,i+10)&&(t+=10),i+=t}if(t>0)return n.subarray(e,e+t)},Ze=function(n,i){var e=0;return e=(n[i]&127)<<21,e|=(n[i+1]&127)<<14,e|=(n[i+2]&127)<<7,e|=n[i+3]&127,e},sn=function(n,i){return Lt(n,i)&&Ze(n,i+6)+10<=n.length-i},dr=function(n){for(var i=cr(n),e=0;e<i.length;e++){var t=i[e];if(hr(t))return hn(t)}},hr=function(n){return n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp"},on=function(n){var i=String.fromCharCode(n[0],n[1],n[2],n[3]),e=Ze(n,4),t=10;return{type:i,size:e,data:n.subarray(t,t+e)}},cr=function(n){for(var i=0,e=[];Lt(n,i);){var t=Ze(n,i+6);i+=10;for(var r=i+t;i+8<r;){var s=on(n.subarray(i)),o=ln(s);o&&e.push(o),i+=s.size+10}fr(n,i)&&(i+=10)}return e},ln=function(n){return n.type==="PRIV"?un(n):n.type[0]==="W"?dn(n):fn(n)},un=function(n){if(!(n.size<2)){var i=we(n.data,!0),e=new Uint8Array(n.data.subarray(i.length+1));return{key:n.type,info:i,data:e.buffer}}},fn=function(n){if(!(n.size<2)){if(n.type==="TXXX"){var i=1,e=we(n.data.subarray(i),!0);i+=e.length+1;var t=we(n.data.subarray(i));return{key:n.type,info:e,data:t}}var r=we(n.data.subarray(1));return{key:n.type,data:r}}},dn=function(n){if(n.type==="WXXX"){if(n.size<2)return;var i=1,e=we(n.data.subarray(i),!0);i+=e.length+1;var t=we(n.data.subarray(i));return{key:n.type,info:e,data:t}}var r=we(n.data);return{key:n.type,data:r}},hn=function(n){if(n.data.byteLength===8){var i=new Uint8Array(n.data),e=i[3]&1,t=(i[4]<<23)+(i[5]<<15)+(i[6]<<7)+i[7];return t/=45,e&&(t+=4772185884e-2),Math.round(t)}},we=function(n,i){i===void 0&&(i=!1);var e=cn();if(e){var t=e.decode(n);if(i){var r=t.indexOf("\0");return r!==-1?t.substring(0,r):t}return t.replace(/\0/g,"")}for(var s=n.length,o,l,u,d="",f=0;f<s;){if(o=n[f++],o===0&&i)return d;if(o===0||o===3)continue;switch(o>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:d+=String.fromCharCode(o);break;case 12:case 13:l=n[f++],d+=String.fromCharCode((o&31)<<6|l&63);break;case 14:l=n[f++],u=n[f++],d+=String.fromCharCode((o&15)<<12|(l&63)<<6|(u&63)<<0);break}}return d},At;function cn(){if(!navigator.userAgent.includes("PlayStation 4"))return!At&&typeof self.TextDecoder<"u"&&(At=new self.TextDecoder("utf-8")),At}var vr={hexDump:function(n){for(var i="",e=0;e<n.length;e++){var t=n[e].toString(16);t.length<2&&(t="0"+t),i+=t}return i}},Je=Math.pow(2,32)-1,vn=[].push,gr={video:1,audio:2,id3:3,text:4};function se(a){return String.fromCharCode.apply(null,a)}function mr(a,n){var i=a[n]<<8|a[n+1];return i<0?65536+i:i}function N(a,n){var i=yr(a,n);return i<0?4294967296+i:i}function pr(a,n){var i=N(a,n);return i*=Math.pow(2,32),i+=N(a,n+4),i}function yr(a,n){return a[n]<<24|a[n+1]<<16|a[n+2]<<8|a[n+3]}function Rt(a,n,i){a[n]=i>>24,a[n+1]=i>>16&255,a[n+2]=i>>8&255,a[n+3]=i&255}function gn(a){for(var n=a.byteLength,i=0;i<n;){var e=N(a,i);if(e>8&&a[i+4]===109&&a[i+5]===111&&a[i+6]===111&&a[i+7]===102)return!0;i=e>1?i+e:n}return!1}function G(a,n){var i=[];if(!n.length)return i;for(var e=a.byteLength,t=0;t<e;){var r=N(a,t),s=se(a.subarray(t+4,t+8)),o=r>1?t+r:e;if(s===n[0])if(n.length===1)i.push(a.subarray(t+8,o));else{var l=G(a.subarray(t+8,o),n.slice(1));l.length&&vn.apply(i,l)}t=o}return i}function mn(a){var n=[],i=a[0],e=8,t=N(a,e);e+=4;var r=0,s=0;i===0?(r=N(a,e),s=N(a,e+4),e+=8):(r=pr(a,e),s=pr(a,e+8),e+=16),e+=2;var o=a.length+s,l=mr(a,e);e+=2;for(var u=0;u<l;u++){var d=e,f=N(a,d);d+=4;var h=f&2147483647,c=(f&2147483648)>>>31;if(c===1)return A.warn("SIDX has hierarchical references (not supported)"),null;var v=N(a,d);d+=4,n.push({referenceSize:h,subsegmentDuration:v,info:{duration:v/t,start:o,end:o+h-1}}),o+=h,d+=4,e=d}return{earliestPresentationTime:r,timescale:t,version:i,referencesCount:l,references:n}}function Er(a){for(var n=[],i=G(a,["moov","trak"]),e=0;e<i.length;e++){var t=i[e],r=G(t,["tkhd"])[0];if(r){var s=r[0],o=N(r,s===0?12:20),l=G(t,["mdia","mdhd"])[0];if(l){s=l[0];var u=N(l,s===0?12:20),d=G(t,["mdia","hdlr"])[0];if(d){var f=se(d.subarray(8,12)),h={soun:$.AUDIO,vide:$.VIDEO}[f];if(h){var c=G(t,["mdia","minf","stbl","stsd"])[0],v=pn(c);n[o]={timescale:u,type:h},n[h]=ge({timescale:u,id:o},v)}}}}}var m=G(a,["moov","mvex","trex"]);return m.forEach(function(g){var p=N(g,4),y=n[p];y&&(y.default={duration:N(g,12),flags:N(g,20)})}),n}function pn(a){var n=a.subarray(8),i=n.subarray(86),e=se(n.subarray(4,8)),t=e,r=e==="enca"||e==="encv";if(r){var s=G(n,[e])[0],o=s.subarray(e==="enca"?28:78),l=G(o,["sinf"]);l.forEach(function(pe){var de=G(pe,["schm"])[0];if(de){var le=se(de.subarray(4,8));if(le==="cbcs"||le==="cenc"){var Ue=G(pe,["frma"])[0];Ue&&(t=se(Ue))}}})}switch(t){case"avc1":case"avc2":case"avc3":case"avc4":{var u=G(i,["avcC"])[0];t+="."+et(u[1])+et(u[2])+et(u[3]);break}case"mp4a":{var d=G(n,[e])[0],f=G(d.subarray(28),["esds"])[0];if(f&&f.length>12){var h=4;if(f[h++]!==3)break;h=bt(f,h),h+=2;var c=f[h++];if(c&128&&(h+=2),c&64&&(h+=f[h++]),f[h++]!==4)break;h=bt(f,h);var v=f[h++];if(v===64)t+="."+et(v);else break;if(h+=12,f[h++]!==5)break;h=bt(f,h);var m=f[h++],g=(m&248)>>3;g===31&&(g+=1+((m&7)<<3)+((f[h]&224)>>5)),t+="."+g}break}case"hvc1":case"hev1":{var p=G(i,["hvcC"])[0],y=p[1],E=["","A","B","C"][y>>6],S=y&31,L=N(p,2),D=(y&32)>>5?"H":"L",R=p[12],T=p.subarray(6,12);t+="."+E+S,t+="."+L.toString(16).toUpperCase(),t+="."+D+R;for(var b="",I=T.length;I--;){var P=T[I];if(P||b){var C=P.toString(16).toUpperCase();b="."+C+b}}t+=b;break}case"dvh1":case"dvhe":{var w=G(i,["dvcC"])[0],M=w[2]>>1&127,F=w[2]<<5&32|w[3]>>3&31;t+="."+be(M)+"."+be(F);break}case"vp09":{var H=G(i,["vpcC"])[0],U=H[4],W=H[5],K=H[6]>>4&15;t+="."+be(U)+"."+be(W)+"."+be(K);break}case"av01":{var B=G(i,["av1C"])[0],Q=B[1]>>>5,q=B[1]&31,J=B[2]>>>7?"H":"M",ee=(B[2]&64)>>6,re=(B[2]&32)>>5,Z=Q===2&&ee?re?12:10:ee?10:8,X=(B[2]&16)>>4,Pe=(B[2]&8)>>3,Ee=(B[2]&4)>>2,te=B[2]&3,ce=1,ve=1,ie=1,z=0;t+="."+Q+"."+be(q)+J+"."+be(Z)+"."+X+"."+Pe+Ee+te+"."+be(ce)+"."+be(ve)+"."+be(ie)+"."+z;break}}return{codec:t,encrypted:r}}function bt(a,n){for(var i=n+5;a[n++]&128&&n<i;);return n}function et(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function be(a){return(a<10?"0":"")+a}function yn(a,n){if(!a||!n)return a;var i=n.keyId;if(i&&n.isCommonEncryption){var e=G(a,["moov","trak"]);e.forEach(function(t){var r=G(t,["mdia","minf","stbl","stsd"])[0],s=r.subarray(8),o=G(s,["enca"]),l=o.length>0;l||(o=G(s,["encv"])),o.forEach(function(u){var d=l?u.subarray(28):u.subarray(78),f=G(d,["sinf"]);f.forEach(function(h){var c=En(h);if(c){var v=c.subarray(8,24);v.some(function(m){return m!==0})||(A.log("[eme] Patching keyId in 'enc"+(l?"a":"v")+">sinf>>tenc' box: "+vr.hexDump(v)+" -> "+vr.hexDump(i)),c.set(i,8))}})})})}return a}function En(a){var n=G(a,["schm"])[0];if(n){var i=se(n.subarray(4,8));if(i==="cbcs"||i==="cenc")return G(a,["schi","tenc"])[0]}return A.error("[eme] missing 'schm' box"),null}function xn(a,n){return G(n,["moof","traf"]).reduce(function(i,e){var t=G(e,["tfdt"])[0],r=t[0],s=G(e,["tfhd"]).reduce(function(o,l){var u=N(l,4),d=a[u];if(d){var f=N(t,4);if(r===1){if(f===Je)return A.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;f*=Je+1,f+=N(t,8)}var h=d.timescale||9e4,c=f/h;if(O(c)&&(o===null||c<o))return c}return o},null);return s!==null&&O(s)&&(i===null||s<i)?s:i},null)}function Tn(a,n){for(var i=0,e=0,t=0,r=G(a,["moof","traf"]),s=0;s<r.length;s++){var o=r[s],l=G(o,["tfhd"])[0],u=N(l,4),d=n[u];if(d){var f=d.default,h=N(l,0)|f?.flags,c=f?.duration;h&8&&(h&2?c=N(l,12):c=N(l,8));for(var v=d.timescale||9e4,m=G(o,["trun"]),g=0;g<m.length;g++){if(i=Sn(m[g]),!i&&c){var p=N(m[g],4);i=c*p}d.type===$.VIDEO?e+=i/v:d.type===$.AUDIO&&(t+=i/v)}}}if(e===0&&t===0){for(var y=1/0,E=0,S=0,L=G(a,["sidx"]),D=0;D<L.length;D++){var R=mn(L[D]);if(R!=null&&R.references){y=Math.min(y,R.earliestPresentationTime/R.timescale);var T=R.references.reduce(function(b,I){return b+I.info.duration||0},0);E=Math.max(E,T+R.earliestPresentationTime/R.timescale),S=E-y}}if(S&&O(S))return S}return e||t}function Sn(a){var n=N(a,0),i=8;n&1&&(i+=4),n&4&&(i+=4);for(var e=0,t=N(a,4),r=0;r<t;r++){if(n&256){var s=N(a,i);e+=s,i+=4}n&512&&(i+=4),n&1024&&(i+=4),n&2048&&(i+=4)}return e}function Ln(a,n,i){G(n,["moof","traf"]).forEach(function(e){G(e,["tfhd"]).forEach(function(t){var r=N(t,4),s=a[r];if(s){var o=s.timescale||9e4;G(e,["tfdt"]).forEach(function(l){var u=l[0],d=i*o;if(d){var f=N(l,4);if(u===0)f-=d,f=Math.max(f,0),Rt(l,4,f);else{f*=Math.pow(2,32),f+=N(l,8),f-=d,f=Math.max(f,0);var h=Math.floor(f/(Je+1)),c=Math.floor(f%(Je+1));Rt(l,4,h),Rt(l,8,c)}}})}})})}function An(a){var n={valid:null,remainder:null},i=G(a,["moof"]);if(i.length<2)return n.remainder=a,n;var e=i[i.length-1];return n.valid=Me(a,0,e.byteOffset-8),n.remainder=Me(a,e.byteOffset-8),n}function xe(a,n){var i=new Uint8Array(a.length+n.length);return i.set(a),i.set(n,a.length),i}function xr(a,n){var i=[],e=n.samples,t=n.timescale,r=n.id,s=!1,o=G(e,["moof"]);return o.map(function(l){var u=l.byteOffset-8,d=G(l,["traf"]);d.map(function(f){var h=G(f,["tfdt"]).map(function(c){var v=c[0],m=N(c,4);return v===1&&(m*=Math.pow(2,32),m+=N(c,8)),m/t})[0];return h!==void 0&&(a=h),G(f,["tfhd"]).map(function(c){var v=N(c,4),m=N(c,0)&16777215,g=(m&1)!==0,p=(m&2)!==0,y=(m&8)!==0,E=0,S=(m&16)!==0,L=0,D=(m&32)!==0,R=8;v===r&&(g&&(R+=8),p&&(R+=4),y&&(E=N(c,R),R+=4),S&&(L=N(c,R),R+=4),D&&(R+=4),n.type==="video"&&(s=Rn(n.codec)),G(f,["trun"]).map(function(T){var b=T[0],I=N(T,0)&16777215,P=(I&1)!==0,C=0,w=(I&4)!==0,M=(I&256)!==0,F=0,H=(I&512)!==0,U=0,W=(I&1024)!==0,K=(I&2048)!==0,B=0,Q=N(T,4),q=8;P&&(C=N(T,q),q+=4),w&&(q+=4);for(var J=C+u,ee=0;ee<Q;ee++){if(M?(F=N(T,q),q+=4):F=E,H?(U=N(T,q),q+=4):U=L,W&&(q+=4),K&&(b===0?B=N(T,q):B=yr(T,q),q+=4),n.type===$.VIDEO)for(var re=0;re<U;){var Z=N(e,J);if(J+=4,bn(s,e[J])){var X=e.subarray(J,J+Z);Tr(X,s?2:1,a+B/t,i)}J+=Z,re+=Z+4}a+=F/t}}))})})}),i}function Rn(a){if(!a)return!1;var n=a.indexOf("."),i=n<0?a:a.substring(0,n);return i==="hvc1"||i==="hev1"||i==="dvh1"||i==="dvhe"}function bn(a,n){if(a){var i=n>>1&63;return i===39||i===40}else{var e=n&31;return e===6}}function Tr(a,n,i,e){var t=Sr(a),r=0;r+=n;for(var s=0,o=0,l=0;r<t.length;){s=0;do{if(r>=t.length)break;l=t[r++],s+=l}while(l===255);o=0;do{if(r>=t.length)break;l=t[r++],o+=l}while(l===255);var u=t.length-r,d=r;if(o<u)r+=o;else if(o>u){A.error("Malformed SEI payload. "+o+" is too small, only "+u+" bytes left to parse.");break}if(s===4){var f=t[d++];if(f===181){var h=mr(t,d);if(d+=2,h===49){var c=N(t,d);if(d+=4,c===1195456820){var v=t[d++];if(v===3){var m=t[d++],g=31&m,p=64&m,y=p?2+g*3:0,E=new Uint8Array(y);if(p){E[0]=m;for(var S=1;S<y;S++)E[S]=t[d++]}e.push({type:v,payloadType:s,pts:i,bytes:E})}}}}}else if(s===5&&o>16){for(var L=[],D=0;D<16;D++){var R=t[d++].toString(16);L.push(R.length==1?"0"+R:R),(D===3||D===5||D===7||D===9)&&L.push("-")}for(var T=o-16,b=new Uint8Array(T),I=0;I<T;I++)b[I]=t[d++];e.push({payloadType:s,pts:i,uuid:L.join(""),userData:we(b),userDataBytes:b})}}}function Sr(a){for(var n=a.byteLength,i=[],e=1;e<n-2;)a[e]===0&&a[e+1]===0&&a[e+2]===3?(i.push(e+2),e+=2):e++;if(i.length===0)return a;var t=n-i.length,r=new Uint8Array(t),s=0;for(e=0;e<t;s++,e++)s===i[0]&&(s++,i.shift()),r[e]=a[s];return r}function In(a){var n=a[0],i="",e="",t=0,r=0,s=0,o=0,l=0,u=0;if(n===0){for(;se(a.subarray(u,u+1))!=="\0";)i+=se(a.subarray(u,u+1)),u+=1;for(i+=se(a.subarray(u,u+1)),u+=1;se(a.subarray(u,u+1))!=="\0";)e+=se(a.subarray(u,u+1)),u+=1;e+=se(a.subarray(u,u+1)),u+=1,t=N(a,12),r=N(a,16),o=N(a,20),l=N(a,24),u=28}else if(n===1){u+=4,t=N(a,u),u+=4;var d=N(a,u);u+=4;var f=N(a,u);for(u+=4,s=Math.pow(2,32)*d+f,ji(s)||(s=Number.MAX_SAFE_INTEGER,A.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=N(a,u),u+=4,l=N(a,u),u+=4;se(a.subarray(u,u+1))!=="\0";)i+=se(a.subarray(u,u+1)),u+=1;for(i+=se(a.subarray(u,u+1)),u+=1;se(a.subarray(u,u+1))!=="\0";)e+=se(a.subarray(u,u+1)),u+=1;e+=se(a.subarray(u,u+1)),u+=1}var h=a.subarray(u,a.byteLength);return{schemeIdUri:i,value:e,timeScale:t,presentationTime:s,presentationTimeDelta:r,eventDuration:o,id:l,payload:h}}var _n=function(){a.clearKeyUriToKeyIdMap=function(){};function a(i,e,t,r,s){r===void 0&&(r=[1]),s===void 0&&(s=null),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=i,this.uri=e,this.keyFormat=t,this.keyFormatVersions=r,this.iv=s,this.encrypted=i?i!=="NONE":!1,this.isCommonEncryption=this.encrypted&&i!=="AES-128"}var n=a.prototype;return n.isSupported=function(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES"}return!1},n.getDecryptData=function(e){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof e!="number"&&(this.method==="AES-128"&&!this.iv&&A.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),e=0);var t=Dn(e),r=new a(this.method,this.uri,"identity",this.keyFormatVersions,t);return r}return this},a}();function Dn(a){for(var n=new Uint8Array(16),i=12;i<16;i++)n[i]=a>>8*(15-i)&255;return n}function Ne(a){if(a===void 0&&(a=!0),!(typeof self>"u")){var n=(a||!self.MediaSource)&&self.ManagedMediaSource;return n||self.MediaSource||self.WebKitMediaSource}}function Cn(a){return typeof self<"u"&&a===self.ManagedMediaSource}var tt={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 Pn(a,n){var i=tt[n];return!!i&&!!i[a.slice(0,4)]}function It(a,n,i){return i===void 0&&(i=!0),!a.split(",").some(function(e){return!Lr(e,n,i)})}function Lr(a,n,i){var e;i===void 0&&(i=!0);var t=Ne(i);return(e=t?.isTypeSupported(_t(a,n)))!=null?e:!1}function _t(a,n){return n+'/mp4;codecs="'+a+'"'}function Ar(a){if(a){var n=a.substring(0,4);return tt.video[n]}return 2}function rt(a){return a.split(",").reduce(function(n,i){var e=tt.video[i];return e?(e*2+n)/(n?3:2):(tt.audio[i]+n)/(n?2:1)},0)}var Dt={};function wn(a,n){if(n===void 0&&(n=!0),Dt[a])return Dt[a];for(var i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[a],e=0;e<i.length;e++)if(Lr(i[e],"audio",n))return Dt[a]=i[e],i[e];return a}var kn=/flac|opus/i;function it(a,n){return n===void 0&&(n=!0),a.replace(kn,function(i){return wn(i.toLowerCase(),n)})}function Rr(a,n){return a&&a!=="mp4a"?a:n&&n.split(",")[0]}function Fn(a){var n=a.split(".");if(n.length>2){var i=n.shift()+".";return i+=parseInt(n.shift()).toString(16),i+=("000"+parseInt(n.shift()).toString(16)).slice(-4),i}return a}var br=/#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,Ir=/#EXT-X-MEDIA:(.*)/g,On=/^#EXT(?:INF|-X-TARGETDURATION):/m,_r=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),Mn=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("|")),qe=function(){function a(){}return a.findGroup=function(i,e){for(var t=0;t<i.length;t++){var r=i[t];if(r.id===e)return r}},a.resolve=function(i,e){return xt.buildAbsoluteURL(e,i,{alwaysNormalize:!0})},a.isMediaPlaylist=function(i){return On.test(i)},a.parseMasterPlaylist=function(i,e){var t=!1,r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:t},s=[];br.lastIndex=0;for(var o;(o=br.exec(i))!=null;)if(o[1]){var l,u=new ne(o[1]),d=o[2],f={attrs:u,bitrate:u.decimalInteger("BANDWIDTH")||u.decimalInteger("AVERAGE-BANDWIDTH"),name:u.NAME,url:a.resolve(d,e)},h=u.decimalResolution("RESOLUTION");h&&(f.width=h.width,f.height=h.height),Nn(u.CODECS,f),(l=f.unknownCodecs)!=null&&l.length||s.push(f),r.levels.push(f)}else if(o[3]){var c=o[3],v=o[4];switch(c){case"SESSION-DATA":{var m=new ne(v),g=m["DATA-ID"];g&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[g]=m);break}case"SESSION-KEY":{var p=Dr(v,e);p.encrypted&&p.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(p)):A.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+v+'"');break}case"DEFINE":break;case"CONTENT-STEERING":{var y=new ne(v);r.contentSteering={uri:a.resolve(y["SERVER-URI"],e),pathwayId:y["PATHWAY-ID"]||"."};break}case"START":{r.startTimeOffset=Cr(v);break}}}var E=s.length>0&&s.length<r.levels.length;return r.levels=E?s:r.levels,r.levels.length===0&&(r.playlistParsingError=new Error("no levels found in manifest")),r},a.parseMasterPlaylistMedia=function(i,e,t){var r,s={},o=t.levels,l={AUDIO:o.map(function(L){return{id:L.attrs.AUDIO,audioCodec:L.audioCodec}}),SUBTITLES:o.map(function(L){return{id:L.attrs.SUBTITLES,textCodec:L.textCodec}}),"CLOSED-CAPTIONS":[]},u=0;for(Ir.lastIndex=0;(r=Ir.exec(i))!==null;){var d=new ne(r[1]),f=d.TYPE;if(f){var h=l[f],c=s[f]||[];s[f]=c;var v=d.LANGUAGE,m=d["ASSOC-LANGUAGE"],g=d.CHANNELS,p=d.CHARACTERISTICS,y=d["INSTREAM-ID"],E={attrs:d,bitrate:0,id:u++,groupId:d["GROUP-ID"]||"",name:d.NAME||v||"",type:f,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:v,url:d.URI?a.resolve(d.URI,e):""};if(m&&(E.assocLang=m),g&&(E.channels=g),p&&(E.characteristics=p),y&&(E.instreamId=y),h!=null&&h.length){var S=a.findGroup(h,E.groupId)||h[0];Pr(E,S,"audioCodec"),Pr(E,S,"textCodec")}c.push(E)}}return s},a.parseLevelPlaylist=function(i,e,t,r,s,o){var l=new rn(e),u=l.fragments,d=null,f=0,h=0,c=0,v=0,m=null,g=new St(r,e),p,y,E,S=-1,L=!1,D=null;for(_r.lastIndex=0,l.m3u8=i,l.hasVariableRefs=!1;(p=_r.exec(i))!==null;){L&&(L=!1,g=new St(r,e),g.start=c,g.sn=f,g.cc=v,g.level=t,d&&(g.initSegment=d,g.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null,D&&(g.setByteRange(D),D=null)));var R=p[1];if(R){g.duration=parseFloat(R);var T=(" "+p[2]).slice(1);g.title=T||null,g.tagList.push(T?["INF",R,T]:["INF",R])}else if(p[3]){if(O(g.duration)){g.start=c,E&&Fr(g,E,l),g.sn=f,g.level=t,g.cc=v,u.push(g);var b=(" "+p[3]).slice(1);g.relurl=b,wr(g,m),m=g,c+=g.duration,f++,h=0,L=!0}}else if(p[4]){var I=(" "+p[4]).slice(1);m?g.setByteRange(I,m):g.setByteRange(I)}else if(p[5])g.rawProgramDateTime=(" "+p[5]).slice(1),g.tagList.push(["PROGRAM-DATE-TIME",g.rawProgramDateTime]),S===-1&&(S=u.length);else{if(p=p[0].match(Mn),!p){A.warn("No matches on slow regex match for level playlist!");continue}for(y=1;y<p.length&&!(typeof p[y]<"u");y++);var P=(" "+p[y]).slice(1),C=(" "+p[y+1]).slice(1),w=p[y+2]?(" "+p[y+2]).slice(1):"";switch(P){case"PLAYLIST-TYPE":l.type=C.toUpperCase();break;case"MEDIA-SEQUENCE":f=l.startSN=parseInt(C);break;case"SKIP":{var M=new ne(C),F=M.decimalInteger("SKIPPED-SEGMENTS");if(O(F)){l.skippedSegments=F;for(var H=F;H--;)u.unshift(null);f+=F}var U=M.enumeratedString("RECENTLY-REMOVED-DATERANGES");U&&(l.recentlyRemovedDateranges=U.split(" "));break}case"TARGETDURATION":l.targetduration=Math.max(parseInt(C),1);break;case"VERSION":l.version=parseInt(C);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":l.live=!1;break;case"#":(C||w)&&g.tagList.push(w?[C,w]:[C]);break;case"DISCONTINUITY":v++,g.tagList.push(["DIS"]);break;case"GAP":g.gap=!0,g.tagList.push([P]);break;case"BITRATE":g.tagList.push([P,C]);break;case"DATERANGE":{var W=new ne(C),K=new lr(W,l.dateRanges[W.ID]);K.isValid||l.skippedSegments?l.dateRanges[K.id]=K:A.warn('Ignoring invalid DATERANGE tag: "'+C+'"'),g.tagList.push(["EXT-X-DATERANGE",C]);break}case"DEFINE":break;case"DISCONTINUITY-SEQUENCE":v=parseInt(C);break;case"KEY":{var B=Dr(C,e);if(B.isSupported()){if(B.method==="NONE"){E=void 0;break}E||(E={}),E[B.keyFormat]&&(E=ye({},E)),E[B.keyFormat]=B}else A.warn('[Keys] Ignoring invalid EXT-X-KEY tag: "'+C+'"');break}case"START":l.startTimeOffset=Cr(C);break;case"MAP":{var Q=new ne(C);if(g.duration){var q=new St(r,e);kr(q,Q,t,E),d=q,g.initSegment=d,d.rawProgramDateTime&&!g.rawProgramDateTime&&(g.rawProgramDateTime=d.rawProgramDateTime)}else{var J=g.byteRangeEndOffset;if(J){var ee=g.byteRangeStartOffset;D=J-ee+"@"+ee}else D=null;kr(g,Q,t,E),d=g,L=!0}break}case"SERVER-CONTROL":{var re=new ne(C);l.canBlockReload=re.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=re.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&re.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=re.optionalFloat("PART-HOLD-BACK",0),l.holdBack=re.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{var Z=new ne(C);l.partTarget=Z.decimalFloatingPoint("PART-TARGET");break}case"PART":{var X=l.partList;X||(X=l.partList=[]);var Pe=h>0?X[X.length-1]:void 0,Ee=h++,te=new ne(C),ce=new en(te,g,e,Ee,Pe);X.push(ce),g.duration+=ce.duration;break}case"PRELOAD-HINT":{var ve=new ne(C);l.preloadHint=ve;break}case"RENDITION-REPORT":{var ie=new ne(C);l.renditionReports=l.renditionReports||[],l.renditionReports.push(ie);break}default:A.warn("line parsed but not handled: "+p);break}}}m&&!m.relurl?(u.pop(),c-=m.duration,l.partList&&(l.fragmentHint=m)):l.partList&&(wr(g,m),g.cc=v,l.fragmentHint=g,E&&Fr(g,E,l));var z=u.length,pe=u[0],de=u[z-1];if(c+=l.skippedSegments*l.targetduration,c>0&&z&&de){l.averagetargetduration=c/z;var le=de.sn;l.endSN=le!=="initSegment"?le:0,l.live||(de.endList=!0),pe&&(l.startCC=pe.cc)}else l.endSN=0,l.startCC=0;return l.fragmentHint&&(c+=l.fragmentHint.duration),l.totalduration=c,l.endCC=v,S>0&&Bn(u,S),l},a}();function Dr(a,n,i){var e,t,r=new ne(a),s=(e=r.METHOD)!=null?e:"",o=r.URI,l=r.hexadecimalInteger("IV"),u=r.KEYFORMATVERSIONS,d=(t=r.KEYFORMAT)!=null?t:"identity";o&&r.IV&&!l&&A.error("Invalid IV: "+r.IV);var f=o?qe.resolve(o,n):"",h=(u||"1").split("/").map(Number).filter(Number.isFinite);return new _n(s,f,d,h,l)}function Cr(a){var n=new ne(a),i=n.decimalFloatingPoint("TIME-OFFSET");return O(i)?i:null}function Nn(a,n){var i=(a||"").split(/[ ,]+/).filter(function(e){return e});["video","audio","text"].forEach(function(e){var t=i.filter(function(r){return Pn(r,e)});t.length&&(n[e+"Codec"]=t.join(","),i=i.filter(function(r){return t.indexOf(r)===-1}))}),n.unknownCodecs=i}function Pr(a,n,i){var e=n[i];e&&(a[i]=e)}function Bn(a,n){for(var i=a[n],e=n;e--;){var t=a[e];if(!t)return;t.programDateTime=i.programDateTime-t.duration*1e3,i=t}}function wr(a,n){a.rawProgramDateTime?a.programDateTime=Date.parse(a.rawProgramDateTime):n!=null&&n.programDateTime&&(a.programDateTime=n.endProgramDateTime),O(a.programDateTime)||(a.programDateTime=null,a.rawProgramDateTime=null)}function kr(a,n,i,e){a.relurl=n.URI,n.BYTERANGE&&a.setByteRange(n.BYTERANGE),a.level=i,a.sn="initSegment",e&&(a.levelkeys=e),a.initSegment=null}function Fr(a,n,i){a.levelkeys=n;var e=i.encryptedFragments;(!e.length||e[e.length-1].levelkeys!==n)&&Object.keys(n).some(function(t){return n[t].isCommonEncryption})&&e.push(a)}var Y={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},j={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function Or(a){var n=a.type;switch(n){case Y.AUDIO_TRACK:return j.AUDIO;case Y.SUBTITLE_TRACK:return j.SUBTITLE;default:return j.MAIN}}function Ct(a,n){var i=a.url;return(i===void 0||i.indexOf("data:")===0)&&(i=n.url),i}var Un=function(){function a(i){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=i,this.registerListeners()}var n=a.prototype;return n.startLoad=function(e){},n.stopLoad=function(){this.destroyInternalLoaders()},n.registerListeners=function(){var e=this.hls;e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.LEVEL_LOADING,this.onLevelLoading,this),e.on(x.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(x.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},n.unregisterListeners=function(){var e=this.hls;e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.LEVEL_LOADING,this.onLevelLoading,this),e.off(x.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(x.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},n.createInternalLoader=function(e){var t=this.hls.config,r=t.pLoader,s=t.loader,o=r||s,l=new o(t);return this.loaders[e.type]=l,l},n.getInternalLoader=function(e){return this.loaders[e.type]},n.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},n.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},n.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},n.onManifestLoading=function(e,t){var r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Y.MANIFEST,url:r,deliveryDirectives:null})},n.onLevelLoading=function(e,t){var r=t.id,s=t.level,o=t.pathwayId,l=t.url,u=t.deliveryDirectives;this.load({id:r,level:s,pathwayId:o,responseType:"text",type:Y.LEVEL,url:l,deliveryDirectives:u})},n.onAudioTrackLoading=function(e,t){var r=t.id,s=t.groupId,o=t.url,l=t.deliveryDirectives;this.load({id:r,groupId:s,level:null,responseType:"text",type:Y.AUDIO_TRACK,url:o,deliveryDirectives:l})},n.onSubtitleTrackLoading=function(e,t){var r=t.id,s=t.groupId,o=t.url,l=t.deliveryDirectives;this.load({id:r,groupId:s,level:null,responseType:"text",type:Y.SUBTITLE_TRACK,url:o,deliveryDirectives:l})},n.load=function(e){var t,r=this,s=this.hls.config,o=this.getInternalLoader(e);if(o){var l=o.context;if(l&&l.url===e.url&&l.level===e.level){A.trace("[playlist-loader]: playlist request ongoing");return}A.log("[playlist-loader]: aborting previous loader for type: "+e.type),o.abort()}var u;if(e.type===Y.MANIFEST?u=s.manifestLoadPolicy.default:u=ye({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),o=this.createInternalLoader(e),O((t=e.deliveryDirectives)==null?void 0:t.part)){var d;if(e.type===Y.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===Y.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===Y.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){var f=d.partTarget,h=d.targetduration;if(f&&h){var c=Math.max(f*3,h*.8)*1e3;u=ye({},u,{maxTimeToFirstByteMs:Math.min(c,u.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(c,u.maxTimeToFirstByteMs)})}}}var v=u.errorRetry||u.timeoutRetry||{},m={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:v.maxNumRetry||0,retryDelay:v.retryDelayMs||0,maxRetryDelay:v.maxRetryDelayMs||0},g={onSuccess:function(y,E,S,L){var D=r.getInternalLoader(S);r.resetInternalLoader(S.type);var R=y.data;if(R.indexOf("#EXTM3U")!==0){r.handleManifestParsingError(y,S,new Error("no EXTM3U delimiter"),L||null,E);return}E.parsing.start=performance.now(),qe.isMediaPlaylist(R)?r.handleTrackOrLevelPlaylist(y,E,S,L||null,D):r.handleMasterPlaylist(y,E,S,L)},onError:function(y,E,S,L){r.handleNetworkError(E,S,!1,y,L)},onTimeout:function(y,E,S){r.handleNetworkError(E,S,!0,void 0,y)}};o.load(e,m,g)},n.handleMasterPlaylist=function(e,t,r,s){var o=this.hls,l=e.data,u=Ct(e,r),d=qe.parseMasterPlaylist(l,u);if(d.playlistParsingError){this.handleManifestParsingError(e,r,d.playlistParsingError,s,t);return}var f=d.contentSteering,h=d.levels,c=d.sessionData,v=d.sessionKeys,m=d.startTimeOffset,g=d.variableList;this.variableList=g;var p=qe.parseMasterPlaylistMedia(l,u,d),y=p.AUDIO,E=y===void 0?[]:y,S=p.SUBTITLES,L=p["CLOSED-CAPTIONS"];if(E.length){var D=E.some(function(R){return!R.url});!D&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(A.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),E.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ne({}),bitrate:0,url:""}))}o.trigger(x.MANIFEST_LOADED,{levels:h,audioTracks:E,subtitles:S,captions:L,contentSteering:f,url:u,stats:t,networkDetails:s,sessionData:c,sessionKeys:v,startTimeOffset:m,variableList:g})},n.handleTrackOrLevelPlaylist=function(e,t,r,s,o){var l=this.hls,u=r.id,d=r.level,f=r.type,h=Ct(e,r),c=0,v=O(d)?d:O(u)?u:0,m=Or(r),g=qe.parseLevelPlaylist(e.data,h,v,m,c,this.variableList);if(f===Y.MANIFEST){var p={attrs:new ne({}),bitrate:0,details:g,name:"",url:h};l.trigger(x.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:h,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=g,this.handlePlaylistLoaded(g,e,t,r,s,o)},n.handleManifestParsingError=function(e,t,r,s,o){this.hls.trigger(x.ERROR,{type:V.NETWORK_ERROR,details:_.MANIFEST_PARSING_ERROR,fatal:t.type===Y.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:s,stats:o})},n.handleNetworkError=function(e,t,r,s,o){r===void 0&&(r=!1);var l="A network "+(r?"timeout":"error"+(s?" (status "+s.code+")":""))+" occurred while loading "+e.type;e.type===Y.LEVEL?l+=": "+e.level+" id: "+e.id:(e.type===Y.AUDIO_TRACK||e.type===Y.SUBTITLE_TRACK)&&(l+=" id: "+e.id+' group-id: "'+e.groupId+'"');var u=new Error(l);A.warn("[playlist-loader]: "+l);var d=_.UNKNOWN,f=!1,h=this.getInternalLoader(e);switch(e.type){case Y.MANIFEST:d=r?_.MANIFEST_LOAD_TIMEOUT:_.MANIFEST_LOAD_ERROR,f=!0;break;case Y.LEVEL:d=r?_.LEVEL_LOAD_TIMEOUT:_.LEVEL_LOAD_ERROR,f=!1;break;case Y.AUDIO_TRACK:d=r?_.AUDIO_TRACK_LOAD_TIMEOUT:_.AUDIO_TRACK_LOAD_ERROR,f=!1;break;case Y.SUBTITLE_TRACK:d=r?_.SUBTITLE_TRACK_LOAD_TIMEOUT:_.SUBTITLE_LOAD_ERROR,f=!1;break}h&&this.resetInternalLoader(e.type);var c={type:V.NETWORK_ERROR,details:d,fatal:f,url:e.url,loader:h,context:e,error:u,networkDetails:t,stats:o};if(s){var v=t?.url||e.url;c.response=ge({url:v,data:void 0},s)}this.hls.trigger(x.ERROR,c)},n.handlePlaylistLoaded=function(e,t,r,s,o,l){var u=this.hls,d=s.type,f=s.level,h=s.id,c=s.groupId,v=s.deliveryDirectives,m=Ct(t,s),g=Or(s),p=typeof s.level=="number"&&g===j.MAIN?f:void 0;if(!e.fragments.length){var y=new Error("No Segments found in Playlist");u.trigger(x.ERROR,{type:V.NETWORK_ERROR,details:_.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:y,reason:y.message,response:t,context:s,level:p,parent:g,networkDetails:o,stats:r});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));var E=e.playlistParsingError;if(E){u.trigger(x.ERROR,{type:V.NETWORK_ERROR,details:_.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:E,reason:E.message,response:t,context:s,level:p,parent:g,networkDetails:o,stats:r});return}switch(e.live&&l&&(l.getCacheAge&&(e.ageHeader=l.getCacheAge()||0),(!l.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),d){case Y.MANIFEST:case Y.LEVEL:u.trigger(x.LEVEL_LOADED,{details:e,level:p||0,id:h||0,stats:r,networkDetails:o,deliveryDirectives:v});break;case Y.AUDIO_TRACK:u.trigger(x.AUDIO_TRACK_LOADED,{details:e,id:h||0,groupId:c||"",stats:r,networkDetails:o,deliveryDirectives:v});break;case Y.SUBTITLE_TRACK:u.trigger(x.SUBTITLE_TRACK_LOADED,{details:e,id:h||0,groupId:c||"",stats:r,networkDetails:o,deliveryDirectives:v});break}},a}();function Gn(a,n){var i;try{i=new Event("addtrack")}catch{i=document.createEvent("Event"),i.initEvent("addtrack",!1,!1)}i.track=a,n.dispatchEvent(i)}function Hn(a){var n=a.mode;if(n==="disabled"&&(a.mode="hidden"),a.cues)for(var i=a.cues.length;i--;)a.removeCue(a.cues[i]);n==="disabled"&&(a.mode=n)}function Vn(a,n,i,e){var t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0)for(var r=Wn(a.cues,n,i),s=0;s<r.length;s++)(!e||e(r[s]))&&a.removeCue(r[s]);t==="disabled"&&(a.mode=t)}function Kn(a,n){if(n<a[0].startTime)return 0;var i=a.length-1;if(n>a[i].endTime)return-1;for(var e=0,t=i;e<=t;){var r=Math.floor((t+e)/2);if(n<a[r].startTime)t=r-1;else if(n>a[r].startTime&&e<i)e=r+1;else return r}return a[e].startTime-n<n-a[t].startTime?e:t}function Wn(a,n,i){var e=[],t=Kn(a,n);if(t>-1)for(var r=t,s=a.length;r<s;r++){var o=a[r];if(o.startTime>=n&&o.endTime<=i)e.push(o);else if(o.startTime>i)return e}return e}var Te={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"},Yn=.25;function Pt(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function Mr(a,n,i,e,t){var r=new a(n,i,"");try{r.value=e,t&&(r.type=t)}catch{r=new a(n,i,JSON.stringify(t?ge({type:t},e):e))}return r}var nt=function(){var a=Pt();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY}();function wt(a,n){return a.getTime()/1e3-n}function qn(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var jn=function(){function a(i){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=i,this._registerListeners()}var n=a.prototype;return n.destroy=function(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null},n._registerListeners=function(){var e=this.hls;e.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this)},n._unregisterListeners=function(){var e=this.hls;e.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this)},n.onMediaAttached=function(e,t){this.media=t.media},n.onMediaDetaching=function(){this.id3Track&&(Hn(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})},n.onManifestLoading=function(){this.dateRangeCuesAppended={}},n.createTrack=function(e){var t=this.getID3Track(e.textTracks);return t.mode="hidden",t},n.getID3Track=function(e){if(this.media){for(var t=0;t<e.length;t++){var r=e[t];if(r.kind==="metadata"&&r.label==="id3")return Gn(r,this.media),r}return this.media.addTextTrack("metadata","id3")}},n.onFragParsingMetadata=function(e,t){if(this.media){var r=this.hls.config,s=r.enableEmsgMetadataCues,o=r.enableID3MetadataCues;if(!(!s&&!o)){var l=t.samples;this.id3Track||(this.id3Track=this.createTrack(this.media));var u=Pt();if(u)for(var d=0;d<l.length;d++){var f=l[d].type;if(!(f===Te.emsg&&!s||!o)){var h=cr(l[d].data);if(h){var c=l[d].pts,v=c+l[d].duration;v>nt&&(v=nt);var m=v-c;m<=0&&(v=c+Yn);for(var g=0;g<h.length;g++){var p=h[g];if(!hr(p)){this.updateId3CueEnds(c,f);var y=Mr(u,c,v,p,f);y&&this.id3Track.addCue(y)}}}}}}}},n.updateId3CueEnds=function(e,t){var r,s=(r=this.id3Track)==null?void 0:r.cues;if(s)for(var o=s.length;o--;){var l=s[o];l.type===t&&l.startTime<e&&l.endTime===nt&&(l.endTime=e)}},n.onBufferFlushing=function(e,t){var r=t.startOffset,s=t.endOffset,o=t.type,l=this.id3Track,u=this.hls;if(u){var d=u.config,f=d.enableEmsgMetadataCues,h=d.enableID3MetadataCues;if(l&&(f||h)){var c;o==="audio"?c=function(m){return m.type===Te.audioId3&&h}:o==="video"?c=function(m){return m.type===Te.emsg&&f}:c=function(m){return m.type===Te.audioId3&&h||m.type===Te.emsg&&f},Vn(l,r,s,c)}}},n.onLevelUpdated=function(e,t){var r=this,s=t.details;if(!(!this.media||!s.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)){var o=this.dateRangeCuesAppended,l=this.id3Track,u=s.dateRanges,d=Object.keys(u);if(l)for(var f=Object.keys(o).filter(function(E){return!d.includes(E)}),h=function(){var S=f[c];Object.keys(o[S].cues).forEach(function(L){l.removeCue(o[S].cues[L])}),delete o[S]},c=f.length;c--;)h();var v=s.fragments[s.fragments.length-1];if(!(d.length===0||!O(v?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var m=v.programDateTime/1e3-v.start,g=Pt(),p=function(){var S=d[y],L=u[S],D=wt(L.startDate,m),R=o[S],T=R?.cues||{},b=R?.durationKnown||!1,I=nt,P=L.endDate;if(P)I=wt(P,m),b=!0;else if(L.endOnNext&&!b){var C=d.reduce(function(K,B){if(B!==L.id){var Q=u[B];if(Q.class===L.class&&Q.startDate>L.startDate&&(!K||L.startDate<K.startDate))return Q}return K},null);C&&(I=wt(C.startDate,m),b=!0)}for(var w=Object.keys(L.attr),M=0;M<w.length;M++){var F=w[M];if(Zi(F)){var H=T[F];if(H)b&&!R.durationKnown&&(H.endTime=I);else if(g){var U=L.attr[F];Ji(F)&&(U=qn(U));var W=Mr(g,D,I,{key:F,data:U},Te.dateRange);W&&(W.id=S,r.id3Track.addCue(W),T[F]=W)}}}o[S]={cues:T,dateRange:L,durationKnown:b}},y=0;y<d.length;y++)p()}}},a}(),Xn=function(){function a(i){var e=this;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=function(){return e.timeupdate()},this.hls=i,this.config=i.config,this.registerListeners()}var n=a.prototype;return n.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null},n.registerListeners=function(){this.hls.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(x.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(x.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(x.ERROR,this.onError,this)},n.unregisterListeners=function(){this.hls.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(x.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(x.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(x.ERROR,this.onError,this)},n.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)},n.onMediaDetaching=function(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)},n.onManifestLoading=function(){this.levelDetails=null,this._latency=null,this.stallCount=0},n.onLevelUpdated=function(e,t){var r=t.details;this.levelDetails=r,r.advanced&&this.timeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)},n.onError=function(e,t){var r;t.details===_.BUFFER_STALLED_ERROR&&(this.stallCount++,(r=this.levelDetails)!=null&&r.live&&A.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))},n.timeupdate=function(){var e=this.media,t=this.levelDetails;if(!(!e||!t)){this.currentTime=e.currentTime;var r=this.computeLatency();if(r!==null){this._latency=r;var s=this.config,o=s.lowLatencyMode,l=s.maxLiveSyncPlaybackRate;if(!(!o||l===1||!t.live)){var u=this.targetLatency;if(u!==null){var d=r-u,f=Math.min(this.maxLatency,u+t.targetduration),h=d<f;if(h&&d>.05&&this.forwardBufferLength>1){var c=Math.min(2,Math.max(1,l)),v=Math.round(2/(1+Math.exp(-.75*d-this.edgeStalled))*20)/20;e.playbackRate=Math.min(c,Math.max(1,v))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}}}}},n.estimateLiveEdge=function(){var e=this.levelDetails;return e===null?null:e.edge+e.age},n.computeLatency=function(){var e=this.estimateLiveEdge();return e===null?null:e-this.currentTime},he(a,[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e=this.config,t=this.levelDetails;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(e===null)return null;var t=e.holdBack,r=e.partHoldBack,s=e.targetduration,o=this.config,l=o.liveSyncDuration,u=o.liveSyncDurationCount,d=o.lowLatencyMode,f=this.hls.userConfig,h=d&&r||t;(f.liveSyncDuration||f.liveSyncDurationCount||h===0)&&(h=l!==void 0?l:u*s);var c=s,v=1;return h+Math.min(this.stallCount*v,c)}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency,r=this.levelDetails;if(e===null||t===null||r===null)return null;var s=r.edge,o=e-t-this.edgeStalled,l=s-r.totalduration,u=s-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(l,o),u)}},{key:"drift",get:function(){var e=this.levelDetails;return e===null?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(e===null)return 0;var t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}}]),a}(),kt=["NONE","TYPE-0","TYPE-1",null];function zn(a){return kt.indexOf(a)>-1}var at=["SDR","PQ","HLG"];function $n(a){return!!a&&at.indexOf(a)>-1}var st={No:"",Yes:"YES",v2:"v2"};function Nr(a){var n=a.canSkipUntil,i=a.canSkipDateRanges,e=a.age,t=e<n/2;return n&&t?i?st.v2:st.Yes:st.No}var Br=function(){function a(i,e,t){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=i,this.part=e,this.skip=t}var n=a.prototype;return n.addDirectives=function(e){var t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href},a}(),Ft=function(){function a(i){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=[i.url],this._attrs=[i.attrs],this.bitrate=i.bitrate,i.details&&(this.details=i.details),this.id=i.id||0,this.name=i.name,this.width=i.width||0,this.height=i.height||0,this.frameRate=i.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=i.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=i.audioCodec,this.videoCodec=i.videoCodec,this.codecSet=[i.videoCodec,i.audioCodec].filter(function(e){return!!e}).map(function(e){return e.substring(0,4)}).join(","),this.addGroupId("audio",i.attrs.AUDIO),this.addGroupId("text",i.attrs.SUBTITLES)}var n=a.prototype;return n.hasAudioGroup=function(e){return Ur(this._audioGroups,e)},n.hasSubtitleGroup=function(e){return Ur(this._subtitleGroups,e)},n.addGroupId=function(e,t){if(t){if(e==="audio"){var r=this._audioGroups;r||(r=this._audioGroups=[]),r.indexOf(t)===-1&&r.push(t)}else if(e==="text"){var s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}},n.addFallback=function(){},he(a,[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"averageBitrate",get:function(){return this._avgBitrate||this.realBitrate||this.bitrate}},{key:"attrs",get:function(){return this._attrs[0]}},{key:"codecs",get:function(){return this.attrs.CODECS||""}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"videoRange",get:function(){return this.attrs["VIDEO-RANGE"]||"SDR"}},{key:"score",get:function(){return this.attrs.optionalFloat("SCORE",0)}},{key:"uri",get:function(){return this.url[0]||""}},{key:"audioGroups",get:function(){return this._audioGroups}},{key:"subtitleGroups",get:function(){return this._subtitleGroups}},{key:"urlId",get:function(){return 0},set:function(e){}},{key:"audioGroupIds",get:function(){return this.audioGroups?[this.audioGroupId]:void 0}},{key:"textGroupIds",get:function(){return this.subtitleGroups?[this.textGroupId]:void 0}},{key:"audioGroupId",get:function(){var e;return(e=this.audioGroups)==null?void 0:e[0]}},{key:"textGroupId",get:function(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}}]),a}();function Ur(a,n){return!n||!a?!1:a.indexOf(n)!==-1}function Ot(a,n){var i=n.startPTS;if(O(i)){var e=0,t;n.sn>a.sn?(e=i-a.start,t=a):(e=a.start-i,t=n),t.duration!==e&&(t.duration=e)}else if(n.sn>a.sn){var r=a.cc===n.cc;r&&a.minEndPTS?n.start=a.start+(a.minEndPTS-a.start):n.start=a.start+a.duration}else n.start=Math.max(a.start-n.duration,0)}function Gr(a,n,i,e,t,r){var s=e-i;s<=0&&(A.warn("Fragment should have a positive duration",n),e=i+n.duration,r=t+n.duration);var o=i,l=e,u=n.startPTS,d=n.endPTS;if(O(u)){var f=Math.abs(u-i);O(n.deltaPTS)?n.deltaPTS=Math.max(f,n.deltaPTS):n.deltaPTS=f,o=Math.max(i,u),i=Math.min(i,u),t=Math.min(t,n.startDTS),l=Math.min(e,d),e=Math.max(e,d),r=Math.max(r,n.endDTS)}var h=i-n.start;n.start!==0&&(n.start=i),n.duration=e-n.start,n.startPTS=i,n.maxStartPTS=o,n.startDTS=t,n.endPTS=e,n.minEndPTS=l,n.endDTS=r;var c=n.sn;if(!a||c<a.startSN||c>a.endSN)return 0;var v,m=c-a.startSN,g=a.fragments;for(g[m]=n,v=m;v>0;v--)Ot(g[v],g[v-1]);for(v=m;v<g.length-1;v++)Ot(g[v],g[v+1]);return a.fragmentHint&&Ot(g[g.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,h}function Qn(a,n){for(var i=null,e=a.fragments,t=e.length-1;t>=0;t--){var r=e[t].initSegment;if(r){i=r;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;var s=0,o;if(ea(a,n,function(v,m){v.relurl&&(s=v.cc-m.cc),O(v.startPTS)&&O(v.endPTS)&&(m.start=m.startPTS=v.startPTS,m.startDTS=v.startDTS,m.maxStartPTS=v.maxStartPTS,m.endPTS=v.endPTS,m.endDTS=v.endDTS,m.minEndPTS=v.minEndPTS,m.duration=v.endPTS-v.startPTS,m.duration&&(o=m),n.PTSKnown=n.alignedSliding=!0),m.elementaryStreams=v.elementaryStreams,m.loader=v.loader,m.stats=v.stats,v.initSegment&&(m.initSegment=v.initSegment,i=v.initSegment)}),i){var l=n.fragmentHint?n.fragments.concat(n.fragmentHint):n.fragments;l.forEach(function(v){var m;v&&(!v.initSegment||v.initSegment.relurl===((m=i)==null?void 0:m.relurl))&&(v.initSegment=i)})}if(n.skippedSegments)if(n.deltaUpdateFailed=n.fragments.some(function(v){return!v}),n.deltaUpdateFailed){A.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(var u=n.skippedSegments;u--;)n.fragments.shift();n.startSN=n.fragments[0].sn,n.startCC=n.fragments[0].cc}else n.canSkipDateRanges&&(n.dateRanges=Zn(a.dateRanges,n.dateRanges,n.recentlyRemovedDateranges));var d=n.fragments;if(s){A.warn("discontinuity sliding from playlist, take drift into account");for(var f=0;f<d.length;f++)d[f].cc+=s}n.skippedSegments&&(n.startCC=n.fragments[0].cc),Jn(a.partList,n.partList,function(v,m){m.elementaryStreams=v.elementaryStreams,m.stats=v.stats}),o?Gr(n,o,o.startPTS,o.endPTS,o.startDTS,o.endDTS):Hr(a,n),d.length&&(n.totalduration=n.edge-d[0].start),n.driftStartTime=a.driftStartTime,n.driftStart=a.driftStart;var h=n.advancedDateTime;if(n.advanced&&h){var c=n.edge;n.driftStart||(n.driftStartTime=h,n.driftStart=c),n.driftEndTime=h,n.driftEnd=c}else n.driftEndTime=a.driftEndTime,n.driftEnd=a.driftEnd,n.advancedDateTime=a.advancedDateTime}function Zn(a,n,i){var e=ye({},a);return i&&i.forEach(function(t){delete e[t]}),Object.keys(n).forEach(function(t){var r=new lr(n[t].attr,e[t]);r.isValid?e[t]=r:A.warn('Ignoring invalid Playlist Delta Update DATERANGE tag: "'+JSON.stringify(n[t].attr)+'"')}),e}function Jn(a,n,i){if(a&&n)for(var e=0,t=0,r=a.length;t<=r;t++){var s=a[t],o=n[t+e];s&&o&&s.index===o.index&&s.fragment.sn===o.fragment.sn?i(s,o):e--}}function ea(a,n,i){for(var e=n.skippedSegments,t=Math.max(a.startSN,n.startSN)-n.startSN,r=(a.fragmentHint?1:0)+(e?n.endSN:Math.min(a.endSN,n.endSN))-n.startSN,s=n.startSN-a.startSN,o=n.fragmentHint?n.fragments.concat(n.fragmentHint):n.fragments,l=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments,u=t;u<=r;u++){var d=l[s+u],f=o[u];e&&!f&&u<e&&(f=n.fragments[u]=d),d&&f&&i(d,f)}}function Hr(a,n){var i=n.startSN+n.skippedSegments-a.startSN,e=a.fragments;i<0||i>=e.length||ta(n,e[i].start)}function ta(a,n){if(n){for(var i=a.fragments,e=a.skippedSegments;e<i.length;e++)i[e].start+=n;a.fragmentHint&&(a.fragmentHint.start+=n)}}function ra(a,n){n===void 0&&(n=1/0);var i=1e3*a.targetduration;if(a.updated){var e=a.fragments,t=4;if(e.length&&i*t>n){var r=e[e.length-1].duration*1e3;r<i&&(i=r)}}else i/=2;return Math.round(i)}function ia(a,n,i){if(!(a!=null&&a.details))return null;var e=a.details,t=e.fragments[n-e.startSN];return t||(t=e.fragmentHint,t&&t.sn===n)?t:n<e.startSN&&i&&i.sn===n?i:null}function Vr(a,n,i){var e;return a!=null&&a.details?Kr((e=a.details)==null?void 0:e.partList,n,i):null}function Kr(a,n,i){if(a)for(var e=a.length;e--;){var t=a[e];if(t.index===i&&t.fragment.sn===n)return t}return null}function Wr(a){a.forEach(function(n,i){var e=n.details;e!=null&&e.fragments&&e.fragments.forEach(function(t){t.level=i})})}function ot(a){switch(a.details){case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_TIMEOUT:case _.LEVEL_LOAD_TIMEOUT:case _.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Yr(a,n){var i=ot(n);return a.default[(i?"timeout":"error")+"Retry"]}function Mt(a,n){var i=a.backoff==="linear"?1:Math.pow(2,n);return Math.min(i*a.retryDelayMs,a.maxRetryDelayMs)}function qr(a){return ge(ge({},a),{errorRetry:null,timeoutRetry:null})}function lt(a,n,i,e){if(!a)return!1;var t=e?.code,r=n<a.maxNumRetry&&(na(t)||!!i);return a.shouldRetry?a.shouldRetry(a,n,i,e,r):r}function na(a){return a===0&&navigator.onLine===!1||!!a&&(a<400||a>499)}var jr={search:function(n,i){for(var e=0,t=n.length-1,r=null,s=null;e<=t;){r=(e+t)/2|0,s=n[r];var o=i(s);if(o>0)e=r+1;else if(o<0)t=r-1;else return s}return null}};function aa(a,n,i){if(n===null||!Array.isArray(a)||!a.length||!O(n))return null;var e=a[0].programDateTime;if(n<(e||0))return null;var t=a[a.length-1].endProgramDateTime;if(n>=(t||0))return null;i=i||0;for(var r=0;r<a.length;++r){var s=a[r];if(sa(n,i,s))return s}return null}function Xr(a,n,i,e){i===void 0&&(i=0),e===void 0&&(e=0);var t=null;if(a){t=n[a.sn-n[0].sn+1]||null;var r=a.endDTS-i;r>0&&r<15e-7&&(i+=15e-7)}else i===0&&n[0].start===0&&(t=n[0]);if(t&&(!a||a.level===t.level)&&zr(i,e,t)===0)return t;var s=jr.search(n,zr.bind(null,i,e));return s&&(s!==a||!t)?s:t}function zr(a,n,i){if(a===void 0&&(a=0),n===void 0&&(n=0),i.start<=a&&i.start+i.duration>a)return 0;var e=Math.min(n,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-e<=a?1:i.start-e>a&&i.start?-1:0}function sa(a,n,i){var e=Math.min(n,i.duration+(i.deltaPTS?i.deltaPTS:0))*1e3,t=i.endProgramDateTime||0;return t-e>a}function oa(a,n){return jr.search(a,function(i){return i.cc<n?1:i.cc>n?-1:0})}var ue={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Se={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4},la=function(){function a(i){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=i,this.log=A.log.bind(A,"[info]:"),this.warn=A.warn.bind(A,"[warning]:"),this.error=A.error.bind(A,"[error]:"),this.registerListeners()}var n=a.prototype;return n.registerListeners=function(){var e=this.hls;e.on(x.ERROR,this.onError,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this)},n.unregisterListeners=function(){var e=this.hls;e&&(e.off(x.ERROR,this.onError,this),e.off(x.ERROR,this.onErrorOut,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this))},n.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},n.startLoad=function(e){},n.stopLoad=function(){this.playlistError=0},n.getVariantLevelIndex=function(e){return e?.type===j.MAIN?e.level:this.hls.loadLevel},n.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},n.onLevelUpdated=function(){this.playlistError=0},n.onError=function(e,t){var r,s;if(!t.fatal){var o=this.hls,l=t.context;switch(t.details){case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case _.FRAG_PARSING_ERROR:if((r=t.frag)!=null&&r.gap){t.errorAction={action:ue.DoNothing,flags:Se.None};return}case _.FRAG_GAP:case _.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ue.SendAlternateToPenaltyBox;return}case _.LEVEL_EMPTY_ERROR:case _.LEVEL_PARSING_ERROR:{var u,d,f=t.parent===j.MAIN?t.level:o.loadLevel;t.details===_.LEVEL_EMPTY_ERROR&&((u=t.context)!=null&&(d=u.levelDetails)!=null&&d.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,f):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,f))}return;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:typeof l?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,l.level));return;case _.AUDIO_TRACK_LOAD_ERROR:case _.AUDIO_TRACK_LOAD_TIMEOUT:case _.SUBTITLE_LOAD_ERROR:case _.SUBTITLE_TRACK_LOAD_TIMEOUT:if(l){var h=o.levels[o.loadLevel];if(h&&(l.type===Y.AUDIO_TRACK&&h.hasAudioGroup(l.groupId)||l.type===Y.SUBTITLE_TRACK&&h.hasSubtitleGroup(l.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o.loadLevel),t.errorAction.action=ue.SendAlternateToPenaltyBox,t.errorAction.flags=Se.MoveAllAlternatesMatchingHost;return}}return;case _.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{var c=o.levels[o.loadLevel],v=c?.attrs["HDCP-LEVEL"];v?t.errorAction={action:ue.SendAlternateToPenaltyBox,flags:Se.MoveAllAlternatesMatchingHDCP,hdcpLevel:v}:this.keySystemError(t)}return;case _.BUFFER_ADD_CODEC_ERROR:case _.REMUX_ALLOC_ERROR:case _.BUFFER_APPEND_ERROR:t.errorAction=this.getLevelSwitchAction(t,(s=t.level)!=null?s:o.loadLevel);return;case _.INTERNAL_EXCEPTION:case _.BUFFER_APPENDING_ERROR:case _.BUFFER_FULL_ERROR:case _.LEVEL_SWITCH_ERROR:case _.BUFFER_STALLED_ERROR:case _.BUFFER_SEEK_OVER_HOLE:case _.BUFFER_NUDGE_ON_STALL:t.errorAction={action:ue.DoNothing,flags:Se.None};return}t.type===V.KEY_SYSTEM_ERROR&&this.keySystemError(t)}},n.keySystemError=function(e){var t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)},n.getPlaylistRetryOrSwitchAction=function(e,t){var r=this.hls,s=Yr(r.config.playlistLoadPolicy,e),o=this.playlistError++,l=lt(s,o,ot(e),e.response);if(l)return{action:ue.RetryRequest,flags:Se.None,retryConfig:s,retryCount:o};var u=this.getLevelSwitchAction(e,t);return s&&(u.retryConfig=s,u.retryCount=o),u},n.getFragRetryOrSwitchAction=function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),s=t.levels[r],o=t.config,l=o.fragLoadPolicy,u=o.keyLoadPolicy,d=Yr(e.details.startsWith("key")?u:l,e),f=t.levels.reduce(function(v,m){return v+m.fragmentError},0);if(s){e.details!==_.FRAG_GAP&&s.fragmentError++;var h=lt(d,f,ot(e),e.response);if(h)return{action:ue.RetryRequest,flags:Se.None,retryConfig:d,retryCount:f}}var c=this.getLevelSwitchAction(e,r);return d&&(c.retryConfig=d,c.retryCount=f),c},n.getLevelSwitchAction=function(e,t){var r=this.hls;t==null&&(t=r.loadLevel);var s=this.hls.levels[t];if(s){var o,l,u=e.details;s.loadError++,u===_.BUFFER_APPEND_ERROR&&s.fragmentError++;var d=-1,f=r.levels,h=r.loadLevel,c=r.minAutoLevel,v=r.maxAutoLevel;r.autoLevelEnabled||(r.loadLevel=-1);for(var m=(o=e.frag)==null?void 0:o.type,g=m===j.AUDIO&&u===_.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(u===_.BUFFER_ADD_CODEC_ERROR||u===_.BUFFER_APPEND_ERROR),p=g&&f.some(function(I){var P=I.audioCodec;return s.audioCodec!==P}),y=e.sourceBufferName==="video"&&(u===_.BUFFER_ADD_CODEC_ERROR||u===_.BUFFER_APPEND_ERROR),E=y&&f.some(function(I){var P=I.codecSet,C=I.audioCodec;return s.codecSet!==P&&s.audioCodec===C}),S=(l=e.context)!=null?l:{},L=S.type,D=S.groupId,R=function(){var P=(b+h)%f.length;if(P!==h&&P>=c&&P<=v&&f[P].loadError===0){var C,w,M=f[P];if(u===_.FRAG_GAP&&e.frag){var F=f[P].details;if(F){var H=Xr(e.frag,F.fragments,e.frag.start);if(H!=null&&H.gap)return 0}}else{if(L===Y.AUDIO_TRACK&&M.hasAudioGroup(D)||L===Y.SUBTITLE_TRACK&&M.hasSubtitleGroup(D))return 0;if(m===j.AUDIO&&(C=s.audioGroups)!=null&&C.some(function(U){return M.hasAudioGroup(U)})||m===j.SUBTITLE&&(w=s.subtitleGroups)!=null&&w.some(function(U){return M.hasSubtitleGroup(U)})||p&&s.audioCodec===M.audioCodec||!p&&s.audioCodec!==M.audioCodec||E&&s.codecSet===M.codecSet)return 0}return d=P,1}},T,b=f.length;b--&&(T=R(),!(T!==0&&T===1)););if(d>-1&&r.loadLevel!==d)return e.levelRetry=!0,this.playlistError=0,{action:ue.SendAlternateToPenaltyBox,flags:Se.None,nextAutoLevel:d}}return{action:ue.SendAlternateToPenaltyBox,flags:Se.MoveAllAlternatesMatchingHost}},n.onErrorOut=function(e,t){var r;switch((r=t.errorAction)==null?void 0:r.action){case ue.DoNothing:break;case ue.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==_.FRAG_GAP?t.fatal=!0:/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());break}if(t.fatal){this.hls.stopLoad();return}},n.sendAlternateToPenaltyBox=function(e){var t=this.hls,r=e.errorAction;if(r){var s=r.flags,o=r.hdcpLevel,l=r.nextAutoLevel;switch(s){case Se.None:this.switchLevel(e,l);break;case Se.MoveAllAlternatesMatchingHDCP:o&&(t.maxHdcpLevel=kt[kt.indexOf(o)-1],r.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower');break}r.resolved||this.switchLevel(e,l)}},n.switchLevel=function(e,t){t!==void 0&&e.errorAction&&(this.warn("switching to level "+t+" after "+e.details),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)},a}(),ua=function(){function a(i,e){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=A.log.bind(A,e+":"),this.warn=A.warn.bind(A,e+":"),this.hls=i}var n=a.prototype;return n.destroy=function(){this.clearTimer(),this.hls=this.log=this.warn=null},n.clearTimer=function(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)},n.startLoad=function(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()},n.stopLoad=function(){this.canLoad=!1,this.clearTimer()},n.switchParams=function(e,t,r){var s=t?.renditionReports;if(s){for(var o=-1,l=0;l<s.length;l++){var u=s[l],d=void 0;try{d=new self.URL(u.URI,t.url).href}catch(g){A.warn("Could not construct new URL for Rendition Report: "+g),d=u.URI||""}if(d===e){o=l;break}else d===e.substring(0,d.length)&&(o=l)}if(o!==-1){var f=s[o],h=parseInt(f["LAST-MSN"])||t?.lastPartSn,c=parseInt(f["LAST-PART"])||t?.lastPartIndex;if(this.hls.config.lowLatencyMode){var v=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&v>t.partTarget&&(c+=1)}var m=r&&Nr(r);return new Br(h,c>=0?c:void 0,m)}}},n.loadPlaylist=function(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())},n.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},n.shouldReloadPlaylist=function(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)},n.playlistLoaded=function(e,t,r){var s=this,o=t.details,l=t.stats,u=self.performance.now(),d=l.loading.first?Math.max(0,u-l.loading.first):0;if(o.advancedDateTime=Date.now()-d,o.live||r!=null&&r.live){if(o.reloaded(r),r&&this.log("live playlist "+e+" "+(o.advanced?"REFRESHED "+o.lastPartSn+"-"+o.lastPartIndex:o.updated?"UPDATED":"MISSED")),r&&o.fragments.length>0&&Qn(r,o),!this.canLoad||!o.live)return;var f,h=void 0,c=void 0;if(o.canBlockReload&&o.endSN&&o.advanced){var v=this.hls.config.lowLatencyMode,m=o.lastPartSn,g=o.endSN,p=o.lastPartIndex,y=p!==-1,E=m===g,S=v?0:p;y?(h=E?g+1:m,c=E?S:p+1):h=g+1;var L=o.age,D=L+o.ageHeader,R=Math.min(D-o.partTarget,o.targetduration*1.5);if(R>0){if(r&&R>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+R+" with playlist age: "+o.age),R=0;else{var T=Math.floor(R/o.targetduration);if(h+=T,c!==void 0){var b=Math.round(R%o.targetduration/o.partTarget);c+=b}this.log("CDN Tune-in age: "+o.ageHeader+"s last advanced "+L.toFixed(2)+"s goal: "+R+" skip sn "+T+" to part "+c)}o.tuneInGoal=R}if(f=this.getDeliveryDirectives(o,t.deliveryDirectives,h,c),v||!E){this.loadPlaylist(f);return}}else(o.canBlockReload||o.canSkipUntil)&&(f=this.getDeliveryDirectives(o,t.deliveryDirectives,h,c));var I=this.hls.mainForwardBufferInfo,P=I?I.end-I.len:0,C=(o.edge-P)*1e3,w=ra(o,C);o.updated&&u>this.requestScheduled+w&&(this.requestScheduled=l.loading.start),h!==void 0&&o.canBlockReload?this.requestScheduled=l.loading.first+w-(o.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+w<u?this.requestScheduled=u:this.requestScheduled-u<=0&&(this.requestScheduled+=w);var M=this.requestScheduled-u;M=Math.max(0,M),this.log("reload live playlist "+e+" in "+Math.round(M)+" ms"),this.timer=self.setTimeout(function(){return s.loadPlaylist(f)},M)}else this.clearTimer()},n.getDeliveryDirectives=function(e,t,r,s){var o=Nr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,s=t.part,o=st.No),new Br(r,s,o)},n.checkRetry=function(e){var t=this,r=e.details,s=ot(e),o=e.errorAction,l=o||{},u=l.action,d=l.retryCount,f=d===void 0?0:d,h=l.retryConfig,c=!!o&&!!h&&(u===ue.RetryRequest||!o.resolved&&u===ue.SendAlternateToPenaltyBox);if(c){var v;if(this.requestScheduled=-1,f>=h.maxNumRetry)return!1;if(s&&(v=e.context)!=null&&v.deliveryDirectives)this.warn("Retrying playlist loading "+(f+1)+"/"+h.maxNumRetry+' after "'+r+'" without delivery-directives'),this.loadPlaylist();else{var m=Mt(h,f);this.timer=self.setTimeout(function(){return t.loadPlaylist()},m),this.warn("Retrying playlist loading "+(f+1)+"/"+h.maxNumRetry+' after "'+r+'" in '+m+"ms")}e.levelRetry=!0,o.resolved=!0}return c},a}(),Ge=function(){function a(i,e,t){e===void 0&&(e=0),t===void 0&&(t=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=i,this.alpha_=i?Math.exp(Math.log(.5)/i):0,this.estimate_=e,this.totalWeight_=t}var n=a.prototype;return n.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e},n.getTotalWeight=function(){return this.totalWeight_},n.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},a}(),fa=function(){function a(i,e,t,r){r===void 0&&(r=100),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=t,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ge(i),this.fast_=new Ge(e),this.defaultTTFB_=r,this.ttfb_=new Ge(i)}var n=a.prototype;return n.update=function(e,t){var r=this.slow_,s=this.fast_,o=this.ttfb_;r.halfLife!==e&&(this.slow_=new Ge(e,r.getEstimate(),r.getTotalWeight())),s.halfLife!==t&&(this.fast_=new Ge(t,s.getEstimate(),s.getTotalWeight())),o.halfLife!==e&&(this.ttfb_=new Ge(e,o.getEstimate(),o.getTotalWeight()))},n.sample=function(e,t){e=Math.max(e,this.minDelayMs_);var r=8*t,s=e/1e3,o=r/s;this.fast_.sample(s,o),this.slow_.sample(s,o)},n.sampleTTFB=function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))},n.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},n.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},n.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},n.destroy=function(){},a}();function da(){if(typeof matchMedia=="function"){var a=matchMedia("(dynamic-range: high)"),n=matchMedia("bad query");if(a.media!==n.media)return a.matches===!0}return!1}function ha(a,n){var i=!1,e=[];return a&&(i=a!=="SDR",e=[a]),n&&(e=n.allowedVideoRanges||at.slice(0),i=n.preferHDR!==void 0?n.preferHDR:da(),i?e=e.filter(function(t){return t!=="SDR"}):e=["SDR"]),{preferHDR:i,allowedVideoRanges:e}}function ca(a,n,i,e,t){for(var r=Object.keys(a),s=e?.channels,o=e?.audioCodec,l=s&&parseInt(s)===2,u=!0,d=!1,f=1/0,h=1/0,c=1/0,v=0,m=[],g=ha(n,t),p=g.preferHDR,y=g.allowedVideoRanges,E=function(){var b=a[r[S]];u=b.channels[2]>0,f=Math.min(f,b.minHeight),h=Math.min(h,b.minFramerate),c=Math.min(c,b.minBitrate);var I=y.filter(function(P){return b.videoRanges[P]>0});I.length>0&&(d=!0,m=I)},S=r.length;S--;)E();f=O(f)?f:0,h=O(h)?h:0;var L=Math.max(1080,f),D=Math.max(30,h);c=O(c)?c:i,i=Math.max(c,i),d||(n=void 0,m=[]);var R=r.reduce(function(T,b){var I=a[b];if(b===T)return T;if(I.minBitrate>i)return _e(b,"min bitrate of "+I.minBitrate+" > current estimate of "+i),T;if(!I.hasDefaultAudio)return _e(b,"no renditions with default or auto-select sound found"),T;if(o&&b.indexOf(o.substring(0,4))%5!==0)return _e(b,'audio codec preference "'+o+'" not found'),T;if(s&&!l){if(!I.channels[s])return _e(b,"no renditions with "+s+" channel sound found (channels options: "+Object.keys(I.channels)+")"),T}else if((!o||l)&&u&&I.channels[2]===0)return _e(b,"no renditions with stereo sound found"),T;return I.minHeight>L?(_e(b,"min resolution of "+I.minHeight+" > maximum of "+L),T):I.minFramerate>D?(_e(b,"min framerate of "+I.minFramerate+" > maximum of "+D),T):m.some(function(P){return I.videoRanges[P]>0})?I.maxScore<v?(_e(b,"max score of "+I.maxScore+" < selected max of "+v),T):T&&(rt(b)>=rt(T)||I.fragmentError>a[T].fragmentError)?T:(v=I.maxScore,b):(_e(b,"no variants with VIDEO-RANGE of "+JSON.stringify(m)+" found"),T)},void 0);return{codecSet:R,videoRanges:m,preferHDR:p,minFramerate:h,minBitrate:c}}function _e(a,n){A.log('[abr] start candidates with "'+a+'" ignored because '+n)}function va(a){return a.reduce(function(n,i){var e=n.groups[i.groupId];e||(e=n.groups[i.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),e.tracks.push(i);var t=i.channels||"2";return e.channels[t]=(e.channels[t]||0)+1,e.hasDefault=e.hasDefault||i.default,e.hasAutoSelect=e.hasAutoSelect||i.autoselect,e.hasDefault&&(n.hasDefaultAudio=!0),e.hasAutoSelect&&(n.hasAutoSelectAudio=!0),n},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function ga(a,n,i,e){return a.slice(i,e+1).reduce(function(t,r){if(!r.codecSet)return t;var s=r.audioGroups,o=t[r.codecSet];o||(t[r.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!s,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,r.bitrate);var 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,t},{})}var ma=function(){function a(i){var e=this;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=function(){var t=e.fragCurrent,r=e.partCurrent,s=e.hls,o=s.autoLevelEnabled,l=s.media;if(!(!t||!l)){var u=performance.now(),d=r?r.stats:t.stats,f=r?r.duration:t.duration,h=u-d.loading.start,c=s.minAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||t.level<=c){e.clearTimer(),e._nextAutoLevel=-1;return}if(!(!o||l.paused||!l.playbackRate||!l.readyState)){var v=s.mainForwardBufferInfo;if(v!==null){var m=e.bwEstimator.getEstimateTTFB(),g=Math.abs(l.playbackRate);if(!(h<=Math.max(m,1e3*(f/(g*2))))){var p=v.len/g,y=d.loading.first?d.loading.first-d.loading.start:-1,E=d.loaded&&y>-1,S=e.getBwEstimate(),L=s.levels,D=L[t.level],R=d.total||Math.max(d.loaded,Math.round(f*D.averageBitrate/8)),T=E?h-y:h;T<1&&E&&(T=Math.min(h,d.loaded*8/S));var b=E?d.loaded*1e3/T:0,I=b?(R-d.loaded)/b:R*8/S+m/1e3;if(!(I<=p)){var P=b?b*8:S,C=Number.POSITIVE_INFINITY,w;for(w=t.level-1;w>c;w--){var M=L[w].maxBitrate;if(C=e.getTimeToLoadFrag(m/1e3,P,f*M,!L[w].details),C<p)break}if(!(C>=I)&&!(C>f*10)){s.nextLoadLevel=s.nextAutoLevel=w,E?e.bwEstimator.sample(h-Math.min(m,y),d.loaded):e.bwEstimator.sampleTTFB(h);var F=L[w].maxBitrate;e.getBwEstimate()*e.hls.config.abrBandWidthUpFactor>F&&e.resetEstimator(F),e.clearTimer(),A.warn("[abr] Fragment "+t.sn+(r?" part "+r.index:"")+" of level "+t.level+` is loading too slowly;
2
+ Time to underbuffer: `+p.toFixed(3)+` s
3
+ Estimated load time for current fragment: `+I.toFixed(3)+` s
4
+ Estimated load time for down switch fragment: `+C.toFixed(3)+` s
5
+ TTFB estimate: `+(y|0)+` ms
6
+ Current BW estimate: `+(O(S)?S|0:"Unknown")+` bps
7
+ New BW estimate: `+(e.getBwEstimate()|0)+` bps
8
+ Switching to level `+w+" @ "+(F|0)+" bps"),s.trigger(x.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:r,stats:d})}}}}}}},this.hls=i,this.bwEstimator=this.initEstimator(),this.registerListeners()}var n=a.prototype;return n.resetEstimator=function(e){e&&(A.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()},n.initEstimator=function(){var e=this.hls.config;return new fa(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},n.registerListeners=function(){var e=this.hls;e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.FRAG_LOADING,this.onFragLoading,this),e.on(x.FRAG_LOADED,this.onFragLoaded,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this),e.on(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(x.LEVEL_LOADED,this.onLevelLoaded,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(x.ERROR,this.onError,this)},n.unregisterListeners=function(){var e=this.hls;e&&(e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.FRAG_LOADING,this.onFragLoading,this),e.off(x.FRAG_LOADED,this.onFragLoaded,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this),e.off(x.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(x.LEVEL_LOADED,this.onLevelLoaded,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(x.ERROR,this.onError,this))},n.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null},n.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},n.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},n.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},n.onFragLoading=function(e,t){var r=t.frag;if(!this.ignoreFragment(r)){if(!r.bitrateTest){var s;this.fragCurrent=r,this.partCurrent=(s=t.part)!=null?s:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}},n.onLevelSwitching=function(e,t){this.clearTimer()},n.onError=function(e,t){if(!t.fatal)switch(t.details){case _.BUFFER_ADD_CODEC_ERROR:case _.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case _.FRAG_LOAD_TIMEOUT:{var r=t.frag,s=this.fragCurrent,o=this.partCurrent;if(r&&s&&r.sn===s.sn&&r.level===s.level){var l=performance.now(),u=o?o.stats:r.stats,d=l-u.loading.start,f=u.loading.first?u.loading.first-u.loading.start:-1,h=u.loaded&&f>-1;if(h){var c=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(d-Math.min(c,f),u.loaded)}else this.bwEstimator.sampleTTFB(d)}break}}},n.getTimeToLoadFrag=function(e,t,r,s){var o=e+r/t,l=s?this.lastLevelLoadSec:0;return o+l},n.onLevelLoaded=function(e,t){var r=this.hls.config,s=t.stats.loading,o=s.end-s.start;O(o)&&(this.lastLevelLoadSec=o/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD)},n.onFragLoaded=function(e,t){var r=t.frag,s=t.part,o=s?s.stats:r.stats;if(r.type===j.MAIN&&this.bwEstimator.sampleTTFB(o.loading.first-o.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){var l=s?s.duration:r.duration,u=this.hls.levels[r.level],d=(u.loaded?u.loaded.bytes:0)+o.loaded,f=(u.loaded?u.loaded.duration:0)+l;u.loaded={bytes:d,duration:f},u.realBitrate=Math.round(8*d/f)}if(r.bitrateTest){var h={stats:o,frag:r,part:s,id:r.type};this.onFragBuffered(x.FRAG_BUFFERED,h),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}},n.onFragBuffered=function(e,t){var r=t.frag,s=t.part,o=s!=null&&s.stats.loaded?s.stats:r.stats;if(!o.aborted&&!this.ignoreFragment(r)){var l=o.parsing.end-o.loading.start-Math.min(o.loading.first-o.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(l,o.loaded),o.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=l/1e3:this.bitrateTestDelay=0}},n.ignoreFragment=function(e){return e.type!==j.MAIN||e.sn==="initSegment"},n.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},n.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},n.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls,s=r.maxAutoLevel,o=r.config,l=r.minAutoLevel,u=t?t.duration:e?e.duration:0,d=this.getBwEstimate(),f=this.getStarvationDelay(),h=o.abrBandWidthFactor,c=o.abrBandWidthUpFactor;if(f){var v=this.findBestLevel(d,l,s,f,0,h,c);if(v>=0)return v}var m=u?Math.min(u,o.maxStarvationDelay):o.maxStarvationDelay;if(!f){var g=this.bitrateTestDelay;if(g){var p=u?Math.min(u,o.maxLoadingDelay):o.maxLoadingDelay;m=p-g,A.info("[abr] bitrate test took "+Math.round(1e3*g)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*m)+" ms"),h=c=1}}var y=this.findBestLevel(d,l,s,f,m,h,c);if(A.info("[abr] "+(f?"rebuffering expected":"buffer is empty")+", optimal quality level "+y),y>-1)return y;var E=r.levels[l],S=r.levels[r.loadLevel];return E?.bitrate<S?.bitrate?l:r.loadLevel},n.getStarvationDelay=function(){var e=this.hls,t=e.media;if(!t)return 1/0;var r=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,s=e.mainForwardBufferInfo;return(s?s.len:0)/r},n.getBwEstimate=function(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate},n.findBestLevel=function(e,t,r,s,o,l,u){var d,f=this,h=s+o,c=this.lastLoadedFragLevel,v=c===-1?this.hls.firstLevel:c,m=this.fragCurrent,g=this.partCurrent,p=this.hls,y=p.levels,E=p.allAudioTracks,S=p.loadLevel,L=p.config;if(y.length===1)return 0;var D=y[v],R=!!(D!=null&&(d=D.details)!=null&&d.live),T=S===-1||c===-1,b,I="SDR",P=D?.frameRate||0,C=L.audioPreference,w=L.videoPreference,M=this.audioTracksByGroup||(this.audioTracksByGroup=va(E));if(T){if(this.firstSelection!==-1)return this.firstSelection;var F=this.codecTiers||(this.codecTiers=ga(y,M,t,r)),H=ca(F,I,e,C,w),U=H.codecSet,W=H.videoRanges,K=H.minFramerate,B=H.minBitrate,Q=H.preferHDR;b=U,I=Q?W[W.length-1]:W[0],P=K,e=Math.max(e,B),A.log("[abr] picked start tier "+JSON.stringify(H))}else b=D?.codecSet,I=D?.videoRange;for(var q=g?g.duration:m?m.duration:0,J=this.bwEstimator.getEstimateTTFB()/1e3,ee=[],re=function(){var Ee,te=y[X],ce=X>v;if(!te)return 0;if(b&&te.codecSet!==b||I&&te.videoRange!==I||ce&&P>te.frameRate||!ce&&P>0&&P<te.frameRate||te.supportedResult&&!((Ee=te.supportedResult.decodingInfoResults)!=null&&Ee[0].smooth))return ee.push(X),0;var ve=te.details,ie=(g?ve?.partTarget:ve?.averagetargetduration)||q,z;ce?z=u*e:z=l*e;var pe=q&&s>=q*2&&o===0?y[X].averageBitrate:y[X].maxBitrate,de=f.getTimeToLoadFrag(J,z,pe*ie,ve===void 0),le=z>=pe&&(X===c||te.loadError===0&&te.fragmentError===0)&&(de<=J||!O(de)||R&&!f.bitrateTestDelay||de<h);if(le){var Ue=f.forcedAutoLevel;return X!==S&&(Ue===-1||Ue!==S)&&(ee.length&&A.trace("[abr] Skipped level(s) "+ee.join(",")+" of "+r+' max with CODECS and VIDEO-RANGE:"'+y[ee[0]].codecs+'" '+y[ee[0]].videoRange+'; not compatible with "'+D.codecs+'" '+I),A.info("[abr] switch candidate:"+v+"->"+X+" adjustedbw("+Math.round(z)+")-bitrate="+Math.round(z-pe)+" ttfb:"+J.toFixed(1)+" avgDuration:"+ie.toFixed(1)+" maxFetchDuration:"+h.toFixed(1)+" fetchDuration:"+de.toFixed(1)+" firstSelection:"+T+" codecSet:"+b+" videoRange:"+I+" hls.loadLevel:"+S)),T&&(f.firstSelection=X),{v:X}}},Z,X=r;X>=t;X--)if(Z=re(),Z!==0&&Z)return Z.v;return-1},he(a,[{key:"firstAutoLevel",get:function(){var e=this.hls,t=e.maxAutoLevel,r=e.minAutoLevel,s=this.getBwEstimate(),o=this.hls.config.maxStarvationDelay,l=this.findBestLevel(s,r,t,0,o,1,1);if(l>-1)return l;var u=this.hls.firstLevel,d=Math.min(Math.max(u,r),t);return A.warn("[abr] Could not find best starting auto level. Defaulting to first in playlist "+u+" clamped to "+d),d}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){var e=this.forcedAutoLevel,t=this.bwEstimator,r=t.canEstimate(),s=this.lastLoadedFragLevel>-1;if(e!==-1&&(!r||!s||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;var o=r&&s?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){var l=this.hls.levels;if(l.length>Math.max(e,o)&&l[e].loadError<=l[o].loadError)return e}return this._nextAutoLevel=o,this.nextAutoLevelKey=this.getAutoLevelKey(),o},set:function(e){var t=this.hls,r=t.maxAutoLevel,s=t.minAutoLevel,o=Math.min(Math.max(e,s),r);this._nextAutoLevel!==o&&(this.nextAutoLevelKey="",this._nextAutoLevel=o)}}]),a}(),pa={length:0,start:function(){return 0},end:function(){return 0}},ae=function(){function a(){}return a.isBuffered=function(i,e){try{if(i){for(var t=a.getBuffered(i),r=0;r<t.length;r++)if(e>=t.start(r)&&e<=t.end(r))return!0}}catch{}return!1},a.bufferInfo=function(i,e,t){try{if(i){var r=a.getBuffered(i),s=[],o;for(o=0;o<r.length;o++)s.push({start:r.start(o),end:r.end(o)});return this.bufferedInfo(s,e,t)}}catch{}return{len:0,start:e,end:e,nextStart:void 0}},a.bufferedInfo=function(i,e,t){e=Math.max(0,e),i.sort(function(g,p){var y=g.start-p.start;return y||p.end-g.end});var r=[];if(t)for(var s=0;s<i.length;s++){var o=r.length;if(o){var l=r[o-1].end;i[s].start-l<t?i[s].end>l&&(r[o-1].end=i[s].end):r.push(i[s])}else r.push(i[s])}else r=i;for(var u=0,d,f=e,h=e,c=0;c<r.length;c++){var v=r[c].start,m=r[c].end;if(e+t>=v&&e<m)f=v,h=m,u=h-e;else if(e+t<v){d=v;break}}return{len:u,start:f||0,end:h||0,nextStart:d}},a.getBuffered=function(i){try{return i.buffered}catch(e){return A.log("failed to get media.buffered",e),pa}},a}(),ya=function(){function a(i){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=i}var n=a.prototype;return n.append=function(e,t,r){var s=this.queues[t];s.push(e),s.length===1&&!r&&this.executeNext(t)},n.insertAbort=function(e,t){var r=this.queues[t];r.unshift(e),this.executeNext(t)},n.appendBlocker=function(e){var t,r=new Promise(function(o){t=o}),s={execute:t,onStart:function(){},onComplete:function(){},onError:function(){}};return this.append(s,e),r},n.executeNext=function(e){var t=this.queues[e];if(t.length){var r=t[0];try{r.execute()}catch(o){A.warn('[buffer-operation-queue]: Exception executing "'+e+'" SourceBuffer operation: '+o),r.onError(o);var s=this.buffers[e];s!=null&&s.updating||this.shiftAndExecuteNext(e)}}},n.shiftAndExecuteNext=function(e){this.queues[e].shift(),this.executeNext(e)},n.current=function(e){return this.queues[e][0]},a}(),$r=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Ea=function(){function a(i){var e=this;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=function(r){e.hls&&e.hls.pauseBuffering()},this._onStartStreaming=function(r){e.hls&&e.hls.resumeBuffering()},this._onMediaSourceOpen=function(){var r=e.media,s=e.mediaSource;e.log("Media source opened"),r&&(r.removeEventListener("emptied",e._onMediaEmptied),e.updateMediaElementDuration(),e.hls.trigger(x.MEDIA_ATTACHED,{media:r,mediaSource:s})),s&&s.removeEventListener("sourceopen",e._onMediaSourceOpen),e.checkPendingTracks()},this._onMediaSourceClose=function(){e.log("Media source closed")},this._onMediaSourceEnded=function(){e.log("Media source ended")},this._onMediaEmptied=function(){var r=e.mediaSrc,s=e._objectUrl;r!==s&&A.error("Media element src was set while attaching MediaSource ("+s+" > "+r+")")},this.hls=i;var t="[buffer-controller]";this.appendSource=Cn(Ne(i.config.preferManagedMediaSource)),this.log=A.log.bind(A,t),this.warn=A.warn.bind(A,t),this.error=A.error.bind(A,t),this._initSourceBuffer(),this.registerListeners()}var n=a.prototype;return n.hasSourceTypes=function(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0},n.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null},n.registerListeners=function(){var e=this.hls;e.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.BUFFER_RESET,this.onBufferReset,this),e.on(x.BUFFER_APPENDING,this.onBufferAppending,this),e.on(x.BUFFER_CODECS,this.onBufferCodecs,this),e.on(x.BUFFER_EOS,this.onBufferEos,this),e.on(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(x.FRAG_PARSED,this.onFragParsed,this),e.on(x.FRAG_CHANGED,this.onFragChanged,this)},n.unregisterListeners=function(){var e=this.hls;e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.BUFFER_RESET,this.onBufferReset,this),e.off(x.BUFFER_APPENDING,this.onBufferAppending,this),e.off(x.BUFFER_CODECS,this.onBufferCodecs,this),e.off(x.BUFFER_EOS,this.onBufferEos,this),e.off(x.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(x.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(x.FRAG_PARSED,this.onFragParsed,this),e.off(x.FRAG_CHANGED,this.onFragChanged,this)},n._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new ya(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null},n.onManifestLoading=function(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null},n.onManifestParsed=function(e,t){var r=2;t.audio&&!t.video||t.altAudio,r=1,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},n.onMediaAttaching=function(e,t){var r=this.media=t.media,s=Ne(this.appendSource);if(r&&s){var o,l=this.mediaSource=new s;this.log("created media source: "+((o=l.constructor)==null?void 0:o.name)),l.addEventListener("sourceopen",this._onMediaSourceOpen),l.addEventListener("sourceended",this._onMediaSourceEnded),l.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(l.addEventListener("startstreaming",this._onStartStreaming),l.addEventListener("endstreaming",this._onEndStreaming));var u=this._objectUrl=self.URL.createObjectURL(l);if(this.appendSource)try{r.removeAttribute("src");var d=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||d&&l instanceof d,Qr(r),xa(r,u),r.load()}catch{r.src=u}else r.src=u;r.addEventListener("emptied",this._onMediaEmptied)}},n.onMediaDetaching=function(){var e=this.media,t=this.mediaSource,r=this._objectUrl;if(t){if(this.log("media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(s){this.warn("onMediaDetaching: "+s.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),r&&self.URL.revokeObjectURL(r),this.mediaSrc===r?(e.removeAttribute("src"),this.appendSource&&Qr(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(x.MEDIA_DETACHED,void 0)},n.onBufferReset=function(){var e=this;this.getSourceBufferTypes().forEach(function(t){e.resetBuffer(t)}),this._initSourceBuffer()},n.resetBuffer=function(e){var t=this.sourceBuffer[e];try{if(t){var r;this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,(r=this.mediaSource)!=null&&r.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}}catch(s){this.warn("onBufferReset "+e,s)}},n.onBufferCodecs=function(e,t){var r=this,s=this.getSourceBufferTypes().length,o=Object.keys(t);if(o.forEach(function(u){if(s){var d=r.tracks[u];if(d&&typeof d.buffer.changeType=="function"){var f,h=t[u],c=h.id,v=h.codec,m=h.levelCodec,g=h.container,p=h.metadata,y=Rr(d.codec,d.levelCodec),E=y?.replace($r,"$1"),S=Rr(v,m),L=(f=S)==null?void 0:f.replace($r,"$1");if(S&&E!==L){u.slice(0,5)==="audio"&&(S=it(S,r.appendSource));var D=g+";codecs="+S;r.appendChangeType(u,D),r.log("switching codec "+y+" to "+S),r.tracks[u]={buffer:d.buffer,codec:v,container:g,levelCodec:m,metadata:p,id:c}}}}else r.pendingTracks[u]=t[u]}),!s){var l=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==l&&(this.log(l+" bufferCodec event(s) expected "+o.join(",")),this.bufferCodecEventsExpected=l),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}},n.appendChangeType=function(e,t){var r=this,s=this.operationQueue,o={execute:function(){var u=r.sourceBuffer[e];u&&(r.log("changing "+e+" sourceBuffer type to "+t),u.changeType(t)),s.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(u){r.warn("Failed to change "+e+" SourceBuffer type",u)}};s.append(o,e,!!this.pendingTracks[e])},n.onBufferAppending=function(e,t){var r=this,s=this.hls,o=this.operationQueue,l=this.tracks,u=t.data,d=t.type,f=t.frag,h=t.part,c=t.chunkMeta,v=c.buffering[d],m=self.performance.now();v.start=m;var g=f.stats.buffering,p=h?h.stats.buffering:null;g.start===0&&(g.start=m),p&&p.start===0&&(p.start=m);var y=l.audio,E=!1;d==="audio"&&y?.container==="audio/mpeg"&&(E=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);var S=f.start,L={execute:function(){if(v.executeStart=self.performance.now(),E){var R=r.sourceBuffer[d];if(R){var T=S-R.timestampOffset;Math.abs(T)>=.1&&(r.log("Updating audio SourceBuffer timestampOffset to "+S+" (delta: "+T+") sn: "+f.sn+")"),R.timestampOffset=S)}}r.appendExecutor(u,d)},onStart:function(){},onComplete:function(){var R=self.performance.now();v.executeEnd=v.end=R,g.first===0&&(g.first=R),p&&p.first===0&&(p.first=R);var T=r.sourceBuffer,b={};for(var I in T)b[I]=ae.getBuffered(T[I]);r.appendErrors[d]=0,d==="audio"||d==="video"?r.appendErrors.audiovideo=0:(r.appendErrors.audio=0,r.appendErrors.video=0),r.hls.trigger(x.BUFFER_APPENDED,{type:d,frag:f,part:h,chunkMeta:c,parent:f.type,timeRanges:b})},onError:function(R){var T={type:V.MEDIA_ERROR,parent:f.type,details:_.BUFFER_APPEND_ERROR,sourceBufferName:d,frag:f,part:h,chunkMeta:c,error:R,err:R,fatal:!1};if(R.code===DOMException.QUOTA_EXCEEDED_ERR)T.details=_.BUFFER_FULL_ERROR;else{var b=++r.appendErrors[d];T.details=_.BUFFER_APPEND_ERROR,r.warn("Failed "+b+"/"+s.config.appendErrorMaxRetry+' times to append segment in "'+d+'" sourceBuffer'),b>=s.config.appendErrorMaxRetry&&(T.fatal=!0)}s.trigger(x.ERROR,T)}};o.append(L,d,!!this.pendingTracks[d])},n.onBufferFlushing=function(e,t){var r=this,s=this.operationQueue,o=function(u){return{execute:r.removeExecutor.bind(r,u,t.startOffset,t.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(x.BUFFER_FLUSHED,{type:u})},onError:function(f){r.warn("Failed to remove from "+u+" SourceBuffer",f)}}};t.type?s.append(o(t.type),t.type):this.getSourceBufferTypes().forEach(function(l){s.append(o(l),l)})},n.onFragParsed=function(e,t){var r=this,s=t.frag,o=t.part,l=[],u=o?o.elementaryStreams:s.elementaryStreams;u[$.AUDIOVIDEO]?l.push("audiovideo"):(u[$.AUDIO]&&l.push("audio"),u[$.VIDEO]&&l.push("video"));var d=function(){var h=self.performance.now();s.stats.buffering.end=h,o&&(o.stats.buffering.end=h);var c=o?o.stats:s.stats;r.hls.trigger(x.FRAG_BUFFERED,{frag:s,part:o,stats:c,id:s.type})};l.length===0&&this.warn("Fragments must have at least one ElementaryStreamType set. type: "+s.type+" level: "+s.level+" sn: "+s.sn),this.blockBuffers(d,l)},n.onFragChanged=function(e,t){this.trimBuffers()},n.onBufferEos=function(e,t){var r=this,s=this.getSourceBufferTypes().reduce(function(o,l){var u=r.sourceBuffer[l];return u&&(!t.type||t.type===l)&&(u.ending=!0,u.ended||(u.ended=!0,r.log(l+" sourceBuffer now EOS"))),o&&!!(!u||u.ended)},!0);s&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(function(){r.getSourceBufferTypes().forEach(function(l){var u=r.sourceBuffer[l];u&&(u.ending=!1)});var o=r.mediaSource;if(!o||o.readyState!=="open"){o&&r.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+o.readyState);return}r.log("Calling mediaSource.endOfStream()"),o.endOfStream()}))},n.onLevelUpdated=function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},n.trimBuffers=function(){var e=this.hls,t=this.details,r=this.media;if(!(!r||t===null)){var s=this.getSourceBufferTypes();if(s.length){var o=e.config,l=r.currentTime,u=t.levelTargetDuration,d=t.live&&o.liveBackBufferLength!==null?o.liveBackBufferLength:o.backBufferLength;if(O(d)&&d>0){var f=Math.max(d,u),h=Math.floor(l/u)*u-f;this.flushBackBuffer(l,u,h)}if(O(o.frontBufferFlushThreshold)&&o.frontBufferFlushThreshold>0){var c=Math.max(o.maxBufferLength,o.frontBufferFlushThreshold),v=Math.max(c,u),m=Math.floor(l/u)*u+v;this.flushFrontBuffer(l,u,m)}}}},n.flushBackBuffer=function(e,t,r){var s=this,o=this.details,l=this.sourceBuffer,u=this.getSourceBufferTypes();u.forEach(function(d){var f=l[d];if(f){var h=ae.getBuffered(f);if(h.length>0&&r>h.start(0)){if(s.hls.trigger(x.BACK_BUFFER_REACHED,{bufferEnd:r}),o!=null&&o.live)s.hls.trigger(x.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(f.ended&&h.end(h.length-1)-e<t*2){s.log("Cannot flush "+d+" back buffer while SourceBuffer is in ended state");return}s.hls.trigger(x.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:d})}}})},n.flushFrontBuffer=function(e,t,r){var s=this,o=this.sourceBuffer,l=this.getSourceBufferTypes();l.forEach(function(u){var d=o[u];if(d){var f=ae.getBuffered(d),h=f.length;if(h<2)return;var c=f.start(h-1),v=f.end(h-1);if(r>c||e>=c&&e<=v)return;if(d.ended&&e-v<2*t){s.log("Cannot flush "+u+" front buffer while SourceBuffer is in ended state");return}s.hls.trigger(x.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:u})}})},n.updateMediaElementDuration=function(){if(!(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")){var e=this.details,t=this.hls,r=this.media,s=this.mediaSource,o=e.fragments[0].start+e.totalduration,l=r.duration,u=O(s.duration)?s.duration:0;e.live&&t.config.liveDurationInfinity?(s.duration=1/0,this.updateSeekableRange(e)):(o>u&&o>l||!O(l))&&(this.log("Updating Media Source duration to "+o.toFixed(3)),s.duration=o)}},n.updateSeekableRange=function(e){var t=this.mediaSource,r=e.fragments,s=r.length;if(s&&e.live&&t!=null&&t.setLiveSeekableRange){var o=Math.max(0,r[0].start),l=Math.max(o,o+e.totalduration);this.log("Media Source duration is set to "+t.duration+". Setting seekable range to "+o+"-"+l+"."),t.setLiveSeekableRange(o,l)}},n.checkPendingTracks=function(){var e=this.bufferCodecEventsExpected,t=this.operationQueue,r=this.pendingTracks,s=Object.keys(r).length;if(s&&(!e||s===2||"audiovideo"in r)){this.createSourceBuffers(r),this.pendingTracks={};var o=this.getSourceBufferTypes();if(o.length)this.hls.trigger(x.BUFFER_CREATED,{tracks:this.tracks}),o.forEach(function(u){t.executeNext(u)});else{var l=new Error("could not create source buffer for media codec(s)");this.hls.trigger(x.ERROR,{type:V.MEDIA_ERROR,details:_.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:l,reason:l.message})}}},n.createSourceBuffers=function(e){var t=this,r=this.sourceBuffer,s=this.mediaSource;if(!s)throw Error("createSourceBuffers called when mediaSource was null");var o=function(d){if(!r[d]){var f,h=e[d];if(!h)throw Error("source buffer exists for track "+d+", however track does not");var c=((f=h.levelCodec)==null?void 0:f.indexOf(","))===-1?h.levelCodec:h.codec;c&&d.slice(0,5)==="audio"&&(c=it(c,t.appendSource));var v=h.container+";codecs="+c;t.log("creating sourceBuffer("+v+")");try{var m=r[d]=s.addSourceBuffer(v),g=d;t.addBufferListener(g,"updatestart",t._onSBUpdateStart),t.addBufferListener(g,"updateend",t._onSBUpdateEnd),t.addBufferListener(g,"error",t._onSBUpdateError),t.appendSource&&t.addBufferListener(g,"bufferedchange",function(p,y){var E=y.removedRanges;E!=null&&E.length&&t.hls.trigger(x.BUFFER_FLUSHED,{type:d})}),t.tracks[d]={buffer:m,codec:c,container:h.container,levelCodec:h.levelCodec,metadata:h.metadata,id:h.id}}catch(p){t.error("error while trying to add sourceBuffer: "+p.message),t.hls.trigger(x.ERROR,{type:V.MEDIA_ERROR,details:_.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:p,sourceBufferName:d,mimeType:v})}}};for(var l in e)o(l)},n._onSBUpdateStart=function(e){var t=this.operationQueue,r=t.current(e);r.onStart()},n._onSBUpdateEnd=function(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}var r=this.operationQueue,s=r.current(e);s.onComplete(),r.shiftAndExecuteNext(e)},n._onSBUpdateError=function(e,t){var r,s=new Error(e+" SourceBuffer error. MediaSource readyState: "+((r=this.mediaSource)==null?void 0:r.readyState));this.error(""+s,t),this.hls.trigger(x.ERROR,{type:V.MEDIA_ERROR,details:_.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:s,fatal:!1});var o=this.operationQueue.current(e);o&&o.onError(s)},n.removeExecutor=function(e,t,r){var s=this.media,o=this.mediaSource,l=this.operationQueue,u=this.sourceBuffer,d=u[e];if(!s||!o||!d){this.warn("Attempting to remove from the "+e+" SourceBuffer, but it does not exist"),l.shiftAndExecuteNext(e);return}var f=O(s.duration)?s.duration:1/0,h=O(o.duration)?o.duration:1/0,c=Math.max(0,t),v=Math.min(r,f,h);v>c&&(!d.ending||d.ended)?(d.ended=!1,this.log("Removing ["+c+","+v+"] from the "+e+" SourceBuffer"),d.remove(c,v)):l.shiftAndExecuteNext(e)},n.appendExecutor=function(e,t){var r=this.sourceBuffer[t];if(!r){if(!this.pendingTracks[t])throw new Error("Attempting to append to the "+t+" SourceBuffer, but it does not exist");return}r.ended=!1,r.appendBuffer(e)},n.blockBuffers=function(e,t){var r=this;if(t===void 0&&(t=this.getSourceBufferTypes()),!t.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}var s=this.operationQueue,o=t.map(function(l){return s.appendBlocker(l)});Promise.all(o).then(function(){e(),t.forEach(function(l){var u=r.sourceBuffer[l];u!=null&&u.updating||s.shiftAndExecuteNext(l)})})},n.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},n.addBufferListener=function(e,t,r){var s=this.sourceBuffer[e];if(s){var o=r.bind(this,e);this.listeners[e].push({event:t,listener:o}),s.addEventListener(t,o)}},n.removeBufferListeners=function(e){var t=this.sourceBuffer[e];t&&this.listeners[e].forEach(function(r){t.removeEventListener(r.event,r.listener)})},he(a,[{key:"mediaSrc",get:function(){var e,t=((e=this.media)==null?void 0:e.firstChild)||this.media;return t?.src}}]),a}();function Qr(a){var n=a.querySelectorAll("source");[].slice.call(n).forEach(function(i){a.removeChild(i)})}function xa(a,n){var i=self.document.createElement("source");i.type="video/mp4",i.src=n,a.appendChild(i)}var Ta=function(){function a(i){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=i,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}var n=a.prototype;return n.setStreamController=function(e){this.streamController=e},n.destroy=function(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null},n.registerListeners=function(){var e=this.hls;e.on(x.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(x.BUFFER_CODECS,this.onBufferCodecs,this),e.on(x.MEDIA_DETACHING,this.onMediaDetaching,this)},n.unregisterListener=function(){var e=this.hls;e.off(x.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(x.BUFFER_CODECS,this.onBufferCodecs,this),e.off(x.MEDIA_DETACHING,this.onMediaDetaching,this)},n.onFpsDropLevelCapping=function(e,t){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})},n.onMediaAttaching=function(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()},n.onManifestParsed=function(e,t){var r=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,r.config.capLevelToPlayerSize&&t.video&&this.startCapping()},n.onLevelsUpdated=function(e,t){this.timer&&O(this.autoLevelCapping)&&this.detectPlayerSize()},n.onBufferCodecs=function(e,t){var r=this.hls;r.config.capLevelToPlayerSize&&t.video&&this.startCapping()},n.onMediaDetaching=function(){this.stopCapping()},n.detectPlayerSize=function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}var e=this.hls.levels;if(e.length){var t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&A.log("Setting autoLevelCapping to "+r+": "+e[r].height+"p@"+e[r].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),t.autoLevelCapping=r,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},n.getMaxLevel=function(e){var t=this,r=this.hls.levels;if(!r.length)return-1;var s=r.filter(function(o,l){return t.isLevelAllowed(o)&&l<=e});return this.clientRect=null,a.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)},n.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},n.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},n.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,!t.width&&!t.height&&(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t},n.isLevelAllowed=function(e){var t=this.restrictedLevels;return!t.some(function(r){return e.bitrate===r.bitrate&&e.width===r.width&&e.height===r.height})},a.getMaxLevelByMediaSize=function(e,t,r){if(!(e!=null&&e.length))return-1;for(var s=function(h,c){return c?h.width!==c.width||h.height!==c.height:!0},o=e.length-1,l=Math.max(t,r),u=0;u<e.length;u+=1){var d=e[u];if((d.width>=l||d.height>=l)&&s(d,e[u+1])){o=u;break}}return o},he(a,[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}}]),a}(),Sa=function(){function a(i){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=i,this.registerListeners()}var n=a.prototype;return n.setStreamController=function(e){this.streamController=e},n.registerListeners=function(){this.hls.on(x.MEDIA_ATTACHING,this.onMediaAttaching,this)},n.unregisterListeners=function(){this.hls.off(x.MEDIA_ATTACHING,this.onMediaAttaching,this)},n.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},n.onMediaAttaching=function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var s=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=s,s&&typeof s.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},n.checkFPS=function(e,t,r){var s=performance.now();if(t){if(this.lastTime){var o=s-this.lastTime,l=r-this.lastDroppedFrames,u=t-this.lastDecodedFrames,d=1e3*l/o,f=this.hls;if(f.trigger(x.FPS_DROP,{currentDropped:l,currentDecoded:u,totalDroppedFrames:r}),d>0&&l>f.config.fpsDroppedMonitoringThreshold*u){var h=f.currentLevel;A.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(f.autoLevelCapping===-1||f.autoLevelCapping>=h)&&(h=h-1,f.trigger(x.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:f.currentLevel}),f.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},n.checkFPSInterval=function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},a}(),La=3e5,Aa=function(){function a(i){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=i,this.log=A.log.bind(A,"[content-steering]:"),this.registerListeners()}var n=a.prototype;return n.registerListeners=function(){var e=this.hls;e.on(x.MANIFEST_LOADING,this.onManifestLoading,this),e.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(x.MANIFEST_PARSED,this.onManifestParsed,this),e.on(x.ERROR,this.onError,this)},n.unregisterListeners=function(){var e=this.hls;e&&(e.off(x.MANIFEST_LOADING,this.onManifestLoading,this),e.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(x.MANIFEST_PARSED,this.onManifestParsed,this),e.off(x.ERROR,this.onError,this))},n.startLoad=function(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){var e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}},n.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},n.clearTimeout=function(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},n.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},n.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter(function(r){return r!==e}))},n.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},n.onManifestLoaded=function(e,t){var r=t.contentSteering;r!==null&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())},n.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},n.onError=function(e,t){var r=t.errorAction;if(r?.action===ue.SendAlternateToPenaltyBox&&r.flags===Se.MoveAllAlternatesMatchingHost){var s=this.levels,o=this.pathwayPriority,l=this.pathwayId;if(t.context){var u=t.context,d=u.groupId,f=u.pathwayId,h=u.type;d&&s?l=this.getPathwayForGroupId(d,h,l):f&&(l=f)}l in this.penalizedPathways||(this.penalizedPathways[l]=performance.now()),!o&&s&&(o=s.reduce(function(c,v){return c.indexOf(v.pathwayId)===-1&&c.push(v.pathwayId),c},[])),o&&o.length>1&&(this.updatePathwayPriority(o),r.resolved=this.pathwayId!==l),r.resolved||A.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+l+" levels: "+(s&&s.length)+" priorities: "+JSON.stringify(o)+" penalized: "+JSON.stringify(this.penalizedPathways))}},n.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){var r=e[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+r+'"'),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length?(this.log("Found "+t.length+"/"+e.length+' levels in Pathway "'+this.pathwayId+'"'),t):e},n.getLevelsForPathway=function(e){return this.levels===null?[]:this.levels.filter(function(t){return e===t.pathwayId})},n.updatePathwayPriority=function(e){this.pathwayPriority=e;var t,r=this.penalizedPathways,s=performance.now();Object.keys(r).forEach(function(h){s-r[h]>La&&delete r[h]});for(var o=0;o<e.length;o++){var l=e[o];if(!(l in r)){if(l===this.pathwayId)return;var u=this.hls.nextLoadLevel,d=this.hls.levels[u];if(t=this.getLevelsForPathway(l),t.length>0){this.log('Setting Pathway to "'+l+'"'),this.pathwayId=l,Wr(t),this.hls.trigger(x.LEVELS_UPDATED,{levels:t});var f=this.hls.levels[u];d&&f&&this.levels&&(f.attrs["STABLE-VARIANT-ID"]!==d.attrs["STABLE-VARIANT-ID"]&&f.bitrate!==d.bitrate&&this.log("Unstable Pathways change from bitrate "+d.bitrate+" to "+f.bitrate),this.hls.nextLoadLevel=u);break}}}},n.getPathwayForGroupId=function(e,t,r){for(var s=this.getLevelsForPathway(r).concat(this.levels||[]),o=0;o<s.length;o++)if(t===Y.AUDIO_TRACK&&s[o].hasAudioGroup(e)||t===Y.SUBTITLE_TRACK&&s[o].hasSubtitleGroup(e))return s[o].pathwayId;return r},n.clonePathways=function(e){var t=this,r=this.levels;if(r){var s={},o={};e.forEach(function(l){var u=l.ID,d=l["BASE-ID"],f=l["URI-REPLACEMENT"];if(!r.some(function(c){return c.pathwayId===u})){var h=t.getLevelsForPathway(d).map(function(c){var v=new ne(c.attrs);v["PATHWAY-ID"]=u;var m=v.AUDIO&&v.AUDIO+"_clone_"+u,g=v.SUBTITLES&&v.SUBTITLES+"_clone_"+u;m&&(s[v.AUDIO]=m,v.AUDIO=m),g&&(o[v.SUBTITLES]=g,v.SUBTITLES=g);var p=Jr(c.uri,v["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",f),y=new Ft({attrs:v,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:p,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(var E=1;E<c.audioGroups.length;E++)y.addGroupId("audio",c.audioGroups[E]+"_clone_"+u);if(c.subtitleGroups)for(var S=1;S<c.subtitleGroups.length;S++)y.addGroupId("text",c.subtitleGroups[S]+"_clone_"+u);return y});r.push.apply(r,h),Zr(t.audioTracks,s,f,u),Zr(t.subtitleTracks,o,f,u)}})}},n.loadSteeringManifest=function(e){var t=this,r=this.hls.config,s=r.loader;this.loader&&this.loader.destroy(),this.loader=new s(r);var o;try{o=new self.URL(e)}catch{this.enabled=!1,this.log("Failed to parse Steering Manifest URI: "+e);return}if(o.protocol!=="data:"){var l=(this.hls.bandwidthEstimate||r.abrEwmaDefaultEstimate)|0;o.searchParams.set("_HLS_pathway",this.pathwayId),o.searchParams.set("_HLS_throughput",""+l)}var u={responseType:"json",url:o.href},d=r.steeringManifestLoadPolicy.default,f=d.errorRetry||d.timeoutRetry||{},h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:f.maxNumRetry||0,retryDelay:f.retryDelayMs||0,maxRetryDelay:f.maxRetryDelayMs||0},c={onSuccess:function(m,g,p,y){t.log('Loaded steering manifest: "'+o+'"');var E=m.data;if(E.VERSION!==1){t.log("Steering VERSION "+E.VERSION+" not supported!");return}t.updated=performance.now(),t.timeToLoad=E.TTL;var S=E["RELOAD-URI"],L=E["PATHWAY-CLONES"],D=E["PATHWAY-PRIORITY"];if(S)try{t.uri=new self.URL(S,o).href}catch{t.enabled=!1,t.log("Failed to parse Steering Manifest RELOAD-URI: "+S);return}t.scheduleRefresh(t.uri||p.url),L&&t.clonePathways(L);var R={steeringManifest:E,url:o.toString()};t.hls.trigger(x.STEERING_MANIFEST_LOADED,R),D&&t.updatePathwayPriority(D)},onError:function(m,g,p,y){if(t.log("Error loading steering manifest: "+m.code+" "+m.text+" ("+g.url+")"),t.stopLoad(),m.code===410){t.enabled=!1,t.log("Steering manifest "+g.url+" no longer available");return}var E=t.timeToLoad*1e3;if(m.code===429){var S=t.loader;if(typeof S?.getResponseHeader=="function"){var L=S.getResponseHeader("Retry-After");L&&(E=parseFloat(L)*1e3)}t.log("Steering manifest "+g.url+" rate limited");return}t.scheduleRefresh(t.uri||g.url,E)},onTimeout:function(m,g,p){t.log("Timeout loading steering manifest ("+g.url+")"),t.scheduleRefresh(t.uri||g.url)}};this.log("Requesting steering manifest: "+o),this.loader.load(u,h,c)},n.scheduleRefresh=function(e,t){var r=this;t===void 0&&(t=this.timeToLoad*1e3),this.clearTimeout(),this.reloadTimer=self.setTimeout(function(){var s,o=(s=r.hls)==null?void 0:s.media;if(o&&!o.ended){r.loadSteeringManifest(e);return}r.scheduleRefresh(e,r.timeToLoad*1e3)},t)},a}();function Zr(a,n,i,e){a&&Object.keys(n).forEach(function(t){var r=a.filter(function(s){return s.groupId===t}).map(function(s){var o=ye({},s);return o.details=void 0,o.attrs=new ne(o.attrs),o.url=o.attrs.URI=Jr(s.url,s.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),o.groupId=o.attrs["GROUP-ID"]=n[t],o.attrs["PATHWAY-ID"]=e,o});a.push.apply(a,r)})}function Jr(a,n,i,e){var t=e.HOST,r=e.PARAMS,s=e[i],o;n&&(o=s?.[n],o&&(a=o));var l=new self.URL(a);return t&&!o&&(l.host=t),r&&Object.keys(r).sort().forEach(function(u){u&&l.searchParams.set(u,r[u])}),l.href}var Ra=/^age:\s*[\d.]+\s*$/im,ei=function(){function a(i){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=i&&i.xhrSetup||null,this.stats=new $e,this.retryDelay=0}var n=a.prototype;return n.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null,this.stats=null},n.abortInternal=function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))},n.abort=function(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},n.load=function(e,t,r){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=r,this.loadInternal()},n.loadInternal=function(){var e=this,t=this.config,r=this.context;if(!(!t||!r)){var s=this.loader=new self.XMLHttpRequest,o=this.stats;o.loading.first=0,o.loaded=0,o.aborted=!1;var l=this.xhrSetup;l?Promise.resolve().then(function(){if(!e.stats.aborted)return l(s,r.url)}).catch(function(u){return s.open("GET",r.url,!0),l(s,r.url)}).then(function(){e.stats.aborted||e.openAndSendXhr(s,r,t)}).catch(function(u){e.callbacks.onError({code:s.status,text:u.message},r,s,o)}):this.openAndSendXhr(s,r,t)}},n.openAndSendXhr=function(e,t,r){e.readyState||e.open("GET",t.url,!0);var s=t.headers,o=r.loadPolicy,l=o.maxTimeToFirstByteMs,u=o.maxLoadTimeMs;if(s)for(var d in s)e.setRequestHeader(d,s[d]);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),r.timeout=l&&O(l)?l:u,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()},n.readystatechange=function(){var e=this.context,t=this.loader,r=this.stats;if(!(!e||!t)){var s=t.readyState,o=this.config;if(!r.aborted&&s>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),o.timeout!==o.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),o.timeout=o.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),o.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;var l=t.status,u=t.responseType!=="text";if(l>=200&&l<300&&(u&&t.response||t.responseText!==null)){r.loading.end=Math.max(self.performance.now(),r.loading.first);var d=u?t.response:t.responseText,f=t.responseType==="arraybuffer"?d.byteLength:d.length;if(r.loaded=r.total=f,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first),!this.callbacks)return;var h=this.callbacks.onProgress;if(h&&h(r,e,d,t),!this.callbacks)return;var c={url:t.responseURL,data:d,code:l};this.callbacks.onSuccess(c,r,e,t)}else{var v=o.loadPolicy.errorRetry,m=r.retry,g={url:e.url,data:void 0,code:l};lt(v,m,!1,g)?this.retry(v):(A.error(l+" while loading "+e.url),this.callbacks.onError({code:l,text:t.statusText},e,t,r))}}}},n.loadtimeout=function(){var e,t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,r=this.stats.retry;if(lt(t,r,!0))this.retry(t);else{var s;A.warn("timeout while loading "+((s=this.context)==null?void 0:s.url));var o=this.callbacks;o&&(this.abortInternal(),o.onTimeout(this.stats,this.context,this.loader))}},n.retry=function(e){var t=this.context,r=this.stats;this.retryDelay=Mt(e,r.retry),r.retry++,A.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+t?.url+", retrying "+r.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)},n.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},n.getCacheAge=function(){var e=null;if(this.loader&&Ra.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e},n.getResponseHeader=function(e){return this.loader&&new RegExp("^"+e+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null},a}(),ba=function(){function a(){this.chunks=[],this.dataLength=0}var n=a.prototype;return n.push=function(e){this.chunks.push(e),this.dataLength+=e.length},n.flush=function(){var e=this.chunks,t=this.dataLength,r;if(e.length)e.length===1?r=e[0]:r=Ia(e,t);else return new Uint8Array(0);return this.reset(),r},n.reset=function(){this.chunks.length=0,this.dataLength=0},a}();function Ia(a,n){for(var i=new Uint8Array(n),e=0,t=0;t<a.length;t++){var r=a[t];i.set(r,e),e+=r.length}return i}function _a(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var Da=/(\d+)-(\d+)\/(\d+)/,ti=function(){function a(i){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=i.fetchSetup||ka,this.controller=new self.AbortController,this.stats=new $e}var n=a.prototype;return n.destroy=function(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null},n.abortInternal=function(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},n.abort=function(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},n.load=function(e,t,r){var s=this,o=this.stats;if(o.loading.start)throw new Error("Loader can only be used once.");o.loading.start=self.performance.now();var l=Ca(e,this.controller.signal),u=r.onProgress,d=e.responseType==="arraybuffer",f=d?"byteLength":"length",h=t.loadPolicy,c=h.maxTimeToFirstByteMs,v=h.maxLoadTimeMs;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,l),self.clearTimeout(this.requestTimeout),t.timeout=c&&O(c)?c:v,this.requestTimeout=self.setTimeout(function(){s.abortInternal(),r.onTimeout(o,e,s.response)},t.timeout),self.fetch(this.request).then(function(m){s.response=s.loader=m;var g=Math.max(self.performance.now(),o.loading.start);if(self.clearTimeout(s.requestTimeout),t.timeout=v,s.requestTimeout=self.setTimeout(function(){s.abortInternal(),r.onTimeout(o,e,s.response)},v-(g-o.loading.start)),!m.ok){var p=m.status,y=m.statusText;throw new Fa(y||"fetch, bad network response",p,m)}return o.loading.first=g,o.total=wa(m.headers)||o.total,u&&O(t.highWaterMark)?s.loadProgressively(m,o,e,t.highWaterMark,u):d?m.arrayBuffer():e.responseType==="json"?m.json():m.text()}).then(function(m){var g=s.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(s.requestTimeout),o.loading.end=Math.max(self.performance.now(),o.loading.first);var p=m[f];p&&(o.loaded=o.total=p);var y={url:g.url,data:m,code:g.status};u&&!O(t.highWaterMark)&&u(o,e,m,g),r.onSuccess(y,o,e,g)}).catch(function(m){if(self.clearTimeout(s.requestTimeout),!o.aborted){var g=m&&m.code||0,p=m?m.message:null;r.onError({code:g,text:p},e,m?m.details:null,o)}})},n.getCacheAge=function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e},n.getResponseHeader=function(e){return this.response?this.response.headers.get(e):null},n.loadProgressively=function(e,t,r,s,o){s===void 0&&(s=0);var l=new ba,u=e.body.getReader(),d=function f(){return u.read().then(function(h){if(h.done)return l.dataLength&&o(t,r,l.flush(),e),Promise.resolve(new ArrayBuffer(0));var c=h.value,v=c.length;return t.loaded+=v,v<s||l.dataLength?(l.push(c),l.dataLength>=s&&o(t,r,l.flush(),e)):o(t,r,c,e),f()}).catch(function(){return Promise.reject()})};return d()},a}();function Ca(a,n){var i={method:"GET",mode:"cors",credentials:"same-origin",signal:n,headers:new self.Headers(ye({},a.headers))};return a.rangeEnd&&i.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),i}function Pa(a){var n=Da.exec(a);if(n)return parseInt(n[2])-parseInt(n[1])+1}function wa(a){var n=a.get("Content-Range");if(n){var i=Pa(n);if(O(i))return i}var e=a.get("Content-Length");if(e)return parseInt(e)}function ka(a,n){return new self.Request(a.url,n)}var Fa=function(a){Re(n,a);function n(i,e,t){var r;return r=a.call(this,i)||this,r.code=void 0,r.details=void 0,r.code=e,r.details=t,r}return n}(ze(Error)),Oa={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},ri=ge(ge({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:60*1e3*1e3,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:ei,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:ma,bufferController:Ea,capLevelController:Ta,errorController:la,fpsController:Sa,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:null,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!1,certLoadPolicy:{default:Oa},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},Ma()),{},{subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,audioStreamController:void 0,audioTrackController:void 0,emeController:void 0,cmcdController:void 0,contentSteeringController:Aa});function Ma(){return{cueHandler:an,enableWebVTT:!1,enableIMSC1:!1,enableCEA708Captions:!1,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function Na(a,n){if((n.liveSyncDurationCount||n.liveMaxLatencyDurationCount)&&(n.liveSyncDuration||n.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(n.liveMaxLatencyDurationCount!==void 0&&(n.liveSyncDurationCount===void 0||n.liveMaxLatencyDurationCount<=n.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(n.liveMaxLatencyDuration!==void 0&&(n.liveSyncDuration===void 0||n.liveMaxLatencyDuration<=n.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var i=Nt(a),e=["manifest","level","frag"],t=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return e.forEach(function(r){var s=(r==="level"?"playlist":r)+"LoadPolicy",o=n[s]===void 0,l=[];t.forEach(function(u){var d=r+"Loading"+u,f=n[d];if(f!==void 0&&o){l.push(d);var h=i[s].default;switch(n[s]={default:h},u){case"TimeOut":h.maxLoadTimeMs=f,h.maxTimeToFirstByteMs=f;break;case"MaxRetry":h.errorRetry.maxNumRetry=f,h.timeoutRetry.maxNumRetry=f;break;case"RetryDelay":h.errorRetry.retryDelayMs=f,h.timeoutRetry.retryDelayMs=f;break;case"MaxRetryTimeout":h.errorRetry.maxRetryDelayMs=f,h.timeoutRetry.maxRetryDelayMs=f;break}}}),l.length&&A.warn('hls.js config: "'+l.join('", "')+'" setting(s) are deprecated, use "'+s+'": '+JSON.stringify(n[s]))}),ge(ge({},i),n)}function Nt(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(Nt):Object.keys(a).reduce(function(n,i){return n[i]=Nt(a[i]),n},{}):a}function Ba(a){var n=a.loader;if(n!==ti&&n!==ei)A.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1;else{var i=_a();i&&(a.loader=ti,a.progressive=!0,a.enableSoftwareAES=!0,A.log("[config]: Progressive streaming enabled, using FetchLoader"))}}var Bt,Ua=function(a){Re(n,a);function n(e,t){var r;return r=a.call(this,e,"[level-controller]")||this,r._levels=[],r._firstLevel=-1,r._maxAutoLevel=-1,r._startLevel=void 0,r.currentLevel=null,r.currentLevelIndex=-1,r.manualLevelIndex=-1,r.steering=void 0,r.onParsedComplete=void 0,r.steering=t,r._registerListeners(),r}var i=n.prototype;return i._registerListeners=function(){var t=this.hls;t.on(x.MANIFEST_LOADING,this.onManifestLoading,this),t.on(x.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(x.LEVEL_LOADED,this.onLevelLoaded,this),t.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(x.FRAG_BUFFERED,this.onFragBuffered,this),t.on(x.ERROR,this.onError,this)},i._unregisterListeners=function(){var t=this.hls;t.off(x.MANIFEST_LOADING,this.onManifestLoading,this),t.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(x.LEVEL_LOADED,this.onLevelLoaded,this),t.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(x.FRAG_BUFFERED,this.onFragBuffered,this),t.off(x.ERROR,this.onError,this)},i.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),a.prototype.destroy.call(this)},i.stopLoad=function(){var t=this._levels;t.forEach(function(r){r.loadError=0,r.fragmentError=0}),a.prototype.stopLoad.call(this)},i.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1},i.onManifestLoading=function(t,r){this.resetLevels()},i.onManifestLoaded=function(t,r){var s=this.hls.config.preferManagedMediaSource,o=[],l={},u={},d=!1,f=!1,h=!1;r.levels.forEach(function(c){var v,m,g=c.attrs,p=c.audioCodec,y=c.videoCodec;((v=p)==null?void 0:v.indexOf("mp4a.40.34"))!==-1&&(Bt||(Bt=/chrome|firefox/i.test(navigator.userAgent)),Bt&&(c.audioCodec=p=void 0)),p&&(c.audioCodec=p=it(p,s)),((m=y)==null?void 0:m.indexOf("avc1"))===0&&(y=c.videoCodec=Fn(y));var E=c.width,S=c.height,L=c.unknownCodecs;if(d||(d=!!(E&&S)),f||(f=!!y),h||(h=!!p),!(L!=null&&L.length||p&&!It(p,"audio",s)||y&&!It(y,"video",s))){var D=g.CODECS,R=g["FRAME-RATE"],T=g["HDCP-LEVEL"],b=g["PATHWAY-ID"],I=g.RESOLUTION,P=g["VIDEO-RANGE"],C=(b||".")+"-",w=""+C+c.bitrate+"-"+I+"-"+R+"-"+D+"-"+P+"-"+T;if(l[w])if(l[w].uri!==c.url&&!c.attrs["PATHWAY-ID"]){var F=u[w]+=1;c.attrs["PATHWAY-ID"]=new Array(F+1).join(".");var H=new Ft(c);l[w]=H,o.push(H)}else l[w].addGroupId("audio",g.AUDIO),l[w].addGroupId("text",g.SUBTITLES);else{var M=new Ft(c);l[w]=M,u[w]=1,o.push(M)}}}),this.filterAndSortMediaOptions(o,r,d,f,h)},i.filterAndSortMediaOptions=function(t,r,s,o,l){var u=this,d=[],f=[],h=t;if((s||o)&&l&&(h=h.filter(function(T){var b=T.videoCodec,I=T.videoRange,P=T.width,C=T.height;return(!!b||!!(P&&C))&&$n(I)})),h.length===0){Promise.resolve().then(function(){if(u.hls){r.levels.length&&u.warn("One or more CODECS in variant not supported: "+JSON.stringify(r.levels[0].attrs));var T=new Error("no level with compatible codecs found in manifest");u.hls.trigger(x.ERROR,{type:V.MEDIA_ERROR,details:_.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:r.url,error:T,reason:T.message})}});return}if(r.audioTracks){var c=this.hls.config.preferManagedMediaSource;d=r.audioTracks.filter(function(T){return!T.audioCodec||It(T.audioCodec,"audio",c)}),ii(d)}r.subtitles&&(f=r.subtitles,ii(f));var v=h.slice(0);h.sort(function(T,b){if(T.attrs["HDCP-LEVEL"]!==b.attrs["HDCP-LEVEL"])return(T.attrs["HDCP-LEVEL"]||"")>(b.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&T.height!==b.height)return T.height-b.height;if(T.frameRate!==b.frameRate)return T.frameRate-b.frameRate;if(T.videoRange!==b.videoRange)return at.indexOf(T.videoRange)-at.indexOf(b.videoRange);if(T.videoCodec!==b.videoCodec){var I=Ar(T.videoCodec),P=Ar(b.videoCodec);if(I!==P)return P-I}if(T.uri===b.uri&&T.codecSet!==b.codecSet){var C=rt(T.codecSet),w=rt(b.codecSet);if(C!==w)return w-C}return T.averageBitrate!==b.averageBitrate?T.averageBitrate-b.averageBitrate:0});var m=v[0];if(this.steering&&(h=this.steering.filterParsedLevels(h),h.length!==v.length)){for(var g=0;g<v.length;g++)if(v[g].pathwayId===h[0].pathwayId){m=v[g];break}}this._levels=h;for(var p=0;p<h.length;p++)if(h[p]===m){var y;this._firstLevel=p;var E=m.bitrate,S=this.hls.bandwidthEstimate;if(this.log("manifest loaded, "+h.length+" level(s) found, first bitrate: "+E),((y=this.hls.userConfig)==null?void 0:y.abrEwmaDefaultEstimate)===void 0){var L=Math.min(E,this.hls.config.abrEwmaDefaultEstimateMax);L>S&&S===ri.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=L)}break}var D=l&&!o,R={levels:h,audioTracks:d,subtitleTracks:f,sessionData:r.sessionData,sessionKeys:r.sessionKeys,firstLevel:this._firstLevel,stats:r.stats,audio:l,video:o,altAudio:!D&&d.some(function(T){return!!T.url})};this.hls.trigger(x.MANIFEST_PARSED,R),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)},i.onError=function(t,r){r.fatal||!r.context||r.context.type===Y.LEVEL&&r.context.level===this.level&&this.checkRetry(r)},i.onFragBuffered=function(t,r){var s=r.frag;if(s!==void 0&&s.type===j.MAIN){var o=s.elementaryStreams;if(!Object.keys(o).some(function(u){return!!o[u]}))return;var l=this._levels[s.level];l!=null&&l.loadError&&(this.log("Resetting level error count of "+l.loadError+" on frag buffered"),l.loadError=0)}},i.onLevelLoaded=function(t,r){var s,o=r.level,l=r.details,u=this._levels[o];if(!u){var d;this.warn("Invalid level index "+o),(d=r.deliveryDirectives)!=null&&d.skip&&(l.deltaUpdateFailed=!0);return}o===this.currentLevelIndex?(u.fragmentError===0&&(u.loadError=0),this.playlistLoaded(o,r,u.details)):(s=r.deliveryDirectives)!=null&&s.skip&&(l.deltaUpdateFailed=!0)},i.loadPlaylist=function(t){a.prototype.loadPlaylist.call(this);var r=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){var o=s.uri;if(t)try{o=t.addDirectives(o)}catch(u){this.warn("Could not construct new URL with HLS Delivery Directives: "+u)}var l=s.attrs["PATHWAY-ID"];this.log("Loading level index "+r+(t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:"")+" with"+(l?" Pathway "+l:"")+" "+o),this.clearTimer(),this.hls.trigger(x.LEVEL_LOADING,{url:o,level:r,pathwayId:s.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}},i.removeLevel=function(t){var r=this,s,o=this._levels.filter(function(l,u){return u!==t?!0:(r.steering&&r.steering.removeLevel(l),l===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,l.details&&l.details.fragments.forEach(function(d){return d.level=-1})),!1)});Wr(o),this._levels=o,this.currentLevelIndex>-1&&(s=this.currentLevel)!=null&&s.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(x.LEVELS_UPDATED,{levels:o})},i.onLevelsUpdated=function(t,r){var s=r.levels;this._levels=s},i.checkMaxAutoUpdated=function(){var t=this.hls,r=t.autoLevelCapping,s=t.maxAutoLevel,o=t.maxHdcpLevel;this._maxAutoLevel!==s&&(this._maxAutoLevel=s,this.hls.trigger(x.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:r,levels:this.levels,maxAutoLevel:s,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:o}))},he(n,[{key:"levels",get:function(){return this._levels.length===0?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var r=this._levels;if(r.length!==0){if(t<0||t>=r.length){var s=new Error("invalid level idx"),o=t<0;if(this.hls.trigger(x.ERROR,{type:V.OTHER_ERROR,details:_.LEVEL_SWITCH_ERROR,level:t,fatal:o,error:s,reason:s.message}),o)return;t=Math.min(t,r.length-1)}var l=this.currentLevelIndex,u=this.currentLevel,d=u?u.attrs["PATHWAY-ID"]:void 0,f=r[t],h=f.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=f,!(l===t&&f.details&&u&&d===h)){this.log("Switching to level "+t+" ("+(f.height?f.height+"p ":"")+(f.videoRange?f.videoRange+" ":"")+(f.codecSet?f.codecSet+" ":"")+"@"+f.bitrate+")"+(h?" with Pathway "+h:"")+" from level "+l+(d?" with Pathway "+d:""));var c={level:t,attrs:f.attrs,details:f.details,bitrate:f.bitrate,averageBitrate:f.averageBitrate,maxBitrate:f.maxBitrate,realBitrate:f.realBitrate,width:f.width,height:f.height,codecSet:f.codecSet,audioCodec:f.audioCodec,videoCodec:f.videoCodec,audioGroups:f.audioGroups,subtitleGroups:f.subtitleGroups,loaded:f.loaded,loadError:f.loadError,fragmentError:f.fragmentError,name:f.name,id:f.id,uri:f.uri,url:f.url,urlId:0,audioGroupIds:f.audioGroupIds,textGroupIds:f.textGroupIds};this.hls.trigger(x.LEVEL_SWITCHING,c);var v=f.details;if(!v||v.live){var m=this.switchParams(f.uri,u?.details,v);this.loadPlaylist(m)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(this._startLevel===void 0){var t=this.hls.config.startLevel;return t!==void 0?t:this.hls.firstAutoLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"nextLoadLevel",get:function(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}}]),n}(ua);function ii(a){var n={};a.forEach(function(i){var e=i.groupId||"";i.id=n[e]=n[e]||0,n[e]++})}var me={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},Ga=function(){function a(i){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=i,this._registerListeners()}var n=a.prototype;return n._registerListeners=function(){var e=this.hls;e.on(x.BUFFER_APPENDED,this.onBufferAppended,this),e.on(x.FRAG_BUFFERED,this.onFragBuffered,this),e.on(x.FRAG_LOADED,this.onFragLoaded,this)},n._unregisterListeners=function(){var e=this.hls;e.off(x.BUFFER_APPENDED,this.onBufferAppended,this),e.off(x.FRAG_BUFFERED,this.onFragBuffered,this),e.off(x.FRAG_LOADED,this.onFragLoaded,this)},n.destroy=function(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},n.getAppendedFrag=function(e,t){var r=this.activePartLists[t];if(r)for(var s=r.length;s--;){var o=r[s];if(!o)break;var l=o.end;if(o.start<=e&&l!==null&&e<=l)return o}return this.getBufferedFrag(e,t)},n.getBufferedFrag=function(e,t){for(var r=this.fragments,s=Object.keys(r),o=s.length;o--;){var l=r[s[o]];if(l?.body.type===t&&l.buffered){var u=l.body;if(u.start<=e&&e<=u.end)return u}}return null},n.detectEvictedFragments=function(e,t,r,s){var o=this;this.timeRanges&&(this.timeRanges[e]=t);var l=s?.fragment.sn||-1;Object.keys(this.fragments).forEach(function(u){var d=o.fragments[u];if(d&&!(l>=d.body.sn)){if(!d.buffered&&!d.loaded){d.body.type===r&&o.removeFragment(d.body);return}var f=d.range[e];f&&f.time.some(function(h){var c=!o.isTimeBuffered(h.startPTS,h.endPTS,t);return c&&o.removeFragment(d.body),c})}})},n.detectPartialFragments=function(e){var t=this,r=this.timeRanges,s=e.frag,o=e.part;if(!(!r||s.sn==="initSegment")){var l=He(s),u=this.fragments[l];if(!(!u||u.buffered&&s.gap)){var d=!s.relurl;if(Object.keys(r).forEach(function(h){var c=s.elementaryStreams[h];if(c){var v=r[h],m=d||c.partial===!0;u.range[h]=t.getBufferedTimes(s,o,m,v)}}),u.loaded=null,Object.keys(u.range).length){u.buffered=!0;var f=u.body.endList=s.endList||u.body.endList;f&&(this.endListFragments[u.body.type]=u),ut(u)||this.removeParts(s.sn-1,s.type)}else this.removeFragment(u.body)}}},n.removeParts=function(e,t){var r=this.activePartLists[t];r&&(this.activePartLists[t]=r.filter(function(s){return s.fragment.sn>=e}))},n.fragBuffered=function(e,t){var r=He(e),s=this.fragments[r];!s&&t&&(s=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,s.buffered=!0)},n.getBufferedTimes=function(e,t,r,s){for(var o={time:[],partial:r},l=e.start,u=e.end,d=e.minEndPTS||u,f=e.maxStartPTS||l,h=0;h<s.length;h++){var c=s.start(h)-this.bufferPadding,v=s.end(h)+this.bufferPadding;if(f>=c&&d<=v){o.time.push({startPTS:Math.max(l,s.start(h)),endPTS:Math.min(u,s.end(h))});break}else if(l<v&&u>c){var m=Math.max(l,s.start(h)),g=Math.min(u,s.end(h));g>m&&(o.partial=!0,o.time.push({startPTS:m,endPTS:g}))}else if(u<=c)break}return o},n.getPartialFragment=function(e){var t=null,r,s,o,l=0,u=this.bufferPadding,d=this.fragments;return Object.keys(d).forEach(function(f){var h=d[f];h&&ut(h)&&(s=h.body.start-u,o=h.body.end+u,e>=s&&e<=o&&(r=Math.min(e-s,o-e),l<=r&&(t=h.body,l=r)))}),t},n.isEndListAppended=function(e){var t=this.endListFragments[e];return t!==void 0&&(t.buffered||ut(t))},n.getState=function(e){var t=He(e),r=this.fragments[t];return r?r.buffered?ut(r)?me.PARTIAL:me.OK:me.APPENDING:me.NOT_LOADED},n.isTimeBuffered=function(e,t,r){for(var s,o,l=0;l<r.length;l++){if(s=r.start(l)-this.bufferPadding,o=r.end(l)+this.bufferPadding,e>=s&&t<=o)return!0;if(t<=s)return!1}return!1},n.onFragLoaded=function(e,t){var r=t.frag,s=t.part;if(!(r.sn==="initSegment"||r.bitrateTest)){var o=s?null:t,l=He(r);this.fragments[l]={body:r,appendedPTS:null,loaded:o,buffered:!1,range:Object.create(null)}}},n.onBufferAppended=function(e,t){var r=this,s=t.frag,o=t.part,l=t.timeRanges;if(s.sn!=="initSegment"){var u=s.type;if(o){var d=this.activePartLists[u];d||(this.activePartLists[u]=d=[]),d.push(o)}this.timeRanges=l,Object.keys(l).forEach(function(f){var h=l[f];r.detectEvictedFragments(f,h,u,o)})}},n.onFragBuffered=function(e,t){this.detectPartialFragments(t)},n.hasFragment=function(e){var t=He(e);return!!this.fragments[t]},n.hasParts=function(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)},n.removeFragmentsInRange=function(e,t,r,s,o){var l=this;s&&!this.hasGaps||Object.keys(this.fragments).forEach(function(u){var d=l.fragments[u];if(d){var f=d.body;f.type!==r||s&&!f.gap||f.start<t&&f.end>e&&(d.buffered||o)&&l.removeFragment(f)}})},n.removeFragment=function(e){var t=He(e);e.stats.loaded=0,e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var s=e.sn;this.activePartLists[e.type]=r.filter(function(o){return o.fragment.sn!==s})}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]},n.removeAllFragments=function(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1},a}();function ut(a){var n,i,e;return a.buffered&&(a.body.gap||((n=a.range.video)==null?void 0:n.partial)||((i=a.range.audio)==null?void 0:i.partial)||((e=a.range.audiovideo)==null?void 0:e.partial))}function He(a){return a.type+"_"+a.level+"_"+a.sn}var ni=Math.pow(2,17),Ha=function(){function a(i){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=i}var n=a.prototype;return n.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},n.abort=function(){this.loader&&this.loader.abort()},n.load=function(e,t){var r=this,s=e.url;if(!s)return Promise.reject(new De({type:V.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(s?"part list":"url")),networkDetails:null}));this.abort();var o=this.config,l=o.fLoader,u=o.loader;return new Promise(function(d,f){if(r.loader&&r.loader.destroy(),e.gap)if(e.tagList.some(function(g){return g[0]==="GAP"})){f(si(e));return}else e.gap=!1;var h=r.loader=e.loader=l?new l(o):new u(o),c=ai(e),v=qr(o.fragLoadPolicy.default),m={loadPolicy:v,timeout:v.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:ni};e.stats=h.stats,h.load(c,m,{onSuccess:function(p,y,E,S){r.resetLoader(e,h);var L=p.data;E.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(L.slice(0,16)),L=L.slice(16)),d({frag:e,part:null,payload:L,networkDetails:S})},onError:function(p,y,E,S){r.resetLoader(e,h),f(new De({type:V.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ge({url:s,data:void 0},p),error:new Error("HTTP Error "+p.code+" "+p.text),networkDetails:E,stats:S}))},onAbort:function(p,y,E){r.resetLoader(e,h),f(new De({type:V.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:E,stats:p}))},onTimeout:function(p,y,E){r.resetLoader(e,h),f(new De({type:V.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after "+m.timeout+"ms"),networkDetails:E,stats:p}))},onProgress:function(p,y,E,S){t&&t({frag:e,part:null,payload:E,networkDetails:S})}})})},n.loadPart=function(e,t,r){var s=this;this.abort();var o=this.config,l=o.fLoader,u=o.loader;return new Promise(function(d,f){if(s.loader&&s.loader.destroy(),e.gap||t.gap){f(si(e,t));return}var h=s.loader=e.loader=l?new l(o):new u(o),c=ai(e,t),v=qr(o.fragLoadPolicy.default),m={loadPolicy:v,timeout:v.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:ni};t.stats=h.stats,h.load(c,m,{onSuccess:function(p,y,E,S){s.resetLoader(e,h),s.updateStatsFromPart(e,t);var L={frag:e,part:t,payload:p.data,networkDetails:S};r(L),d(L)},onError:function(p,y,E,S){s.resetLoader(e,h),f(new De({type:V.NETWORK_ERROR,details:_.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ge({url:c.url,data:void 0},p),error:new Error("HTTP Error "+p.code+" "+p.text),networkDetails:E,stats:S}))},onAbort:function(p,y,E){e.stats.aborted=t.stats.aborted,s.resetLoader(e,h),f(new De({type:V.NETWORK_ERROR,details:_.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:E,stats:p}))},onTimeout:function(p,y,E){s.resetLoader(e,h),f(new De({type:V.NETWORK_ERROR,details:_.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after "+m.timeout+"ms"),networkDetails:E,stats:p}))}})})},n.updateStatsFromPart=function(e,t){var r=e.stats,s=t.stats,o=s.total;if(r.loaded+=s.loaded,o){var l=Math.round(e.duration/t.duration),u=Math.min(Math.round(r.loaded/o),l),d=l-u,f=d*Math.round(r.loaded/u);r.total=r.loaded+f}else r.total=Math.max(r.loaded,r.total);var h=r.loading,c=s.loading;h.start?h.first+=c.first-c.start:(h.start=c.start,h.first=c.first),h.end=c.end},n.resetLoader=function(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()},a}();function ai(a,n){n===void 0&&(n=null);var i=n||a,e={frag:a,part:n,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},t=i.byteRangeStartOffset,r=i.byteRangeEndOffset;if(O(t)&&O(r)){var s,o=t,l=r;if(a.sn==="initSegment"&&((s=a.decryptdata)==null?void 0:s.method)==="AES-128"){var u=r-t;u%16&&(l=r+(16-u%16)),t!==0&&(e.resetIV=!0,o=t-16)}e.rangeStart=o,e.rangeEnd=l}return e}function si(a,n){var i=new Error("GAP "+(a.gap?"tag":"attribute")+" found"),e={type:V.MEDIA_ERROR,details:_.FRAG_GAP,fatal:!1,frag:a,error:i,networkDetails:null};return n&&(e.part=n),(n||a).stats.aborted=!0,new De(e)}var De=function(a){Re(n,a);function n(i){var e;return e=a.call(this,i.error.message)||this,e.data=void 0,e.data=i,e}return n}(ze(Error)),Va=function(){function a(i){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=i}var n=a.prototype;return n.abort=function(e){for(var t in this.keyUriToKeyInfo){var r=this.keyUriToKeyInfo[t].loader;if(r){var s;if(e&&e!==((s=r.context)==null?void 0:s.frag.type))return;r.abort()}}},n.detach=function(){for(var e in this.keyUriToKeyInfo){var t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}},n.destroy=function(){this.detach();for(var e in this.keyUriToKeyInfo){var t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}},n.createKeyLoadError=function(e,t,r,s,o){return t===void 0&&(t=_.KEY_LOAD_ERROR),new De({type:V.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:o,error:r,networkDetails:s})},n.loadClear=function(e,t){var r=this;if(this.emeController&&this.config.emeEnabled)for(var s=e.sn,o=e.cc,l=function(){var f=t[u];if(o<=f.cc&&(s==="initSegment"||f.sn==="initSegment"||s<f.sn))return r.emeController.selectKeySystemFormat(f).then(function(h){f.setKeyFormat(h)}),1},u=0;u<t.length&&!l();u++);},n.load=function(e){var t=this;return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(function(r){return t.loadInternal(e,r)}):this.loadInternal(e)},n.loadInternal=function(e,t){var r,s;t&&e.setKeyFormat(t);var o=e.decryptdata;if(!o){var l=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,_.KEY_LOAD_ERROR,l))}var u=o.uri;if(!u)return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error('Invalid key URI: "'+u+'"')));var d=this.keyUriToKeyInfo[u];if((r=d)!=null&&r.decryptdata.key)return o.key=d.decryptdata.key,Promise.resolve({frag:e,keyInfo:d});if((s=d)!=null&&s.keyLoadPromise){var f;switch((f=d.mediaKeySessionContext)==null?void 0:f.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return d.keyLoadPromise.then(function(h){return o.key=h.keyInfo.decryptdata.key,{frag:e,keyInfo:d}})}}switch(d=this.keyUriToKeyInfo[u]={decryptdata:o,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},o.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return o.keyFormat==="identity"?this.loadKeyHTTP(d,e):this.loadKeyEME(d,e);case"AES-128":return this.loadKeyHTTP(d,e);default:return Promise.reject(this.createKeyLoadError(e,_.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'+o.method+'"')))}},n.loadKeyEME=function(e,t){var r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var s=this.emeController.loadKey(r);if(s)return(e.keyLoadPromise=s.then(function(o){return e.mediaKeySessionContext=o,r})).catch(function(o){throw e.keyLoadPromise=null,o})}return Promise.resolve(r)},n.loadKeyHTTP=function(e,t){var r=this,s=this.config,o=s.loader,l=new o(s);return t.keyLoader=e.loader=l,e.keyLoadPromise=new Promise(function(u,d){var f={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},h=s.keyLoadPolicy.default,c={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},v={onSuccess:function(g,p,y,E){var S=y.frag,L=y.keyInfo,D=y.url;if(!S.decryptdata||L!==r.keyUriToKeyInfo[D])return d(r.createKeyLoadError(S,_.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),E));L.decryptdata.key=S.decryptdata.key=new Uint8Array(g.data),S.keyLoader=null,L.loader=null,u({frag:S,keyInfo:L})},onError:function(g,p,y,E){r.resetLoader(p),d(r.createKeyLoadError(t,_.KEY_LOAD_ERROR,new Error("HTTP Error "+g.code+" loading key "+g.text),y,ge({url:f.url,data:void 0},g)))},onTimeout:function(g,p,y){r.resetLoader(p),d(r.createKeyLoadError(t,_.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),y))},onAbort:function(g,p,y){r.resetLoader(p),d(r.createKeyLoadError(t,_.INTERNAL_ABORTED,new Error("key loading aborted"),y))}};l.load(f,c,v)})},n.resetLoader=function(e){var t=e.frag,r=e.keyInfo,s=e.url,o=r.loader;t.keyLoader===o&&(t.keyLoader=null,r.loader=null),delete this.keyUriToKeyInfo[s],o&&o.destroy()},a}(),Ka=function(){function a(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}var n=a.prototype;return n.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},n.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},n.onHandlerDestroyed=function(){},n.hasInterval=function(){return!!this._tickInterval},n.hasNextTick=function(){return!!this._tickTimer},n.setInterval=function(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)},n.clearInterval=function(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1},n.clearNextTick=function(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1},n.tick=function(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)},n.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},n.doTick=function(){},a}(),oi=function(n,i,e,t,r,s){t===void 0&&(t=0),r===void 0&&(r=-1),s===void 0&&(s=!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=ft(),this.buffering={audio:ft(),video:ft(),audiovideo:ft()},this.level=n,this.sn=i,this.id=e,this.size=t,this.part=r,this.partial=s};function ft(){return{start:0,executeStart:0,executeEnd:0,end:0}}function dt(a,n){for(var i=0,e=a.length;i<e;i++){var t;if(((t=a[i])==null?void 0:t.cc)===n)return a[i]}return null}function Wa(a,n,i){return!!(n&&(i.endCC>i.startCC||a&&a.cc<i.startCC))}function Ya(a,n){var i=a.fragments,e=n.fragments;if(!e.length||!i.length){A.log("No fragments to align");return}var t=dt(i,e[0].cc);if(!t||t&&!t.startPTS){A.log("No frag in previous level to align on");return}return t}function li(a,n){if(a){var i=a.start+n;a.start=a.startPTS=i,a.endPTS=i+a.duration}}function ui(a,n){for(var i=n.fragments,e=0,t=i.length;e<t;e++)li(i[e],a);n.fragmentHint&&li(n.fragmentHint,a),n.alignedSliding=!0}function qa(a,n,i){n&&(ja(a,i,n),!i.alignedSliding&&n&&Xa(i,n),!i.alignedSliding&&n&&!i.skippedSegments&&Hr(n,i))}function ja(a,n,i){if(Wa(a,i,n)){var e=Ya(i,n);e&&O(e.start)&&(A.log("Adjusting PTS using last level due to CC increase within current level "+n.url),ui(e.start,n))}}function Xa(a,n){if(!(!a.hasProgramDateTime||!n.hasProgramDateTime)){var i=a.fragments,e=n.fragments;if(!(!i.length||!e.length)){var t,r,s=Math.min(n.endCC,a.endCC);n.startCC<s&&a.startCC<s&&(t=dt(e,s),r=dt(i,s)),(!t||!r)&&(t=e[Math.floor(e.length/2)],r=dt(i,t.cc)||i[Math.floor(i.length/2)]);var o=t.programDateTime,l=r.programDateTime;if(!(!o||!l)){var u=(l-o)/1e3-(r.start-t.start);ui(u,a)}}}}var za=function(){function a(i,e){this.subtle=void 0,this.aesIV=void 0,this.subtle=i,this.aesIV=e}var n=a.prototype;return n.decrypt=function(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)},a}(),$a=function(){function a(i,e){this.subtle=void 0,this.key=void 0,this.subtle=i,this.key=e}var n=a.prototype;return n.expandKey=function(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])},a}();function Qa(a){var n=a.byteLength,i=n&&new DataView(a.buffer).getUint8(n-1);return i?Me(a,0,n-i):a}var Za=function(){function a(){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()}var n=a.prototype;return n.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),r=new Uint32Array(4),s=0;s<4;s++)r[s]=t.getUint32(s*4);return r},n.initTable=function(){var e=this.sBox,t=this.invSBox,r=this.subMix,s=r[0],o=r[1],l=r[2],u=r[3],d=this.invSubMix,f=d[0],h=d[1],c=d[2],v=d[3],m=new Uint32Array(256),g=0,p=0,y=0;for(y=0;y<256;y++)y<128?m[y]=y<<1:m[y]=y<<1^283;for(y=0;y<256;y++){var E=p^p<<1^p<<2^p<<3^p<<4;E=E>>>8^E&255^99,e[g]=E,t[E]=g;var S=m[g],L=m[S],D=m[L],R=m[E]*257^E*16843008;s[g]=R<<24|R>>>8,o[g]=R<<16|R>>>16,l[g]=R<<8|R>>>24,u[g]=R,R=D*16843009^L*65537^S*257^g*16843008,f[E]=R<<24|R>>>8,h[E]=R<<16|R>>>16,c[E]=R<<8|R>>>24,v[E]=R,g?(g=S^m[m[m[D^S]]],p^=m[m[p]]):g=p=1}},n.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,s=0;s<t.length&&r;)r=t[s]===this.key[s],s++;if(!r){this.key=t;var o=this.keySize=t.length;if(o!==4&&o!==6&&o!==8)throw new Error("Invalid aes key size="+o);var l=this.ksRows=(o+6+1)*4,u,d,f=this.keySchedule=new Uint32Array(l),h=this.invKeySchedule=new Uint32Array(l),c=this.sBox,v=this.rcon,m=this.invSubMix,g=m[0],p=m[1],y=m[2],E=m[3],S,L;for(u=0;u<l;u++){if(u<o){S=f[u]=t[u];continue}L=S,u%o===0?(L=L<<8|L>>>24,L=c[L>>>24]<<24|c[L>>>16&255]<<16|c[L>>>8&255]<<8|c[L&255],L^=v[u/o|0]<<24):o>6&&u%o===4&&(L=c[L>>>24]<<24|c[L>>>16&255]<<16|c[L>>>8&255]<<8|c[L&255]),f[u]=S=(f[u-o]^L)>>>0}for(d=0;d<l;d++)u=l-d,d&3?L=f[u]:L=f[u-4],d<4||u<=4?h[d]=L:h[d]=g[c[L>>>24]]^p[c[L>>>16&255]]^y[c[L>>>8&255]]^E[c[L&255]],h[d]=h[d]>>>0}},n.networkToHostOrderSwap=function(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24},n.decrypt=function(e,t,r){for(var s=this.keySize+6,o=this.invKeySchedule,l=this.invSBox,u=this.invSubMix,d=u[0],f=u[1],h=u[2],c=u[3],v=this.uint8ArrayToUint32Array_(r),m=v[0],g=v[1],p=v[2],y=v[3],E=new Int32Array(e),S=new Int32Array(E.length),L,D,R,T,b,I,P,C,w,M,F,H,U,W,K=this.networkToHostOrderSwap;t<E.length;){for(w=K(E[t]),M=K(E[t+1]),F=K(E[t+2]),H=K(E[t+3]),b=w^o[0],I=H^o[1],P=F^o[2],C=M^o[3],U=4,W=1;W<s;W++)L=d[b>>>24]^f[I>>16&255]^h[P>>8&255]^c[C&255]^o[U],D=d[I>>>24]^f[P>>16&255]^h[C>>8&255]^c[b&255]^o[U+1],R=d[P>>>24]^f[C>>16&255]^h[b>>8&255]^c[I&255]^o[U+2],T=d[C>>>24]^f[b>>16&255]^h[I>>8&255]^c[P&255]^o[U+3],b=L,I=D,P=R,C=T,U=U+4;L=l[b>>>24]<<24^l[I>>16&255]<<16^l[P>>8&255]<<8^l[C&255]^o[U],D=l[I>>>24]<<24^l[P>>16&255]<<16^l[C>>8&255]<<8^l[b&255]^o[U+1],R=l[P>>>24]<<24^l[C>>16&255]<<16^l[b>>8&255]<<8^l[I&255]^o[U+2],T=l[C>>>24]<<24^l[b>>16&255]<<16^l[I>>8&255]<<8^l[P&255]^o[U+3],S[t]=K(L^m),S[t+1]=K(T^g),S[t+2]=K(R^p),S[t+3]=K(D^y),m=w,g=M,p=F,y=H,t=t+4}return S.buffer},a}(),Ja=16,Ut=function(){function a(i,e){var t=e===void 0?{}:e,r=t.removePKCS7Padding,s=r===void 0?!0:r;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=i.enableSoftwareAES,this.removePKCS7Padding=s,s)try{var o=self.crypto;o&&(this.subtle=o.subtle||o.webkitSubtle)}catch{}this.subtle===null&&(this.useSoftware=!0)}var n=a.prototype;return n.destroy=function(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null},n.isSync=function(){return this.useSoftware},n.flush=function(){var e=this.currentResult,t=this.remainderData;if(!e||t)return this.reset(),null;var r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Qa(r):r},n.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},n.decrypt=function(e,t,r){var s=this;return this.useSoftware?new Promise(function(o,l){s.softwareDecrypt(new Uint8Array(e),t,r);var u=s.flush();u?o(u.buffer):l(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r)},n.softwareDecrypt=function(e,t,r){var s=this.currentIV,o=this.currentResult,l=this.remainderData;this.logOnce("JS AES decrypt"),l&&(e=xe(l,e),this.remainderData=null);var u=this.getValidChunk(e);if(!u.length)return null;s&&(r=s);var d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new Za),d.expandKey(t);var f=o;return this.currentResult=d.decrypt(u.buffer,0,r),this.currentIV=Me(u,-16).buffer,f||null},n.webCryptoDecrypt=function(e,t,r){var s=this,o=this.subtle;return(this.key!==t||!this.fastAesKey)&&(this.key=t,this.fastAesKey=new $a(o,t)),this.fastAesKey.expandKey().then(function(l){if(!o)return Promise.reject(new Error("web crypto not initialized"));s.logOnce("WebCrypto AES decrypt");var u=new za(o,new Uint8Array(r));return u.decrypt(e.buffer,l)}).catch(function(l){return A.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+l.name+": "+l.message),s.onWebCryptoError(e,t,r)})},n.onWebCryptoError=function(e,t,r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r);var s=this.flush();if(s)return s.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")},n.getValidChunk=function(e){var t=e,r=e.length-e.length%Ja;return r!==e.length&&(t=Me(e,0,r),this.remainderData=Me(e,r)),t},n.logOnce=function(e){this.logEnabled&&(A.log("[decrypter]: "+e),this.logEnabled=!1)},a}(),es={toString:function(n){for(var i="",e=n.length,t=0;t<e;t++)i+="["+n.start(t).toFixed(3)+"-"+n.end(t).toFixed(3)+"]";return i}},k={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},ts=function(a){Re(n,a);function n(e,t,r,s,o){var l;return l=a.call(this)||this,l.hls=void 0,l.fragPrevious=null,l.fragCurrent=null,l.fragmentTracker=void 0,l.transmuxer=null,l._state=k.STOPPED,l.playlistType=void 0,l.media=null,l.mediaBuffer=null,l.config=void 0,l.bitrateTest=!1,l.lastCurrentTime=0,l.nextLoadPosition=0,l.startPosition=0,l.startTimeOffset=null,l.loadedmetadata=!1,l.retryDate=0,l.levels=null,l.fragmentLoader=void 0,l.keyLoader=void 0,l.levelLastLoaded=null,l.startFragRequested=!1,l.decrypter=void 0,l.initPTS=[],l.onvseeking=null,l.onvended=null,l.logPrefix="",l.log=void 0,l.warn=void 0,l.playlistType=o,l.logPrefix=s,l.log=A.log.bind(A,s+":"),l.warn=A.warn.bind(A,s+":"),l.hls=e,l.fragmentLoader=new Ha(e.config),l.keyLoader=r,l.fragmentTracker=t,l.config=e.config,l.decrypter=new Ut(e.config),e.on(x.MANIFEST_LOADED,l.onManifestLoaded,qi(l)),l}var i=n.prototype;return i.doTick=function(){this.onTickEnd()},i.onTickEnd=function(){},i.startLoad=function(t){},i.stopLoad=function(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var t=this.fragCurrent;t!=null&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=k.STOPPED},i._streamEnded=function(t,r){if(r.live||t.nextStart||!t.end||!this.media)return!1;var s=r.partList;if(s!=null&&s.length){var o=s[s.length-1],l=ae.isBuffered(this.media,o.start+o.duration/2);return l}var u=r.fragments[r.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(u)},i.getLevelDetails=function(){if(this.levels&&this.levelLastLoaded!==null){var t;return(t=this.levelLastLoaded)==null?void 0:t.details}},i.onMediaAttached=function(t,r){var s=this.media=this.mediaBuffer=r.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),s.addEventListener("seeking",this.onvseeking),s.addEventListener("ended",this.onvended);var o=this.config;this.levels&&o.autoStartLoad&&this.state===k.STOPPED&&this.startLoad(o.startPosition)},i.onMediaDetaching=function(){var t=this.media;t!=null&&t.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),t&&this.onvseeking&&this.onvended&&(t.removeEventListener("seeking",this.onvseeking),t.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()},i.onMediaSeeking=function(){var t=this.config,r=this.fragCurrent,s=this.media,o=this.mediaBuffer,l=this.state,u=s?s.currentTime:0,d=ae.bufferInfo(o||s,u,t.maxBufferHole);if(this.log("media seeking to "+(O(u)?u.toFixed(3):u)+", state: "+l),this.state===k.ENDED)this.resetLoadingState();else if(r){var f=t.maxFragLookUpTolerance,h=r.start-f,c=r.start+r.duration+f;if(!d.len||c<d.start||h>d.end){var v=u>c;(u<h||v)&&(v&&r.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),r.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}s&&(this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0),this.lastCurrentTime=u),!this.loadedmetadata&&!d.len&&(this.nextLoadPosition=this.startPosition=u),this.tickImmediate()},i.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},i.onManifestLoaded=function(t,r){this.startTimeOffset=r.startTimeOffset,this.initPTS=[]},i.onHandlerDestroying=function(){this.hls.off(x.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),a.prototype.onHandlerDestroying.call(this),this.hls=null},i.onHandlerDestroyed=function(){this.state=k.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,a.prototype.onHandlerDestroyed.call(this)},i.loadFragment=function(t,r,s){this._loadFragForPlayback(t,r,s)},i._loadFragForPlayback=function(t,r,s){var o=this,l=function(d){if(o.fragContextChanged(t)){o.warn("Fragment "+t.sn+(d.part?" p: "+d.part.index:"")+" of level "+t.level+" was dropped during download."),o.fragmentTracker.removeFragment(t);return}t.stats.chunkCount++,o._handleFragmentLoadProgress(d)};this._doFragLoad(t,r,s,l).then(function(u){if(u){var d=o.state;if(o.fragContextChanged(t)){(d===k.FRAG_LOADING||!o.fragCurrent&&d===k.PARSING)&&(o.fragmentTracker.removeFragment(t),o.state=k.IDLE);return}"payload"in u&&(o.log("Loaded fragment "+t.sn+" of level "+t.level),o.hls.trigger(x.FRAG_LOADED,u)),o._handleFragmentLoadComplete(u)}}).catch(function(u){o.state===k.STOPPED||o.state===k.ERROR||(o.warn(u),o.resetFragmentLoading(t))})},i.clearTrackerIfNeeded=function(t){var r,s=this.fragmentTracker,o=s.getState(t);if(o===me.APPENDING){var l=t.type,u=this.getFwdBufferInfo(this.mediaBuffer,l),d=Math.max(t.duration,u?u.len:this.config.maxBufferLength);this.reduceMaxBufferLength(d)&&s.removeFragment(t)}else((r=this.mediaBuffer)==null?void 0:r.buffered.length)===0?s.removeAllFragments():s.hasParts(t.type)&&(s.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),s.getState(t)===me.PARTIAL&&s.removeFragment(t))},i.checkLiveUpdate=function(t){if(t.updated&&!t.live){var r=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)},i.flushMainBuffer=function(t,r,s){if(s===void 0&&(s=null),!!(t-r)){var o={startOffset:t,endOffset:r,type:s};this.hls.trigger(x.BUFFER_FLUSHING,o)}},i._loadInitSegment=function(t,r){var s=this;this._doFragLoad(t,r).then(function(o){if(!o||s.fragContextChanged(t)||!s.levels)throw new Error("init load aborted");return o}).then(function(o){var l=s.hls,u=o.payload,d=t.decryptdata;if(u&&u.byteLength>0&&d!=null&&d.key&&d.iv&&d.method==="AES-128"){var f=self.performance.now();return s.decrypter.decrypt(new Uint8Array(u),d.key.buffer,d.iv.buffer).catch(function(h){throw l.trigger(x.ERROR,{type:V.MEDIA_ERROR,details:_.FRAG_DECRYPT_ERROR,fatal:!1,error:h,reason:h.message,frag:t}),h}).then(function(h){var c=self.performance.now();return l.trigger(x.FRAG_DECRYPTED,{frag:t,payload:h,stats:{tstart:f,tdecrypt:c}}),o.payload=h,s.completeInitSegmentLoad(o)})}return s.completeInitSegmentLoad(o)}).catch(function(o){s.state===k.STOPPED||s.state===k.ERROR||(s.warn(o),s.resetFragmentLoading(t))})},i.completeInitSegmentLoad=function(t){var r=this.levels;if(!r)throw new Error("init load aborted, missing levels");var s=t.frag.stats;this.state=k.IDLE,t.frag.data=new Uint8Array(t.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()},i.fragContextChanged=function(t){var r=this.fragCurrent;return!t||!r||t.sn!==r.sn||t.level!==r.level},i.fragBufferedComplete=function(t,r){var s,o,l,u,d=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered "+t.type+" sn: "+t.sn+(r?" part: "+r.index:"")+" of "+(this.playlistType===j.MAIN?"level":"track")+" "+t.level+" (frag:["+((s=t.startPTS)!=null?s:NaN).toFixed(3)+"-"+((o=t.endPTS)!=null?o:NaN).toFixed(3)+"] > buffer:"+(d?es.toString(ae.getBuffered(d)):"(detached)")+")"),t.sn!=="initSegment"){var f;if(t.type!==j.SUBTITLE){var h=t.elementaryStreams;if(!Object.keys(h).some(function(v){return!!h[v]})){this.state=k.IDLE;return}}var c=(f=this.levels)==null?void 0:f[t.level];c!=null&&c.fragmentError&&(this.log("Resetting level fragment error count of "+c.fragmentError+" on frag buffered"),c.fragmentError=0)}this.state=k.IDLE,d&&(!this.loadedmetadata&&t.type==j.MAIN&&d.buffered.length&&((l=this.fragCurrent)==null?void 0:l.sn)===((u=this.fragPrevious)==null?void 0:u.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())},i.seekToStartPos=function(){},i._handleFragmentLoadComplete=function(t){var r=this.transmuxer;if(r){var s=t.frag,o=t.part,l=t.partsLoaded,u=!l||l.length===0||l.some(function(f){return!f}),d=new oi(s.level,s.sn,s.stats.chunkCount+1,0,o?o.index:-1,!u);r.flush(d)}},i._handleFragmentLoadProgress=function(t){},i._doFragLoad=function(t,r,s,o){var l,u=this;s===void 0&&(s=null);var d=r?.details;if(!this.levels||!d)throw new Error("frag load aborted, missing level"+(d?"":" detail")+"s");var f=null;if(t.encrypted&&!((l=t.decryptdata)!=null&&l.key)?(this.log("Loading key for "+t.sn+" of ["+d.startSN+"-"+d.endSN+"], "+(this.logPrefix==="[stream-controller]"?"level":"track")+" "+t.level),this.state=k.KEY_LOADING,this.fragCurrent=t,f=this.keyLoader.load(t).then(function(y){if(!u.fragContextChanged(y.frag))return u.hls.trigger(x.KEY_LOADED,y),u.state===k.KEY_LOADING&&(u.state=k.IDLE),y}),this.hls.trigger(x.KEY_LOADING,{frag:t}),this.fragCurrent===null&&(f=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!t.encrypted&&d.encryptedFragments.length&&this.keyLoader.loadClear(t,d.encryptedFragments),s=Math.max(t.start,s||0),this.config.lowLatencyMode&&t.sn!=="initSegment"){var h=d.partList;if(h&&o){s>t.end&&d.fragmentHint&&(t=d.fragmentHint);var c=this.getNextPart(h,t,s);if(c>-1){var v=h[c];this.log("Loading part sn: "+t.sn+" p: "+v.index+" cc: "+t.cc+" of playlist ["+d.startSN+"-"+d.endSN+"] parts [0-"+c+"-"+(h.length-1)+"] "+(this.logPrefix==="[stream-controller]"?"level":"track")+": "+t.level+", target: "+parseFloat(s.toFixed(3))),this.nextLoadPosition=v.start+v.duration,this.state=k.FRAG_LOADING;var m;return f?m=f.then(function(y){return!y||u.fragContextChanged(y.frag)?null:u.doFragPartsLoad(t,v,r,o)}).catch(function(y){return u.handleFragLoadError(y)}):m=this.doFragPartsLoad(t,v,r,o).catch(function(y){return u.handleFragLoadError(y)}),this.hls.trigger(x.FRAG_LOADING,{frag:t,part:v,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):m}else if(!t.url||this.loadedEndOfParts(h,s))return Promise.resolve(null)}}this.log("Loading fragment "+t.sn+" cc: "+t.cc+" "+(d?"of ["+d.startSN+"-"+d.endSN+"] ":"")+(this.logPrefix==="[stream-controller]"?"level":"track")+": "+t.level+", target: "+parseFloat(s.toFixed(3))),O(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=k.FRAG_LOADING;var g=this.config.progressive,p;return g&&f?p=f.then(function(y){return!y||u.fragContextChanged(y?.frag)?null:u.fragmentLoader.load(t,o)}).catch(function(y){return u.handleFragLoadError(y)}):p=Promise.all([this.fragmentLoader.load(t,g?o:void 0),f]).then(function(y){var E=y[0];return!g&&E&&o&&o(E),E}).catch(function(y){return u.handleFragLoadError(y)}),this.hls.trigger(x.FRAG_LOADING,{frag:t,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):p},i.doFragPartsLoad=function(t,r,s,o){var l=this;return new Promise(function(u,d){var f,h=[],c=(f=s.details)==null?void 0:f.partList,v=function m(g){l.fragmentLoader.loadPart(t,g,o).then(function(p){h[g.index]=p;var y=p.part;l.hls.trigger(x.FRAG_LOADED,p);var E=Vr(s,t.sn,g.index+1)||Kr(c,t.sn,g.index+1);if(E)m(E);else return u({frag:t,part:y,partsLoaded:h})}).catch(d)};v(r)})},i.handleFragLoadError=function(t){if("data"in t){var r=t.data;t.data&&r.details===_.INTERNAL_ABORTED?this.handleFragLoadAborted(r.frag,r.part):this.hls.trigger(x.ERROR,r)}else this.hls.trigger(x.ERROR,{type:V.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null},i._handleTransmuxerFlush=function(t){var r=this.getCurrentContext(t);if(!r||this.state!==k.PARSING){!this.fragCurrent&&this.state!==k.STOPPED&&this.state!==k.ERROR&&(this.state=k.IDLE);return}var s=r.frag,o=r.part,l=r.level,u=self.performance.now();s.stats.parsing.end=u,o&&(o.stats.parsing.end=u),this.updateLevelTiming(s,o,l,t.partial)},i.getCurrentContext=function(t){var r=this.levels,s=this.fragCurrent,o=t.level,l=t.sn,u=t.part;if(!(r!=null&&r[o]))return this.warn("Levels object was unset while buffering fragment "+l+" of level "+o+". The current chunk will not be buffered."),null;var d=r[o],f=u>-1?Vr(d,l,u):null,h=f?f.fragment:ia(d,l,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:f,level:d}):null},i.bufferFragmentData=function(t,r,s,o,l){var u;if(!(!t||this.state!==k.PARSING)){var d=t.data1,f=t.data2,h=d;if(d&&f&&(h=xe(d,f)),!!((u=h)!=null&&u.length)){var c={type:t.type,frag:r,part:s,chunkMeta:o,parent:r.type,data:h};if(this.hls.trigger(x.BUFFER_APPENDING,c),t.dropped&&t.independent&&!s){if(l)return;this.flushBufferGap(r)}}}},i.flushBufferGap=function(t){var r=this.media;if(r){if(!ae.isBuffered(r,r.currentTime)){this.flushMainBuffer(0,t.start);return}var s=r.currentTime,o=ae.bufferInfo(r,s,0),l=t.duration,u=Math.min(this.config.maxFragLookUpTolerance*2,l*.25),d=Math.max(Math.min(t.start-u,o.end-u),s+u);t.start-d>u&&this.flushMainBuffer(d,t.start)}},i.getFwdBufferInfo=function(t,r){var s=this.getLoadPosition();return O(s)?this.getFwdBufferInfoAtPos(t,s,r):null},i.getFwdBufferInfoAtPos=function(t,r,s){var o=this.config.maxBufferHole,l=ae.bufferInfo(t,r,o);if(l.len===0&&l.nextStart!==void 0){var u=this.fragmentTracker.getBufferedFrag(r,s);if(u&&l.nextStart<u.end)return ae.bufferInfo(t,r,Math.max(l.nextStart,o))}return l},i.getMaxBufferLength=function(t){var r=this.config,s;return t?s=Math.max(8*r.maxBufferSize/t,r.maxBufferLength):s=r.maxBufferLength,Math.min(s,r.maxMaxBufferLength)},i.reduceMaxBufferLength=function(t){var r=this.config,s=t||r.maxBufferLength;return r.maxMaxBufferLength>=s?(r.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+r.maxMaxBufferLength+"s"),!0):!1},i.getAppendedFrag=function(t,r){var s=this.fragmentTracker.getAppendedFrag(t,j.MAIN);return s&&"fragment"in s?s.fragment:s},i.getNextFragment=function(t,r){var s=r.fragments,o=s.length;if(!o)return null;var l=this.config,u=s[0].start,d;if(r.live){var f=l.initialLiveManifestSize;if(o<f)return this.warn("Not enough fragments to start playback (have: "+o+", need: "+f+")"),null;(!r.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||t<u)&&(d=this.getInitialLiveFragment(r,s),this.startPosition=this.nextLoadPosition=d?this.hls.liveSyncPosition||d.start:t)}else t<=u&&(d=s[0]);if(!d){var h=l.lowLatencyMode?r.partEnd:r.fragmentEnd;d=this.getFragmentAtPosition(t,h,r)}return this.mapToInitFragWhenRequired(d)},i.isLoopLoading=function(t,r){var s=this.fragmentTracker.getState(t);return(s===me.OK||s===me.PARTIAL&&!!t.gap)&&this.nextLoadPosition>r},i.getNextFragmentLoopLoading=function(t,r,s,o,l){var u=t.gap,d=this.getNextFragment(this.nextLoadPosition,r);if(d===null)return d;if(t=d,u&&t&&!t.gap&&s.nextStart){var f=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,o);if(f!==null&&s.len+f.len>=l)return this.log('buffer full after gaps in "'+o+'" playlist starting at sn: '+t.sn),null}return t},i.mapToInitFragWhenRequired=function(t){return t!=null&&t.initSegment&&!(t!=null&&t.initSegment.data)&&!this.bitrateTest?t.initSegment:t},i.getNextPart=function(t,r,s){for(var o=-1,l=!1,u=!0,d=0,f=t.length;d<f;d++){var h=t[d];if(u=u&&!h.independent,o>-1&&s<h.start)break;var c=h.loaded;c?o=-1:(l||h.independent||u)&&h.fragment===r&&(o=d),l=c}return o},i.loadedEndOfParts=function(t,r){var s=t[t.length-1];return s&&r>s.start&&s.loaded},i.getInitialLiveFragment=function(t,r){var s=this.fragPrevious,o=null;if(s){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+s.programDateTime),o=aa(r,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!o){var l=s.sn+1;if(l>=t.startSN&&l<=t.endSN){var u=r[l-t.startSN];s.cc===u.cc&&(o=u,this.log("Live playlist, switching playlist, load frag with next SN: "+o.sn))}o||(o=oa(r,s.cc),o&&this.log("Live playlist, switching playlist, load frag with same CC: "+o.sn))}}else{var d=this.hls.liveSyncPosition;d!==null&&(o=this.getFragmentAtPosition(d,this.bitrateTest?t.fragmentEnd:t.edge,t))}return o},i.getFragmentAtPosition=function(t,r,s){var o=this.config,l=this.fragPrevious,u=s.fragments,d=s.endSN,f=s.fragmentHint,h=o.maxFragLookUpTolerance,c=s.partList,v=!!(o.lowLatencyMode&&c!=null&&c.length&&f);v&&f&&!this.bitrateTest&&(u=u.concat(f),d=f.sn);var m;if(t<r){var g=t>r-h?0:h;m=Xr(l,u,t,g)}else m=u[u.length-1];if(m){var p=m.sn-s.startSN,y=this.fragmentTracker.getState(m);if((y===me.OK||y===me.PARTIAL&&m.gap)&&(l=m),l&&m.sn===l.sn&&(!v||c[0].fragment.sn>m.sn)){var E=l&&m.level===l.level;if(E){var S=u[p+1];m.sn<d&&this.fragmentTracker.getState(S)!==me.OK?m=S:m=null}}}return m},i.synchronizeToLiveEdge=function(t){var r=this.config,s=this.media;if(s){var o=this.hls.liveSyncPosition,l=s.currentTime,u=t.fragments[0].start,d=t.edge,f=l>=u-r.maxFragLookUpTolerance&&l<=d;if(o!==null&&s.duration>o&&(l<o||!f)){var h=r.liveMaxLatencyDuration!==void 0?r.liveMaxLatencyDuration:r.liveMaxLatencyDurationCount*t.targetduration;(!f&&s.readyState<4||l<d-h)&&(this.loadedmetadata||(this.nextLoadPosition=o),s.readyState&&(this.warn("Playback: "+l.toFixed(3)+" is located too far from the end of live sliding playlist: "+d+", reset currentTime to : "+o.toFixed(3)),s.currentTime=o))}}},i.alignPlaylists=function(t,r,s){var o=t.fragments.length;if(!o)return this.warn("No fragments in live playlist"),0;var l=t.fragments[0].start,u=!r,d=t.alignedSliding&&O(l);if(u||!d&&!l){var f=this.fragPrevious;qa(f,s,t);var h=t.fragments[0].start;return this.log("Live playlist sliding: "+h.toFixed(2)+" start-sn: "+(r?r.startSN:"na")+"->"+t.startSN+" prev-sn: "+(f?f.sn:"na")+" fragments: "+o),h}return l},i.waitForCdnTuneIn=function(t){var r=3;return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*r)},i.setStartPosition=function(t,r){var s=this.startPosition;if(s<r&&(s=-1),s===-1||this.lastCurrentTime===-1){var o=this.startTimeOffset!==null,l=o?this.startTimeOffset:t.startTimeOffset;l!==null&&O(l)?(s=r+l,l<0&&(s+=t.totalduration),s=Math.min(Math.max(r,s),r+t.totalduration),this.log("Start time offset "+l+" found in "+(o?"multivariant":"media")+" playlist, adjust startPosition to "+s),this.startPosition=s):t.live?s=this.hls.liveSyncPosition||r:this.startPosition=s=0,this.lastCurrentTime=s}this.nextLoadPosition=s},i.getLoadPosition=function(){var t=this.media,r=0;return this.loadedmetadata&&t?r=t.currentTime:this.nextLoadPosition&&(r=this.nextLoadPosition),r},i.handleFragLoadAborted=function(t,r){this.transmuxer&&t.sn!=="initSegment"&&t.stats.aborted&&(this.warn("Fragment "+t.sn+(r?" part "+r.index:"")+" of level "+t.level+" was aborted"),this.resetFragmentLoading(t))},i.resetFragmentLoading=function(t){(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==k.FRAG_LOADING_WAITING_RETRY)&&(this.state=k.IDLE)},i.onFragmentOrKeyLoadError=function(t,r){if(r.chunkMeta&&!r.frag){var s=this.getCurrentContext(r.chunkMeta);s&&(r.frag=s.frag)}var o=r.frag;if(!(!o||o.type!==t||!this.levels)){if(this.fragContextChanged(o)){var l;this.warn("Frag load error must match current frag to retry "+o.url+" > "+((l=this.fragCurrent)==null?void 0:l.url));return}var u=r.details===_.FRAG_GAP;u&&this.fragmentTracker.fragBuffered(o,!0);var d=r.errorAction,f=d||{},h=f.action,c=f.retryCount,v=c===void 0?0:c,m=f.retryConfig;if(d&&h===ue.RetryRequest&&m){this.resetStartWhenNotLoaded(this.levelLastLoaded);var g=Mt(m,v);this.warn("Fragment "+o.sn+" of "+t+" "+o.level+" errored with "+r.details+", retrying loading "+(v+1)+"/"+m.maxNumRetry+" in "+g+"ms"),d.resolved=!0,this.retryDate=self.performance.now()+g,this.state=k.FRAG_LOADING_WAITING_RETRY}else if(m&&d)if(this.resetFragmentErrors(t),v<m.maxNumRetry)!u&&h!==ue.RemoveAlternatePermanently&&(d.resolved=!0);else{A.warn(r.details+" reached or exceeded max retry ("+v+")");return}else d?.action===ue.SendAlternateToPenaltyBox?this.state=k.WAITING_LEVEL:this.state=k.ERROR;this.tickImmediate()}},i.reduceLengthAndFlushBuffer=function(t){if(this.state===k.PARSING||this.state===k.PARSED){var r=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,r),o=s&&s.len>.5;o&&this.reduceMaxBufferLength(s.len);var l=!o;return l&&this.warn("Buffer full error while media.currentTime is not buffered, flush "+r+" buffer"),t.frag&&(this.fragmentTracker.removeFragment(t.frag),this.nextLoadPosition=t.frag.start),this.resetLoadingState(),l}return!1},i.resetFragmentErrors=function(t){t===j.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==k.STOPPED&&(this.state=k.IDLE)},i.afterBufferFlushed=function(t,r,s){if(t){var o=ae.getBuffered(t);this.fragmentTracker.detectEvictedFragments(r,o,s),this.state===k.ENDED&&this.resetLoadingState()}},i.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=k.IDLE},i.resetStartWhenNotLoaded=function(t){if(!this.loadedmetadata){this.startFragRequested=!1;var r=t?t.details:null;r!=null&&r.live?(this.startPosition=-1,this.setStartPosition(r,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},i.resetWhenMissingContext=function(t){this.warn("The loading context changed while buffering fragment "+t.sn+" of level "+t.level+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()},i.removeUnbufferedFrags=function(t){t===void 0&&(t=0),this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)},i.updateLevelTiming=function(t,r,s,o){var l=this,u,d=s.details;if(!d){this.warn("level.details undefined");return}var f=Object.keys(t.elementaryStreams).reduce(function(c,v){var m=t.elementaryStreams[v];if(m){var g=m.endPTS-m.startPTS;if(g<=0)return l.warn("Could not parse fragment "+t.sn+" "+v+" duration reliably ("+g+")"),c||!1;var p=o?0:Gr(d,t,m.startPTS,m.endPTS,m.startDTS,m.endDTS);return l.hls.trigger(x.LEVEL_PTS_UPDATED,{details:d,level:s,drift:p,type:v,frag:t,start:m.startPTS,end:m.endPTS}),!0}return c},!1);if(!f&&((u=this.transmuxer)==null?void 0:u.error)===null){var h=new Error("Found no media in fragment "+t.sn+" of level "+t.level+" resetting transmuxer to fallback to playlist timing");if(s.fragmentError===0&&(s.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(h.message),this.hls.trigger(x.ERROR,{type:V.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:h,frag:t,reason:"Found no media in msn "+t.sn+' of level "'+s.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=k.PARSED,this.hls.trigger(x.FRAG_PARSED,{frag:t,part:r})},i.resetTransmuxer=function(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)},i.recoverWorkerError=function(t){t.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())},he(n,[{key:"state",get:function(){return this._state},set:function(t){var r=this._state;r!==t&&(this._state=t,this.log(r+"->"+t))}}]),n}(Ka);function fi(){return self.SourceBuffer||self.WebKitSourceBuffer}function di(){var a=Ne();if(!a)return!1;var n=fi();return!n||n.prototype&&typeof n.prototype.appendBuffer=="function"&&typeof n.prototype.remove=="function"}function rs(){if(!di())return!1;var a=Ne();return typeof a?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(function(n){return a.isTypeSupported(_t(n,"video"))})||["mp4a.40.2","fLaC"].some(function(n){return a.isTypeSupported(_t(n,"audio"))}))}function is(){var a,n=fi();return typeof(n==null||(a=n.prototype)==null?void 0:a.changeType)=="function"}function Ie(a,n){return a===void 0&&(a=""),n===void 0&&(n=9e4),{type:a,id:-1,pid:-1,inputTimeScale:n,sequenceNumber:-1,samples:[],dropped:0}}var hi=function(){function a(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var n=a.prototype;return n.resetInitSegment=function(e,t,r,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},n.resetTimeStamp=function(e){this.initPTS=e,this.resetContiguity()},n.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},n.canParse=function(e,t){return!1},n.appendFrame=function(e,t,r){},n.demux=function(e,t){this.cachedData&&(e=xe(this.cachedData,e),this.cachedData=null);var r=Qe(e,0),s=r?r.length:0,o,l=this._audioTrack,u=this._id3Track,d=r?dr(r):void 0,f=e.length;for((this.basePTS===null||this.frameIndex===0&&O(d))&&(this.basePTS=ns(d,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),r&&r.length>0&&u.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Te.audioId3,duration:Number.POSITIVE_INFINITY});s<f;){if(this.canParse(e,s)){var h=this.appendFrame(l,e,s);h?(this.frameIndex++,this.lastPTS=h.sample.pts,s+=h.length,o=s):s=f}else sn(e,s)?(r=Qe(e,s),u.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Te.audioId3,duration:Number.POSITIVE_INFINITY}),s+=r.length,o=s):s++;if(s===f&&o!==f){var c=Me(e,o);this.cachedData?this.cachedData=xe(this.cachedData,c):this.cachedData=c}}return{audioTrack:l,videoTrack:Ie(),id3Track:u,textTrack:Ie()}},n.demuxSampleAes=function(e,t,r){return Promise.reject(new Error("["+this+"] This demuxer does not support Sample-AES decryption"))},n.flush=function(e){var t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ie(),id3Track:this._id3Track,textTrack:Ie()}},n.destroy=function(){},a}(),ns=function(n,i,e){if(O(n))return n*90;var t=e?e.baseTime*9e4/e.timescale:0;return i*9e4+t};function as(a,n,i,e){var t,r,s,o,l=navigator.userAgent.toLowerCase(),u=e,d=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];t=((n[i+2]&192)>>>6)+1;var f=(n[i+2]&60)>>>2;if(f>d.length-1){var h=new Error("invalid ADTS sampling index:"+f);a.emit(x.ERROR,x.ERROR,{type:V.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!0,error:h,reason:h.message});return}return s=(n[i+2]&1)<<2,s|=(n[i+3]&192)>>>6,A.log("manifest codec:"+e+", ADTS type:"+t+", samplingIndex:"+f),/firefox/i.test(l)?f>=6?(t=5,o=new Array(4),r=f-3):(t=2,o=new Array(2),r=f):l.indexOf("android")!==-1?(t=2,o=new Array(2),r=f):(t=5,o=new Array(4),e&&(e.indexOf("mp4a.40.29")!==-1||e.indexOf("mp4a.40.5")!==-1)||!e&&f>=6?r=f-3:((e&&e.indexOf("mp4a.40.2")!==-1&&(f>=6&&s===1||/vivaldi/i.test(l))||!e&&s===1)&&(t=2,o=new Array(2)),r=f)),o[0]=t<<3,o[0]|=(f&14)>>1,o[1]|=(f&1)<<7,o[1]|=s<<3,t===5&&(o[1]|=(r&14)>>1,o[2]=(r&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:d[f],channelCount:s,codec:"mp4a.40."+t,manifestCodec:u}}function ci(a,n){return a[n]===255&&(a[n+1]&246)===240}function vi(a,n){return a[n+1]&1?7:9}function Gt(a,n){return(a[n+3]&3)<<11|a[n+4]<<3|(a[n+5]&224)>>>5}function ss(a,n){return n+5<a.length}function ht(a,n){return n+1<a.length&&ci(a,n)}function os(a,n){return ss(a,n)&&ci(a,n)&&Gt(a,n)<=a.length-n}function ls(a,n){if(ht(a,n)){var i=vi(a,n);if(n+i>=a.length)return!1;var e=Gt(a,n);if(e<=i)return!1;var t=n+e;return t===a.length||ht(a,t)}return!1}function gi(a,n,i,e,t){if(!a.samplerate){var r=as(n,i,e,t);if(!r)return;a.config=r.config,a.samplerate=r.samplerate,a.channelCount=r.channelCount,a.codec=r.codec,a.manifestCodec=r.manifestCodec,A.log("parsed codec:"+a.codec+", rate:"+r.samplerate+", channels:"+r.channelCount)}}function mi(a){return 1024*9e4/a}function us(a,n){var i=vi(a,n);if(n+i<=a.length){var e=Gt(a,n)-i;if(e>0)return{headerLength:i,frameLength:e}}}function pi(a,n,i,e,t){var r=mi(a.samplerate),s=e+t*r,o=us(n,i),l;if(o){var u=o.frameLength,d=o.headerLength,f=d+u,h=Math.max(0,i+f-n.length);h?(l=new Uint8Array(f-d),l.set(n.subarray(i+d,n.length),0)):l=n.subarray(i+d,i+f);var c={unit:l,pts:s};return h||a.samples.push(c),{sample:c,length:f,missing:h}}var v=n.length-i;l=new Uint8Array(v),l.set(n.subarray(i,n.length),0);var m={unit:l,pts:s};return{sample:m,length:v,missing:-1}}var ct=null,fs=[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],ds=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],hs=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],cs=[0,1,1,4];function yi(a,n,i,e,t){if(!(i+24>n.length)){var r=Ei(n,i);if(r&&i+r.frameLength<=n.length){var s=r.samplesPerFrame*9e4/r.sampleRate,o=e+t*s,l={unit:n.subarray(i,i+r.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=r.channelCount,a.samplerate=r.sampleRate,a.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}}function Ei(a,n){var i=a[n+1]>>3&3,e=a[n+1]>>1&3,t=a[n+2]>>4&15,r=a[n+2]>>2&3;if(i!==1&&t!==0&&t!==15&&r!==3){var s=a[n+2]>>1&1,o=a[n+3]>>6,l=i===3?3-e:e===3?3:4,u=fs[l*14+t-1]*1e3,d=i===3?0:i===2?1:2,f=ds[d*3+r],h=o===3?1:2,c=hs[i][e],v=cs[e],m=c*8*v,g=Math.floor(c*u/f+s)*v;if(ct===null){var p=navigator.userAgent||"",y=p.match(/Chrome\/(\d+)/i);ct=y?parseInt(y[1]):0}var E=!!ct&&ct<=87;return E&&e===2&&u>=224e3&&o===0&&(a[n+3]=a[n+3]|128),{sampleRate:f,channelCount:h,frameLength:g,samplesPerFrame:m}}}function Ht(a,n){return a[n]===255&&(a[n+1]&224)===224&&(a[n+1]&6)!==0}function xi(a,n){return n+1<a.length&&Ht(a,n)}function vs(a,n){var i=4;return Ht(a,n)&&i<=a.length-n}function Ti(a,n){if(n+1<a.length&&Ht(a,n)){var i=4,e=Ei(a,n),t=i;e!=null&&e.frameLength&&(t=e.frameLength);var r=n+t;return r===a.length||xi(a,r)}return!1}var gs=function(a){Re(n,a);function n(e,t){var r;return r=a.call(this)||this,r.observer=void 0,r.config=void 0,r.observer=e,r.config=t,r}var i=n.prototype;return i.resetInitSegment=function(t,r,s,o){a.prototype.resetInitSegment.call(this,t,r,s,o),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:o,inputTimeScale:9e4,dropped:0}},n.probe=function(t){if(!t)return!1;var r=Qe(t,0),s=r?.length||0;if(Ti(t,s))return!1;for(var o=t.length;s<o;s++)if(ls(t,s))return A.log("ADTS sync word found !"),!0;return!1},i.canParse=function(t,r){return os(t,r)},i.appendFrame=function(t,r,s){gi(t,this.observer,r,s,t.manifestCodec);var o=pi(t,r,s,this.basePTS,this.frameIndex);if(o&&o.missing===0)return o},n}(hi),ms=/\/emsg[-/]ID3/i,ps=function(){function a(i,e){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=e}var n=a.prototype;return n.resetTimeStamp=function(){},n.resetInitSegment=function(e,t,r,s){var o=this.videoTrack=Ie("video",1),l=this.audioTrack=Ie("audio",1),u=this.txtTrack=Ie("text",1);if(this.id3Track=Ie("id3",1),this.timeOffset=0,!!(e!=null&&e.byteLength)){var d=Er(e);if(d.video){var f=d.video,h=f.id,c=f.timescale,v=f.codec;o.id=h,o.timescale=u.timescale=c,o.codec=v}if(d.audio){var m=d.audio,g=m.id,p=m.timescale,y=m.codec;l.id=g,l.timescale=p,l.codec=y}u.id=gr.text,o.sampleDuration=0,o.duration=l.duration=s}},n.resetContiguity=function(){this.remainderData=null},a.probe=function(e){return gn(e)},n.demux=function(e,t){this.timeOffset=t;var r=e,s=this.videoTrack,o=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=xe(this.remainderData,e));var l=An(r);this.remainderData=l.remainder,s.samples=l.valid||new Uint8Array}else s.samples=r;var u=this.extractID3Track(s,t);return o.samples=xr(t,s),{videoTrack:s,audioTrack:this.audioTrack,id3Track:u,textTrack:this.txtTrack}},n.flush=function(){var e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;var s=this.extractID3Track(t,this.timeOffset);return r.samples=xr(e,t),{videoTrack:t,audioTrack:Ie(),id3Track:s,textTrack:Ie()}},n.extractID3Track=function(e,t){var r=this.id3Track;if(e.samples.length){var s=G(e.samples,["emsg"]);s&&s.forEach(function(o){var l=In(o);if(ms.test(l.schemeIdUri)){var u=O(l.presentationTime)?l.presentationTime/l.timeScale:t+l.presentationTimeDelta/l.timeScale,d=l.eventDuration===4294967295?Number.POSITIVE_INFINITY:l.eventDuration/l.timeScale;d<=.001&&(d=Number.POSITIVE_INFINITY);var f=l.payload;r.samples.push({data:f,len:f.byteLength,dts:u,pts:u,type:Te.emsg,duration:d})}})}return r},n.demuxSampleAes=function(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},n.destroy=function(){},a}(),ys=function(n,i){var e=0,t=5;i+=t;for(var r=new Uint32Array(1),s=new Uint32Array(1),o=new Uint8Array(1);t>0;){o[0]=n[i];var l=Math.min(t,8),u=8-l;s[0]=4278190080>>>24+u<<u,r[0]=(o[0]&s[0])>>u,e=e?e<<l|r[0]:r[0],i+=1,t-=l}return e},Es=function(){function a(){this.VideoSample=null}var n=a.prototype;return n.createVideoSample=function(e,t,r,s){return{key:e,frame:!1,pts:t,dts:r,units:[],debug:s,length:0}},n.getLastNalUnit=function(e){var t,r=this.VideoSample,s;if((!r||r.units.length===0)&&(r=e[e.length-1]),(t=r)!=null&&t.units){var o=r.units;s=o[o.length-1]}return s},n.pushAccessUnit=function(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){var r=t.samples,s=r.length;if(s){var o=r[s-1];e.pts=o.pts,e.dts=o.dts}else{t.dropped++;return}}t.samples.push(e)}e.debug.length&&A.log(e.pts+"/"+e.dts+":"+e.debug)},a}(),Si=function(){function a(i){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=i,this.bytesAvailable=i.byteLength,this.word=0,this.bitsAvailable=0}var n=a.prototype;return n.loadWord=function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,s=new Uint8Array(4),o=Math.min(4,t);if(o===0)throw new Error("no bytes available");s.set(e.subarray(r,r+o)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=o*8,this.bytesAvailable-=o},n.skipBits=function(e){var t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},n.readBits=function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;if(e>32&&A.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?r<<t|this.readBits(t):r},n.skipLZ=function(){var 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()},n.skipUEG=function(){this.skipBits(1+this.skipLZ())},n.skipEG=function(){this.skipBits(1+this.skipLZ())},n.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},n.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},n.readBoolean=function(){return this.readBits(1)===1},n.readUByte=function(){return this.readBits(8)},n.readUShort=function(){return this.readBits(16)},n.readUInt=function(){return this.readBits(32)},n.skipScalingList=function(e){for(var t=8,r=8,s,o=0;o<e;o++)r!==0&&(s=this.readEG(),r=(t+s+256)%256),t=r===0?t:r},n.readSPS=function(){var e=0,t=0,r=0,s=0,o,l,u,d=this.readUByte.bind(this),f=this.readBits.bind(this),h=this.readUEG.bind(this),c=this.readBoolean.bind(this),v=this.skipBits.bind(this),m=this.skipEG.bind(this),g=this.skipUEG.bind(this),p=this.skipScalingList.bind(this);d();var y=d();if(f(5),v(3),d(),g(),y===100||y===110||y===122||y===244||y===44||y===83||y===86||y===118||y===128){var E=h();if(E===3&&v(1),g(),g(),v(1),c())for(l=E!==3?8:12,u=0;u<l;u++)c()&&(u<6?p(16):p(64))}g();var S=h();if(S===0)h();else if(S===1)for(v(1),m(),m(),o=h(),u=0;u<o;u++)m();g(),v(1);var L=h(),D=h(),R=f(1);R===0&&v(1),v(1),c()&&(e=h(),t=h(),r=h(),s=h());var T=[1,1];if(c()&&c()){var b=d();switch(b){case 1:T=[1,1];break;case 2:T=[12,11];break;case 3:T=[10,11];break;case 4:T=[16,11];break;case 5:T=[40,33];break;case 6:T=[24,11];break;case 7:T=[20,11];break;case 8:T=[32,11];break;case 9:T=[80,33];break;case 10:T=[18,11];break;case 11:T=[15,11];break;case 12:T=[64,33];break;case 13:T=[160,99];break;case 14:T=[4,3];break;case 15:T=[3,2];break;case 16:T=[2,1];break;case 255:{T=[d()<<8|d(),d()<<8|d()];break}}}return{width:Math.ceil((L+1)*16-e*2-t*2),height:(2-R)*(D+1)*16-(R?2:4)*(r+s),pixelRatio:T}},n.readSliceType=function(){return this.readUByte(),this.readUEG(),this.readUEG()},a}(),xs=function(a){Re(n,a);function n(){return a.apply(this,arguments)||this}var i=n.prototype;return i.parseAVCPES=function(t,r,s,o,l){var u=this,d=this.parseAVCNALu(t,s.data),f=this.VideoSample,h,c=!1;s.data=null,f&&d.length&&!t.audFound&&(this.pushAccessUnit(f,t),f=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"")),d.forEach(function(v){var m;switch(v.type){case 1:{var g=!1;h=!0;var p=v.data;if(c&&p.length>4){var y=new Si(p).readSliceType();(y===2||y===4||y===7||y===9)&&(g=!0)}if(g){var E;(E=f)!=null&&E.frame&&!f.key&&(u.pushAccessUnit(f,t),f=u.VideoSample=null)}f||(f=u.VideoSample=u.createVideoSample(!0,s.pts,s.dts,"")),f.frame=!0,f.key=g;break}case 5:h=!0,(m=f)!=null&&m.frame&&!f.key&&(u.pushAccessUnit(f,t),f=u.VideoSample=null),f||(f=u.VideoSample=u.createVideoSample(!0,s.pts,s.dts,"")),f.key=!0,f.frame=!0;break;case 6:{h=!0,Tr(v.data,1,s.pts,r.samples);break}case 7:{var S,L;h=!0,c=!0;var D=v.data,R=new Si(D),T=R.readSPS();if(!t.sps||t.width!==T.width||t.height!==T.height||((S=t.pixelRatio)==null?void 0:S[0])!==T.pixelRatio[0]||((L=t.pixelRatio)==null?void 0:L[1])!==T.pixelRatio[1]){t.width=T.width,t.height=T.height,t.pixelRatio=T.pixelRatio,t.sps=[D],t.duration=l;for(var b=D.subarray(1,4),I="avc1.",P=0;P<3;P++){var C=b[P].toString(16);C.length<2&&(C="0"+C),I+=C}t.codec=I}break}case 8:h=!0,t.pps=[v.data];break;case 9:h=!0,t.audFound=!0,f&&u.pushAccessUnit(f,t),f=u.VideoSample=u.createVideoSample(!1,s.pts,s.dts,"");break;case 12:h=!0;break;default:h=!1,f&&(f.debug+="unknown NAL "+v.type+" ");break}if(f&&h){var w=f.units;w.push(v)}}),o&&f&&(this.pushAccessUnit(f,t),this.VideoSample=null)},i.parseAVCNALu=function(t,r){var s=r.byteLength,o=t.naluState||0,l=o,u=[],d=0,f,h,c,v=-1,m=0;for(o===-1&&(v=0,m=r[0]&31,o=0,d=1);d<s;){if(f=r[d++],!o){o=f?0:1;continue}if(o===1){o=f?0:2;continue}if(!f)o=3;else if(f===1){if(h=d-o-1,v>=0){var g={data:r.subarray(v,h),type:m};u.push(g)}else{var p=this.getLastNalUnit(t.samples);p&&(l&&d<=4-l&&p.state&&(p.data=p.data.subarray(0,p.data.byteLength-l)),h>0&&(p.data=xe(p.data,r.subarray(0,h)),p.state=0))}d<s?(c=r[d]&31,v=d,m=c,o=0):o=-1}else o=0}if(v>=0&&o>=0){var y={data:r.subarray(v,s),type:m,state:o};u.push(y)}if(u.length===0){var E=this.getLastNalUnit(t.samples);E&&(E.data=xe(E.data,r))}return t.naluState=o,u},n}(Es),Ts=function(){function a(i,e,t){this.keyData=void 0,this.decrypter=void 0,this.keyData=t,this.decrypter=new Ut(e,{removePKCS7Padding:!1})}var n=a.prototype;return n.decryptBuffer=function(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)},n.decryptAacSample=function(e,t,r){var s=this,o=e[t].unit;if(!(o.length<=16)){var l=o.subarray(16,o.length-o.length%16),u=l.buffer.slice(l.byteOffset,l.byteOffset+l.length);this.decryptBuffer(u).then(function(d){var f=new Uint8Array(d);o.set(f,16),s.decrypter.isSync()||s.decryptAacSamples(e,t+1,r)})}},n.decryptAacSamples=function(e,t,r){for(;;t++){if(t>=e.length){r();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}},n.getAvcEncryptedData=function(e){for(var t=Math.floor((e.length-48)/160)*16+16,r=new Int8Array(t),s=0,o=32;o<e.length-16;o+=160,s+=16)r.set(e.subarray(o,o+16),s);return r},n.getAvcDecryptedUnit=function(e,t){for(var r=new Uint8Array(t),s=0,o=32;o<e.length-16;o+=160,s+=16)e.set(r.subarray(s,s+16),o);return e},n.decryptAvcSample=function(e,t,r,s,o){var l=this,u=Sr(o.data),d=this.getAvcEncryptedData(u);this.decryptBuffer(d.buffer).then(function(f){o.data=l.getAvcDecryptedUnit(u,f),l.decrypter.isSync()||l.decryptAvcSamples(e,t,r+1,s)})},n.decryptAvcSamples=function(e,t,r,s){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length){s();return}for(var o=e[t].units;!(r>=o.length);r++){var l=o[r];if(!(l.data.length<=48||l.type!==1&&l.type!==5)&&(this.decryptAvcSample(e,t,r,s,l),!this.decrypter.isSync()))return}}},a}(),oe=188,Ss=function(){function a(i,e,t){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=i,this.config=e,this.typeSupported=t,this.videoParser=new xs}a.probe=function(e){var t=a.syncOffset(e);return t>0&&A.warn("MPEG2-TS detected but first sync word found @ offset "+t),t!==-1},a.syncOffset=function(e){for(var t=e.length,r=Math.min(oe*5,t-oe)+1,s=0;s<r;){for(var o=!1,l=-1,u=0,d=s;d<t;d+=oe)if(e[d]===71&&(t-d===oe||e[d+oe]===71)){if(u++,l===-1&&(l=d,l!==0&&(r=Math.min(l+oe*99,e.length-oe)+1)),o||(o=Vt(e,d)===0),o&&u>1&&(l===0&&u>2||d+oe>r))return l}else{if(u)return-1;break}s++}return-1},a.createTrack=function(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:gr[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}};var n=a.prototype;return n.resetInitSegment=function(e,t,r,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=a.createTrack("video"),this._audioTrack=a.createTrack("audio",s),this._id3Track=a.createTrack("id3"),this._txtTrack=a.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=r,this._duration=s},n.resetTimeStamp=function(){},n.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null},n.demux=function(e,t,r,s){r===void 0&&(r=!1),s===void 0&&(s=!1),r||(this.sampleAes=null);var o,l=this._videoTrack,u=this._audioTrack,d=this._id3Track,f=this._txtTrack,h=l.pid,c=l.pesData,v=u.pid,m=d.pid,g=u.pesData,p=d.pesData,y=null,E=this.pmtParsed,S=this._pmtId,L=e.length;if(this.remainderData&&(e=xe(this.remainderData,e),L=e.length,this.remainderData=null),L<oe&&!s)return this.remainderData=e,{audioTrack:u,videoTrack:l,id3Track:d,textTrack:f};var D=Math.max(0,a.syncOffset(e));L-=(L-D)%oe,L<e.byteLength&&!s&&(this.remainderData=new Uint8Array(e.buffer,L,e.buffer.byteLength-L));for(var R=0,T=D;T<L;T+=oe)if(e[T]===71){var b=!!(e[T+1]&64),I=Vt(e,T),P=(e[T+3]&48)>>4,C=void 0;if(P>1){if(C=T+5+e[T+4],C===T+oe)continue}else C=T+4;switch(I){case h:b&&(c&&(o=Ve(c))&&this.videoParser.parseAVCPES(l,f,o,!1,this._duration),c={data:[],size:0}),c&&(c.data.push(e.subarray(C,T+oe)),c.size+=T+oe-C);break;case v:if(b){if(g&&(o=Ve(g)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,o);break;case"mp3":this.parseMPEGPES(u,o);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(C,T+oe)),g.size+=T+oe-C);break;case m:b&&(p&&(o=Ve(p))&&this.parseID3PES(d,o),p={data:[],size:0}),p&&(p.data.push(e.subarray(C,T+oe)),p.size+=T+oe-C);break;case 0:b&&(C+=e[C]+1),S=this._pmtId=Ls(e,C);break;case S:{b&&(C+=e[C]+1);var w=As(e,C,this.typeSupported,r);h=w.videoPid,h>0&&(l.pid=h,l.segmentCodec=w.segmentVideoCodec),v=w.audioPid,v>0&&(u.pid=v,u.segmentCodec=w.segmentAudioCodec),m=w.id3Pid,m>0&&(d.pid=m),y!==null&&!E&&(A.warn("MPEG-TS PMT found at "+T+" after unknown PID '"+y+"'. Backtracking to sync byte @"+D+" to parse all TS packets."),y=null,T=D-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=I;break}}else R++;if(R>0){var M=new Error("Found "+R+" TS packet/s that do not start with 0x47");this.observer.emit(x.ERROR,x.ERROR,{type:V.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:M,reason:M.message})}l.pesData=c,u.pesData=g,d.pesData=p;var F={audioTrack:u,videoTrack:l,id3Track:d,textTrack:f};return s&&this.extractRemainingSamples(F),F},n.flush=function(){var e=this.remainderData;this.remainderData=null;var t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t},n.extractRemainingSamples=function(e){var t=e.audioTrack,r=e.videoTrack,s=e.id3Track,o=e.textTrack,l=r.pesData,u=t.pesData,d=s.pesData,f;if(l&&(f=Ve(l))?(this.videoParser.parseAVCPES(r,o,f,!0,this._duration),r.pesData=null):r.pesData=l,u&&(f=Ve(u))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,f);break;case"mp3":this.parseMPEGPES(t,f);break}t.pesData=null}else u!=null&&u.size&&A.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=u;d&&(f=Ve(d))?(this.parseID3PES(s,f),s.pesData=null):s.pesData=d},n.demuxSampleAes=function(e,t,r){var s=this.demux(e,r,!0,!this.config.progressive),o=this.sampleAes=new Ts(this.observer,this.config,t);return this.decrypt(s,o)},n.decrypt=function(e,t){return new Promise(function(r){var s=e.audioTrack,o=e.videoTrack;s.samples&&s.segmentCodec==="aac"?t.decryptAacSamples(s.samples,0,function(){o.samples?t.decryptAvcSamples(o.samples,0,0,function(){r(e)}):r(e)}):o.samples&&t.decryptAvcSamples(o.samples,0,0,function(){r(e)})})},n.destroy=function(){this._duration=0},n.parseAACPES=function(e,t){var r=0,s=this.aacOverFlow,o=t.data;if(s){this.aacOverFlow=null;var l=s.missing,u=s.sample.unit.byteLength;if(l===-1)o=xe(s.sample.unit,o);else{var d=u-l;s.sample.unit.set(o.subarray(0,l),d),e.samples.push(s.sample),r=s.missing}}var f,h;for(f=r,h=o.length;f<h-1&&!ht(o,f);f++);if(f!==r){var c,v=f<h-1;v?c="AAC PES did not start with ADTS header,offset:"+f:c="No ADTS header found in AAC PES";var m=new Error(c);if(A.warn("parsing error: "+c),this.observer.emit(x.ERROR,x.ERROR,{type:V.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,levelRetry:v,error:m,reason:c}),!v)return}gi(e,this.observer,o,f,this.audioCodec);var g;if(t.pts!==void 0)g=t.pts;else if(s){var p=mi(e.samplerate);g=s.sample.pts+p}else{A.warn("[tsdemuxer]: AAC PES unknown PTS");return}for(var y=0,E;f<h;)if(E=pi(e,o,f,g,y),f+=E.length,E.missing){this.aacOverFlow=E;break}else for(y++;f<h-1&&!ht(o,f);f++);},n.parseMPEGPES=function(e,t){var r=t.data,s=r.length,o=0,l=0,u=t.pts;if(u===void 0){A.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;l<s;)if(xi(r,l)){var d=yi(e,r,l,u,o);if(d)l+=d.length,o++;else break}else l++},n.parseAC3PES=function(e,t){},n.parseID3PES=function(e,t){if(t.pts===void 0){A.warn("[tsdemuxer]: ID3 PES unknown PTS");return}var r=ye({},t,{type:this._videoTrack?Te.emsg:Te.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)},a}();function Vt(a,n){return((a[n+1]&31)<<8)+a[n+2]}function Ls(a,n){return(a[n+10]&31)<<8|a[n+11]}function As(a,n,i,e){var t={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},r=(a[n+1]&15)<<8|a[n+2],s=n+3+r-4,o=(a[n+10]&15)<<8|a[n+11];for(n+=12+o;n<s;){var l=Vt(a,n),u=(a[n+3]&15)<<8|a[n+4];switch(a[n]){case 207:if(!e){Kt("ADTS AAC");break}case 15:t.audioPid===-1&&(t.audioPid=l);break;case 21:t.id3Pid===-1&&(t.id3Pid=l);break;case 219:if(!e){Kt("H.264");break}case 27:t.videoPid===-1&&(t.videoPid=l,t.segmentVideoCodec="avc");break;case 3:case 4:!i.mpeg&&!i.mp3?A.log("MPEG audio found, not supported in this browser"):t.audioPid===-1&&(t.audioPid=l,t.segmentAudioCodec="mp3");break;case 193:if(!e){Kt("AC-3");break}case 129:A.warn("AC-3 in M2TS support not included in build");break;case 6:if(t.audioPid===-1&&u>0)for(var d=n+5,f=u;f>2;){var h=a[d];switch(h){case 106:A.warn("AC-3 in M2TS support not included in build");break}var c=a[d+1]+2;d+=c,f-=c}break;case 194:case 135:A.warn("Unsupported EC-3 in M2TS found");break;case 36:A.warn("Unsupported HEVC in M2TS found");break}n+=u+5}return t}function Kt(a){A.log(a+" with AES-128-CBC encryption found in unencrypted stream")}function Ve(a){var n=0,i,e,t,r,s,o=a.data;if(!a||a.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=xe(o[0],o[1]),o.splice(1,1);i=o[0];var l=(i[0]<<16)+(i[1]<<8)+i[2];if(l===1){if(e=(i[4]<<8)+i[5],e&&e>a.size-6)return null;var u=i[7];u&192&&(r=(i[9]&14)*536870912+(i[10]&255)*4194304+(i[11]&254)*16384+(i[12]&255)*128+(i[13]&254)/2,u&64?(s=(i[14]&14)*536870912+(i[15]&255)*4194304+(i[16]&254)*16384+(i[17]&255)*128+(i[18]&254)/2,r-s>60*9e4&&(A.warn(Math.round((r-s)/9e4)+"s delta between PTS and DTS, align them"),r=s)):s=r),t=i[8];var d=t+9;if(a.size<=d)return null;a.size-=d;for(var f=new Uint8Array(a.size),h=0,c=o.length;h<c;h++){i=o[h];var v=i.byteLength;if(d)if(d>v){d-=v;continue}else i=i.subarray(d),v-=d,d=0;f.set(i,n),n+=v}return e&&(e-=t+3),{data:f,pts:r,dts:s,len:e}}return null}var Rs=function(a){Re(n,a);function n(){return a.apply(this,arguments)||this}var i=n.prototype;return i.resetInitSegment=function(t,r,s,o){a.prototype.resetInitSegment.call(this,t,r,s,o),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:o,inputTimeScale:9e4,dropped:0}},n.probe=function(t){if(!t)return!1;var r=Qe(t,0),s=r?.length||0;if(r&&t[s]===11&&t[s+1]===119&&dr(r)!==void 0&&ys(t,s)<=16)return!1;for(var o=t.length;s<o;s++)if(Ti(t,s))return A.log("MPEG Audio sync word found !"),!0;return!1},i.canParse=function(t,r){return vs(t,r)},i.appendFrame=function(t,r,s){if(this.basePTS!==null)return yi(t,r,s,this.basePTS,this.frameIndex)},n}(hi),Li=function(){function a(){}return a.getSilentFrame=function(i,e){switch(i){case"mp4a.40.2":if(e===1)return new Uint8Array([0,200,0,128,35,128]);if(e===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(e===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(e===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(e===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(e===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(e===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(e===2)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(e===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}},a}(),ke=Math.pow(2,32)-1,fe=function(){function a(){}return a.init=function(){a.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:[]};var i;for(i in a.types)a.types.hasOwnProperty(i)&&(a.types[i]=[i.charCodeAt(0),i.charCodeAt(1),i.charCodeAt(2),i.charCodeAt(3)]);var e=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),t=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]);a.HDLR_TYPES={video:e,audio:t};var r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),s=new Uint8Array([0,0,0,0,0,0,0,0]);a.STTS=a.STSC=a.STCO=s,a.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),a.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),a.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),a.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);var o=new Uint8Array([105,115,111,109]),l=new Uint8Array([97,118,99,49]),u=new Uint8Array([0,0,0,1]);a.FTYP=a.box(a.types.ftyp,o,u,o,l),a.DINF=a.box(a.types.dinf,a.box(a.types.dref,r))},a.box=function(i){for(var e=8,t=arguments.length,r=new Array(t>1?t-1:0),s=1;s<t;s++)r[s-1]=arguments[s];for(var o=r.length,l=o;o--;)e+=r[o].byteLength;var u=new Uint8Array(e);for(u[0]=e>>24&255,u[1]=e>>16&255,u[2]=e>>8&255,u[3]=e&255,u.set(i,4),o=0,e=8;o<l;o++)u.set(r[o],e),e+=r[o].byteLength;return u},a.hdlr=function(i){return a.box(a.types.hdlr,a.HDLR_TYPES[i])},a.mdat=function(i){return a.box(a.types.mdat,i)},a.mdhd=function(i,e){e*=i;var t=Math.floor(e/(ke+1)),r=Math.floor(e%(ke+1));return a.box(a.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,i&255,t>>24,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,85,196,0,0]))},a.mdia=function(i){return a.box(a.types.mdia,a.mdhd(i.timescale,i.duration),a.hdlr(i.type),a.minf(i))},a.mfhd=function(i){return a.box(a.types.mfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255]))},a.minf=function(i){return i.type==="audio"?a.box(a.types.minf,a.box(a.types.smhd,a.SMHD),a.DINF,a.stbl(i)):a.box(a.types.minf,a.box(a.types.vmhd,a.VMHD),a.DINF,a.stbl(i))},a.moof=function(i,e,t){return a.box(a.types.moof,a.mfhd(i),a.traf(t,e))},a.moov=function(i){for(var e=i.length,t=[];e--;)t[e]=a.trak(i[e]);return a.box.apply(null,[a.types.moov,a.mvhd(i[0].timescale,i[0].duration)].concat(t).concat(a.mvex(i)))},a.mvex=function(i){for(var e=i.length,t=[];e--;)t[e]=a.trex(i[e]);return a.box.apply(null,[a.types.mvex].concat(t))},a.mvhd=function(i,e){e*=i;var t=Math.floor(e/(ke+1)),r=Math.floor(e%(ke+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,i>>24&255,i>>16&255,i>>8&255,i&255,t>>24,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return a.box(a.types.mvhd,s)},a.sdtp=function(i){var e=i.samples||[],t=new Uint8Array(4+e.length),r,s;for(r=0;r<e.length;r++)s=e[r].flags,t[r+4]=s.dependsOn<<4|s.isDependedOn<<2|s.hasRedundancy;return a.box(a.types.sdtp,t)},a.stbl=function(i){return a.box(a.types.stbl,a.stsd(i),a.box(a.types.stts,a.STTS),a.box(a.types.stsc,a.STSC),a.box(a.types.stsz,a.STSZ),a.box(a.types.stco,a.STCO))},a.avc1=function(i){var e=[],t=[],r,s,o;for(r=0;r<i.sps.length;r++)s=i.sps[r],o=s.byteLength,e.push(o>>>8&255),e.push(o&255),e=e.concat(Array.prototype.slice.call(s));for(r=0;r<i.pps.length;r++)s=i.pps[r],o=s.byteLength,t.push(o>>>8&255),t.push(o&255),t=t.concat(Array.prototype.slice.call(s));var l=a.box(a.types.avcC,new Uint8Array([1,e[3],e[4],e[5],255,224|i.sps.length].concat(e).concat([i.pps.length]).concat(t))),u=i.width,d=i.height,f=i.pixelRatio[0],h=i.pixelRatio[1];return a.box(a.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,u>>8&255,u&255,d>>8&255,d&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,a.box(a.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),a.box(a.types.pasp,new Uint8Array([f>>24,f>>16&255,f>>8&255,f&255,h>>24,h>>16&255,h>>8&255,h&255])))},a.esds=function(i){var e=i.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(i.config).concat([6,1,2]))},a.audioStsd=function(i){var e=i.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,i.channelCount,0,16,0,0,0,0,e>>8&255,e&255,0,0])},a.mp4a=function(i){return a.box(a.types.mp4a,a.audioStsd(i),a.box(a.types.esds,a.esds(i)))},a.mp3=function(i){return a.box(a.types[".mp3"],a.audioStsd(i))},a.ac3=function(i){return a.box(a.types["ac-3"],a.audioStsd(i),a.box(a.types.dac3,i.config))},a.stsd=function(i){return i.type==="audio"?i.segmentCodec==="mp3"&&i.codec==="mp3"?a.box(a.types.stsd,a.STSD,a.mp3(i)):i.segmentCodec==="ac3"?a.box(a.types.stsd,a.STSD,a.ac3(i)):a.box(a.types.stsd,a.STSD,a.mp4a(i)):a.box(a.types.stsd,a.STSD,a.avc1(i))},a.tkhd=function(i){var e=i.id,t=i.duration*i.timescale,r=i.width,s=i.height,o=Math.floor(t/(ke+1)),l=Math.floor(t%(ke+1));return a.box(a.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,l>>24,l>>16&255,l>>8&255,l&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,r&255,0,0,s>>8&255,s&255,0,0]))},a.traf=function(i,e){var t=a.sdtp(i),r=i.id,s=Math.floor(e/(ke+1)),o=Math.floor(e%(ke+1));return a.box(a.types.traf,a.box(a.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255])),a.box(a.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,s&255,o>>24,o>>16&255,o>>8&255,o&255])),a.trun(i,t.length+16+20+8+16+8+8),t)},a.trak=function(i){return i.duration=i.duration||4294967295,a.box(a.types.trak,a.tkhd(i),a.mdia(i))},a.trex=function(i){var e=i.id;return a.box(a.types.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},a.trun=function(i,e){var t=i.samples||[],r=t.length,s=12+16*r,o=new Uint8Array(s),l,u,d,f,h,c;for(e+=8+s,o.set([i.type==="video"?1:0,0,15,1,r>>>24&255,r>>>16&255,r>>>8&255,r&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255],0),l=0;l<r;l++)u=t[l],d=u.duration,f=u.size,h=u.flags,c=u.cts,o.set([d>>>24&255,d>>>16&255,d>>>8&255,d&255,f>>>24&255,f>>>16&255,f>>>8&255,f&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,c>>>24&255,c>>>16&255,c>>>8&255,c&255],12+16*l);return a.box(a.types.trun,o)},a.initSegment=function(i){a.types||a.init();var e=a.moov(i),t=xe(a.FTYP,e);return t},a}();fe.types=void 0,fe.HDLR_TYPES=void 0,fe.STTS=void 0,fe.STSC=void 0,fe.STCO=void 0,fe.STSZ=void 0,fe.VMHD=void 0,fe.SMHD=void 0,fe.STSD=void 0,fe.FTYP=void 0,fe.DINF=void 0;var bs=9e4;function Is(a,n,i,e){i===void 0&&(i=1),e===void 0&&(e=!1);var t=a*n*i;return e?Math.round(t):t}function je(a,n){return n===void 0&&(n=!1),Is(a,1e3,1/bs,n)}var _s=10*1e3,Ai=1024,Ds=1152,Cs=1536,Ke=null,Wt=null,Yt=function(){function a(i,e,t,r){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=i,this.config=e,this.typeSupported=t,this.ISGenerated=!1,Ke===null){var s=navigator.userAgent||"",o=s.match(/Chrome\/(\d+)/i);Ke=o?parseInt(o[1]):0}if(Wt===null){var l=navigator.userAgent.match(/Safari\/(\d+)/i);Wt=l?parseInt(l[1]):0}}var n=a.prototype;return n.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},n.resetTimeStamp=function(e){A.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e},n.resetNextTimestamp=function(){A.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},n.resetInitSegment=function(){A.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},n.getVideoStartPts=function(e){var t=!1,r=e.reduce(function(s,o){var l=o.pts-s;return l<-4294967296?(t=!0,Le(s,o.pts)):l>0?s:o.pts},e[0].pts);return t&&A.debug("PTS rollover detected"),r},n.remux=function(e,t,r,s,o,l,u,d){var f,h,c,v,m,g,p=o,y=o,E=e.pid>-1,S=t.pid>-1,L=t.samples.length,D=e.samples.length>0,R=u&&L>0||L>1,T=(!E||D)&&(!S||R)||this.ISGenerated||u;if(T){if(this.ISGenerated){var b,I,P,C,w=this.videoTrackConfig;w&&(t.width!==w.width||t.height!==w.height||((b=t.pixelRatio)==null?void 0:b[0])!==((I=w.pixelRatio)==null?void 0:I[0])||((P=t.pixelRatio)==null?void 0:P[1])!==((C=w.pixelRatio)==null?void 0:C[1]))&&this.resetInitSegment()}else c=this.generateIS(e,t,o,l);var M=this.isVideoContiguous,F=-1,H;if(R&&(F=Ps(t.samples),!M&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,F>0){A.warn("[mp4-remuxer]: Dropped "+F+" out of "+L+" video samples due to a missing keyframe");var U=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(F),t.dropped+=F,y+=(t.samples[0].pts-U)/t.inputTimeScale,H=y}else F===-1&&(A.warn("[mp4-remuxer]: No keyframe found out of "+L+" video samples"),g=!1);if(this.ISGenerated){if(D&&R){var W=this.getVideoStartPts(t.samples),K=Le(e.samples[0].pts,W)-W,B=K/t.inputTimeScale;p+=Math.max(0,B),y+=Math.max(0,-B)}if(D){if(e.samplerate||(A.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),c=this.generateIS(e,t,o,l)),h=this.remuxAudio(e,p,this.isAudioContiguous,l,S||R||d===j.AUDIO?y:void 0),R){var Q=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(A.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),c=this.generateIS(e,t,o,l)),f=this.remuxVideo(t,y,M,Q)}}else R&&(f=this.remuxVideo(t,y,M,0));f&&(f.firstKeyFrame=F,f.independent=F!==-1,f.firstKeyFramePTS=H)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(m=Ri(r,o,this._initPTS,this._initDTS)),s.samples.length&&(v=bi(s,o,this._initPTS))),{audio:h,video:f,initSegment:c,independent:g,text:v,id3:m}},n.generateIS=function(e,t,r,s){var o=e.samples,l=t.samples,u=this.typeSupported,d={},f=this._initPTS,h=!f||s,c="audio/mp4",v,m,g;if(h&&(v=m=1/0),e.config&&o.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":u.mpeg?(c="audio/mpeg",e.codec=""):u.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}d.audio={id:"audio",container:c,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&u.mpeg?new Uint8Array(0):fe.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(g=e.inputTimeScale,!f||g!==f.timescale?v=m=o[0].pts-Math.round(g*r):h=!1)}if(t.sps&&t.pps&&l.length){if(t.timescale=t.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:fe.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(g=t.inputTimeScale,!f||g!==f.timescale){var p=this.getVideoStartPts(l),y=Math.round(g*r);m=Math.min(m,Le(l[0].dts,p)-y),v=Math.min(v,p-y)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(d).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:v,timescale:g},this._initDTS={baseTime:m,timescale:g}):v=g=void 0,{tracks:d,initPTS:v,timescale:g}},n.remuxVideo=function(e,t,r,s){var o=e.inputTimeScale,l=e.samples,u=[],d=l.length,f=this._initPTS,h=this.nextAvcDts,c=8,v=this.videoSampleDuration,m,g,p=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,E=!1;if(!r||h===null){var S=t*o,L=l[0].pts-Le(l[0].dts,l[0].pts);Ke&&h!==null&&Math.abs(S-L-h)<15e3?r=!0:h=S-L}for(var D=f.baseTime*o/f.timescale,R=0;R<d;R++){var T=l[R];T.pts=Le(T.pts-D,h),T.dts=Le(T.dts-D,h),T.dts<l[R>0?R-1:R].dts&&(E=!0)}E&&l.sort(function(pt,Ui){var no=pt.dts-Ui.dts,ao=pt.pts-Ui.pts;return no||ao}),m=l[0].dts,g=l[l.length-1].dts;var b=g-m,I=b?Math.round(b/(d-1)):v||e.inputTimeScale/30;if(r){var P=m-h,C=P>I,w=P<-1;if((C||w)&&(C?A.warn("AVC: "+je(P,!0)+" ms ("+P+"dts) hole between fragments detected at "+t.toFixed(3)):A.warn("AVC: "+je(-P,!0)+" ms ("+P+"dts) overlapping between fragments detected at "+t.toFixed(3)),!w||h>=l[0].pts||Ke)){m=h;var M=l[0].pts-P;if(C)l[0].dts=m,l[0].pts=M;else for(var F=0;F<l.length&&!(l[F].dts>M);F++)l[F].dts-=P,l[F].pts-=P;A.log("Video: Initial PTS/DTS adjusted: "+je(M,!0)+"/"+je(m,!0)+", delta: "+je(P,!0)+" ms")}}m=Math.max(0,m);for(var H=0,U=0,W=m,K=0;K<d;K++){for(var B=l[K],Q=B.units,q=Q.length,J=0,ee=0;ee<q;ee++)J+=Q[ee].data.length;U+=J,H+=q,B.length=J,B.dts<W?(B.dts=W,W+=I/4|0||1):W=B.dts,p=Math.min(B.pts,p),y=Math.max(B.pts,y)}g=l[d-1].dts;var re=U+4*H+8,Z;try{Z=new Uint8Array(re)}catch(pt){this.observer.emit(x.ERROR,x.ERROR,{type:V.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:pt,bytes:re,reason:"fail allocating video mdat "+re});return}var X=new DataView(Z.buffer);X.setUint32(0,re),Z.set(fe.types.mdat,4);for(var Pe=!1,Ee=Number.POSITIVE_INFINITY,te=Number.POSITIVE_INFINITY,ce=Number.NEGATIVE_INFINITY,ve=Number.NEGATIVE_INFINITY,ie=0;ie<d;ie++){for(var z=l[ie],pe=z.units,de=0,le=0,Ue=pe.length;le<Ue;le++){var Fi=pe[le],$s=Fi.data,Qt=Fi.data.byteLength;X.setUint32(c,Qt),c+=4,Z.set($s,c),c+=Qt,de+=4+Qt}var gt=void 0;if(ie<d-1)v=l[ie+1].dts-z.dts,gt=l[ie+1].pts-z.pts;else{var Oi=this.config,mt=ie>0?z.dts-l[ie-1].dts:I;if(gt=ie>0?z.pts-l[ie-1].pts:I,Oi.stretchShortVideoTrack&&this.nextAudioPts!==null){var Qs=Math.floor(Oi.maxBufferHole*o),Zt=(s?p+s*o:this.nextAudioPts)-z.pts;Zt>Qs?(v=Zt-mt,v<0?v=mt:Pe=!0,A.log("[mp4-remuxer]: It is approximately "+Zt/90+" ms to the next segment; using duration "+v/90+" ms for the last video frame.")):v=mt}else v=mt}var Zs=Math.round(z.pts-z.dts);Ee=Math.min(Ee,v),ce=Math.max(ce,v),te=Math.min(te,gt),ve=Math.max(ve,gt),u.push(new Ii(z.key,v,de,Zs))}if(u.length){if(Ke){if(Ke<70){var Mi=u[0].flags;Mi.dependsOn=2,Mi.isNonSync=0}}else if(Wt&&ve-te<ce-Ee&&I/ce<.025&&u[0].cts===0){A.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");for(var Jt=m,Ae=0,Ni=u.length;Ae<Ni;Ae++){var Bi=Jt+u[Ae].duration,Js=Jt+u[Ae].cts;if(Ae<Ni-1){var eo=Bi+u[Ae+1].cts;u[Ae].duration=eo-Js}else u[Ae].duration=Ae?u[Ae-1].duration:I;u[Ae].cts=0,Jt=Bi}}}v=Pe||!v?I:v,this.nextAvcDts=h=g+v,this.videoSampleDuration=v,this.isVideoContiguous=!0;var to=fe.moof(e.sequenceNumber++,m,ye({},e,{samples:u})),ro="video",io={data1:to,data2:Z,startPTS:p/o,endPTS:(y+v)/o,startDTS:m/o,endDTS:h/o,type:ro,hasAudio:!1,hasVideo:!0,nb:u.length,dropped:e.dropped};return e.samples=[],e.dropped=0,io},n.getSamplesPerFrame=function(e){switch(e.segmentCodec){case"mp3":return Ds;case"ac3":return Cs;default:return Ai}},n.remuxAudio=function(e,t,r,s,o){var l=e.inputTimeScale,u=e.samplerate?e.samplerate:l,d=l/u,f=this.getSamplesPerFrame(e),h=f*d,c=this._initPTS,v=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,m=[],g=o!==void 0,p=e.samples,y=v?0:8,E=this.nextAudioPts||-1,S=t*l,L=c.baseTime*l/c.timescale;if(this.isAudioContiguous=r=r||p.length&&E>0&&(s&&Math.abs(S-E)<9e3||Math.abs(Le(p[0].pts-L,S)-E)<20*h),p.forEach(function(le){le.pts=Le(le.pts-L,S)}),!r||E<0){if(p=p.filter(function(le){return le.pts>=0}),!p.length)return;o===0?E=0:s&&!g?E=Math.max(0,S):E=p[0].pts}if(e.segmentCodec==="aac")for(var D=this.config.maxAudioFramesDrift,R=0,T=E;R<p.length;R++){var b=p[R],I=b.pts,P=I-T,C=Math.abs(1e3*P/l);if(P<=-D*h&&g)R===0&&(A.warn("Audio frame @ "+(I/l).toFixed(3)+"s overlaps nextAudioPts by "+Math.round(1e3*P/l)+" ms."),this.nextAudioPts=E=T=I);else if(P>=D*h&&C<_s&&g){var w=Math.round(P/h);T=I-w*h,T<0&&(w--,T+=h),R===0&&(this.nextAudioPts=E=T),A.warn("[mp4-remuxer]: Injecting "+w+" audio frame @ "+(T/l).toFixed(3)+"s due to "+Math.round(1e3*P/l)+" ms gap.");for(var M=0;M<w;M++){var F=Math.max(T,0),H=Li.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);H||(A.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),H=b.unit.subarray()),p.splice(R,0,{unit:H,pts:F}),T+=h,R++}}b.pts=T,T+=h}for(var U=null,W=null,K,B=0,Q=p.length;Q--;)B+=p[Q].unit.byteLength;for(var q=0,J=p.length;q<J;q++){var ee=p[q],re=ee.unit,Z=ee.pts;if(W!==null){var X=m[q-1];X.duration=Math.round((Z-W)/d)}else if(r&&e.segmentCodec==="aac"&&(Z=E),U=Z,B>0){B+=y;try{K=new Uint8Array(B)}catch(le){this.observer.emit(x.ERROR,x.ERROR,{type:V.MUX_ERROR,details:_.REMUX_ALLOC_ERROR,fatal:!1,error:le,bytes:B,reason:"fail allocating audio mdat "+B});return}if(!v){var Pe=new DataView(K.buffer);Pe.setUint32(0,B),K.set(fe.types.mdat,4)}}else return;K.set(re,y);var Ee=re.byteLength;y+=Ee,m.push(new Ii(!0,f,Ee,0)),W=Z}var te=m.length;if(te){var ce=m[m.length-1];this.nextAudioPts=E=W+d*ce.duration;var ve=v?new Uint8Array(0):fe.moof(e.sequenceNumber++,U/d,ye({},e,{samples:m}));e.samples=[];var ie=U/l,z=E/l,pe="audio",de={data1:ve,data2:K,startPTS:ie,endPTS:z,startDTS:ie,endDTS:z,type:pe,hasAudio:!0,hasVideo:!1,nb:te};return this.isAudioContiguous=!0,de}},n.remuxEmptyAudio=function(e,t,r,s){var o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,u=o/l,d=this.nextAudioPts,f=this._initDTS,h=f.baseTime*9e4/f.timescale,c=(d!==null?d:s.startDTS*o)+h,v=s.endDTS*o+h,m=u*Ai,g=Math.ceil((v-c)/m),p=Li.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(A.warn("[mp4-remuxer]: remux empty Audio"),!p){A.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}for(var y=[],E=0;E<g;E++){var S=c+E*m;y.push({unit:p,pts:S,dts:S})}return e.samples=y,this.remuxAudio(e,t,r,!1)},a}();function Le(a,n){var i;if(n===null)return a;for(n<a?i=-8589934592:i=8589934592;Math.abs(a-n)>4294967296;)a+=i;return a}function Ps(a){for(var n=0;n<a.length;n++)if(a[n].key)return n;return-1}function Ri(a,n,i,e){var t=a.samples.length;if(t){for(var r=a.inputTimeScale,s=0;s<t;s++){var o=a.samples[s];o.pts=Le(o.pts-i.baseTime*r/i.timescale,n*r)/r,o.dts=Le(o.dts-e.baseTime*r/e.timescale,n*r)/r}var l=a.samples;return a.samples=[],{samples:l}}}function bi(a,n,i){var e=a.samples.length;if(e){for(var t=a.inputTimeScale,r=0;r<e;r++){var s=a.samples[r];s.pts=Le(s.pts-i.baseTime*t/i.timescale,n*t)/t}a.samples.sort(function(l,u){return l.pts-u.pts});var o=a.samples;return a.samples=[],{samples:o}}}var Ii=function(n,i,e,t){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=i,this.size=e,this.cts=t,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:n?2:1,isNonSync:n?0:1}},ws=function(){function a(){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}var n=a.prototype;return n.destroy=function(){},n.resetTimeStamp=function(e){this.initPTS=e,this.lastEndTime=null},n.resetNextTimestamp=function(){this.lastEndTime=null},n.resetInitSegment=function(e,t,r,s){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(yn(e,s)),this.emitInitSegment=!0},n.generateInitSegment=function(e){var t=this.audioCodec,r=this.videoCodec;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}var s=this.initData=Er(e);s.audio&&(t=_i(s.audio,$.AUDIO)),s.video&&(r=_i(s.video,$.VIDEO));var o={};s.audio&&s.video?o.audiovideo={container:"video/mp4",codec:t+","+r,initSegment:e,id:"main"}:s.audio?o.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:s.video?o.video={container:"video/mp4",codec:r,initSegment:e,id:"main"}:A.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=o},n.remux=function(e,t,r,s,o,l){var u,d,f=this.initPTS,h=this.lastEndTime,c={audio:void 0,video:void 0,text:s,id3:r,initSegment:void 0};O(h)||(h=this.lastEndTime=o||0);var v=t.samples;if(!(v!=null&&v.length))return c;var m={initPTS:void 0,timescale:1},g=this.initData;if((u=g)!=null&&u.length||(this.generateInitSegment(v),g=this.initData),!((d=g)!=null&&d.length))return A.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),c;this.emitInitSegment&&(m.tracks=this.initTracks,this.emitInitSegment=!1);var p=Tn(v,g),y=xn(g,v),E=y===null?o:y;(ks(f,E,o,p)||m.timescale!==f.timescale&&l)&&(m.initPTS=E-o,f&&f.timescale===1&&A.warn("Adjusting initPTS by "+(m.initPTS-f.baseTime)),this.initPTS=f={baseTime:m.initPTS,timescale:1});var S=e?E-f.baseTime/f.timescale:h,L=S+p;Ln(g,v,f.baseTime/f.timescale),p>0?this.lastEndTime=L:(A.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var D=!!g.audio,R=!!g.video,T="";D&&(T+="audio"),R&&(T+="video");var b={data1:v,startPTS:S,startDTS:S,endPTS:L,endDTS:L,type:T,hasAudio:D,hasVideo:R,nb:1,dropped:0};return c.audio=b.type==="audio"?b:void 0,c.video=b.type!=="audio"?b:void 0,c.initSegment=m,c.id3=Ri(r,o,f,f),s.samples.length&&(c.text=bi(s,o,f)),c},a}();function ks(a,n,i,e){if(a===null)return!0;var t=Math.max(e,1),r=n-a.baseTime/a.timescale;return Math.abs(r-i)>t}function _i(a,n){var i=a?.codec;if(i&&i.length>4)return i;if(n===$.AUDIO){if(i==="ec-3"||i==="ac-3"||i==="alac")return i;if(i==="fLaC"||i==="Opus"){var e=!1;return it(i,e)}var t="mp4a.40.5";return A.info('Parsed audio codec "'+i+'" or audio object type not handled. Using "'+t+'"'),t}return A.warn('Unhandled video codec "'+i+'"'),i==="hvc1"||i==="hev1"?"hvc1.1.6.L120.90":i==="av01"?"av01.0.04M.08":"avc1.42e01e"}var Di=typeof self<"u"?self:void 0,Ce;try{Ce=self.performance.now.bind(self.performance)}catch{A.debug("Unable to use Performance API on this environment"),Ce=Di?.Date.now}var qt=[{demux:ps,remux:ws},{demux:Ss,remux:Yt},{demux:gs,remux:Yt},{demux:Rs,remux:Yt}],jt=function(){function a(i,e,t,r,s){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=i,this.typeSupported=e,this.config=t,this.vendor=r,this.id=s}var n=a.prototype;return n.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},n.push=function(e,t,r,s){var o=this,l=r.transmuxing;l.executeStart=Ce();var u=new Uint8Array(e),d=this.currentTransmuxState,f=this.transmuxConfig;s&&(this.currentTransmuxState=s);var h=s||d,c=h.contiguous,v=h.discontinuity,m=h.trackSwitch,g=h.accurateTimeOffset,p=h.timeOffset,y=h.initSegmentChange,E=f.audioCodec,S=f.videoCodec,L=f.defaultInitPts,D=f.duration,R=f.initSegmentData,T=Fs(u,t);if(T&&T.method==="AES-128"){var b=this.getDecrypter();if(b.isSync()){var I=b.softwareDecrypt(u,T.key.buffer,T.iv.buffer),P=r.part>-1;if(P&&(I=b.flush()),!I)return l.executeEnd=Ce(),Xt(r);u=new Uint8Array(I)}else return this.decryptionPromise=b.webCryptoDecrypt(u,T.key.buffer,T.iv.buffer).then(function(H){var U=o.push(H,null,r);return o.decryptionPromise=null,U}),this.decryptionPromise}var C=this.needsProbing(v,m);if(C){var w=this.configureTransmuxer(u);if(w)return A.warn("[transmuxer] "+w.message),this.observer.emit(x.ERROR,x.ERROR,{type:V.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,fatal:!1,error:w,reason:w.message}),l.executeEnd=Ce(),Xt(r)}(v||m||y||C)&&this.resetInitSegment(R,E,S,D,t),(v||y||C)&&this.resetInitialTimestamp(L),c||this.resetContiguity();var M=this.transmux(u,T,p,g,r),F=this.currentTransmuxState;return F.contiguous=!0,F.discontinuity=!1,F.trackSwitch=!1,l.executeEnd=Ce(),M},n.flush=function(e){var t=this,r=e.transmuxing;r.executeStart=Ce();var s=this.decrypter,o=this.currentTransmuxState,l=this.decryptionPromise;if(l)return l.then(function(){return t.flush(e)});var u=[],d=o.timeOffset;if(s){var f=s.flush();f&&u.push(this.push(f,null,e))}var h=this.demuxer,c=this.remuxer;if(!h||!c)return r.executeEnd=Ce(),[Xt(e)];var v=h.flush(d);return Be(v)?v.then(function(m){return t.flushRemux(u,m,e),u}):(this.flushRemux(u,v,e),u)},n.flushRemux=function(e,t,r){var s=t.audioTrack,o=t.videoTrack,l=t.id3Track,u=t.textTrack,d=this.currentTransmuxState,f=d.accurateTimeOffset,h=d.timeOffset;A.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var c=this.remuxer.remux(s,o,l,u,h,f,!0,this.id);e.push({remuxResult:c,chunkMeta:r}),r.transmuxing.executeEnd=Ce()},n.resetInitialTimestamp=function(e){var t=this.demuxer,r=this.remuxer;!t||!r||(t.resetTimeStamp(e),r.resetTimeStamp(e))},n.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())},n.resetInitSegment=function(e,t,r,s,o){var l=this.demuxer,u=this.remuxer;!l||!u||(l.resetInitSegment(e,t,r,s),u.resetInitSegment(e,t,r,o))},n.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},n.transmux=function(e,t,r,s,o){var l;return t&&t.method==="SAMPLE-AES"?l=this.transmuxSampleAes(e,t,r,s,o):l=this.transmuxUnencrypted(e,r,s,o),l},n.transmuxUnencrypted=function(e,t,r,s){var o=this.demuxer.demux(e,t,!1,!this.config.progressive),l=o.audioTrack,u=o.videoTrack,d=o.id3Track,f=o.textTrack,h=this.remuxer.remux(l,u,d,f,t,r,!1,this.id);return{remuxResult:h,chunkMeta:s}},n.transmuxSampleAes=function(e,t,r,s,o){var l=this;return this.demuxer.demuxSampleAes(e,t,r).then(function(u){var d=l.remuxer.remux(u.audioTrack,u.videoTrack,u.id3Track,u.textTrack,r,s,!1,l.id);return{remuxResult:d,chunkMeta:o}})},n.configureTransmuxer=function(e){for(var t=this.config,r=this.observer,s=this.typeSupported,o=this.vendor,l,u=0,d=qt.length;u<d;u++){var f;if((f=qt[u].demux)!=null&&f.probe(e)){l=qt[u];break}}if(!l)return new Error("Failed to find demuxer by probing fragment data");var h=this.demuxer,c=this.remuxer,v=l.remux,m=l.demux;(!c||!(c instanceof v))&&(this.remuxer=new v(r,t,s,o)),(!h||!(h instanceof m))&&(this.demuxer=new m(r,t,s),this.probe=m.probe)},n.needsProbing=function(e,t){return!this.demuxer||!this.remuxer||e||t},n.getDecrypter=function(){var e=this.decrypter;return e||(e=this.decrypter=new Ut(this.config)),e},a}();function Fs(a,n){var i=null;return a.byteLength>0&&n?.key!=null&&n.iv!==null&&n.method!=null&&(i=n),i}var Xt=function(n){return{remuxResult:{},chunkMeta:n}};function Be(a){return"then"in a&&a.then instanceof Function}var Os=function(n,i,e,t,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=n,this.videoCodec=i,this.initSegmentData=e,this.duration=t,this.defaultInitPts=r||null},Ms=function(n,i,e,t,r,s){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=n,this.contiguous=i,this.accurateTimeOffset=e,this.trackSwitch=t,this.timeOffset=r,this.initSegmentChange=s},Ci={exports:{}};(function(a){var n=Object.prototype.hasOwnProperty,i="~";function e(){}Object.create&&(e.prototype=Object.create(null),new e().__proto__||(i=!1));function t(l,u,d){this.fn=l,this.context=u,this.once=d||!1}function r(l,u,d,f,h){if(typeof d!="function")throw new TypeError("The listener must be a function");var c=new t(d,f||l,h),v=i?i+u:u;return l._events[v]?l._events[v].fn?l._events[v]=[l._events[v],c]:l._events[v].push(c):(l._events[v]=c,l._eventsCount++),l}function s(l,u){--l._eventsCount===0?l._events=new e:delete l._events[u]}function o(){this._events=new e,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],d,f;if(this._eventsCount===0)return u;for(f in d=this._events)n.call(d,f)&&u.push(i?f.slice(1):f);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},o.prototype.listeners=function(u){var d=i?i+u:u,f=this._events[d];if(!f)return[];if(f.fn)return[f.fn];for(var h=0,c=f.length,v=new Array(c);h<c;h++)v[h]=f[h].fn;return v},o.prototype.listenerCount=function(u){var d=i?i+u:u,f=this._events[d];return f?f.fn?1:f.length:0},o.prototype.emit=function(u,d,f,h,c,v){var m=i?i+u:u;if(!this._events[m])return!1;var g=this._events[m],p=arguments.length,y,E;if(g.fn){switch(g.once&&this.removeListener(u,g.fn,void 0,!0),p){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,d),!0;case 3:return g.fn.call(g.context,d,f),!0;case 4:return g.fn.call(g.context,d,f,h),!0;case 5:return g.fn.call(g.context,d,f,h,c),!0;case 6:return g.fn.call(g.context,d,f,h,c,v),!0}for(E=1,y=new Array(p-1);E<p;E++)y[E-1]=arguments[E];g.fn.apply(g.context,y)}else{var S=g.length,L;for(E=0;E<S;E++)switch(g[E].once&&this.removeListener(u,g[E].fn,void 0,!0),p){case 1:g[E].fn.call(g[E].context);break;case 2:g[E].fn.call(g[E].context,d);break;case 3:g[E].fn.call(g[E].context,d,f);break;case 4:g[E].fn.call(g[E].context,d,f,h);break;default:if(!y)for(L=1,y=new Array(p-1);L<p;L++)y[L-1]=arguments[L];g[E].fn.apply(g[E].context,y)}}return!0},o.prototype.on=function(u,d,f){return r(this,u,d,f,!1)},o.prototype.once=function(u,d,f){return r(this,u,d,f,!0)},o.prototype.removeListener=function(u,d,f,h){var c=i?i+u:u;if(!this._events[c])return this;if(!d)return s(this,c),this;var v=this._events[c];if(v.fn)v.fn===d&&(!h||v.once)&&(!f||v.context===f)&&s(this,c);else{for(var m=0,g=[],p=v.length;m<p;m++)(v[m].fn!==d||h&&!v[m].once||f&&v[m].context!==f)&&g.push(v[m]);g.length?this._events[c]=g.length===1?g[0]:g:s(this,c)}return this},o.prototype.removeAllListeners=function(u){var d;return u?(d=i?i+u:u,this._events[d]&&s(this,d)):(this._events=new e,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,a.exports=o})(Ci);var Ns=Ci.exports,zt=nr(Ns);typeof tr<"u"&&tr&&Bs(self);function Bs(a){var n=new zt,i=function(r,s){a.postMessage({event:r,data:s})};n.on(x.FRAG_DECRYPTED,i),n.on(x.ERROR,i);var e=function(){var r=function(l){var u=function(f){i("workerLog",{logType:l,message:f})};A[l]=u};for(var s in A)r(s)};a.addEventListener("message",function(t){var r=t.data;switch(r.cmd){case"init":{var s=JSON.parse(r.config);a.transmuxer=new jt(n,r.typeSupported,s,r.vendor,r.id),sr(s.debug,r.id),e(),i("init",null);break}case"configure":{a.transmuxer.configure(r.config);break}case"demux":{var o=a.transmuxer.push(r.data,r.decryptdata,r.chunkMeta,r.state);Be(o)?(a.transmuxer.async=!0,o.then(function(f){$t(a,f)}).catch(function(f){i(x.ERROR,{type:V.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,chunkMeta:r.chunkMeta,fatal:!1,error:f,err:f,reason:"transmuxer-worker push error"})})):(a.transmuxer.async=!1,$t(a,o));break}case"flush":{var l=r.chunkMeta,u=a.transmuxer.flush(l),d=Be(u);d||a.transmuxer.async?(Be(u)||(u=Promise.resolve(u)),u.then(function(f){wi(a,f,l)}).catch(function(f){i(x.ERROR,{type:V.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,chunkMeta:r.chunkMeta,fatal:!1,error:f,err:f,reason:"transmuxer-worker flush error"})})):wi(a,u,l);break}}})}function $t(a,n){if(Us(n.remuxResult))return!1;var i=[],e=n.remuxResult,t=e.audio,r=e.video;return t&&Pi(i,t),r&&Pi(i,r),a.postMessage({event:"transmuxComplete",data:n},i),!0}function Pi(a,n){n.data1&&a.push(n.data1.buffer),n.data2&&a.push(n.data2.buffer)}function wi(a,n,i){var e=n.reduce(function(t,r){return $t(a,r)||t},!1);e||a.postMessage({event:"transmuxComplete",data:n[0]}),a.postMessage({event:"flush",data:i})}function Us(a){return!a.audio&&!a.video&&!a.text&&!a.id3&&!a.initSegment}function Gs(){return typeof er=="function"}function Hs(){var a=new self.Blob(["var exports={};var module={exports:exports};function define(f){f()};define.amd=true;("+er.toString()+")(true);"],{type:"text/javascript"}),n=self.URL.createObjectURL(a),i=new self.Worker(n);return{worker:i,objectURL:n}}function Vs(a){var n=new self.URL(a,self.location.href).href,i=new self.Worker(n);return{worker:i,scriptURL:n}}var Ks=function(){function a(i,e,t,r){var s=this;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;var o=i.config;this.hls=i,this.id=e,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=t,this.onFlush=r;var l=function(m,g){g=g||{},g.frag=s.frag,g.id=s.id,m===x.ERROR&&(s.error=g.error),s.hls.trigger(m,g)};this.observer=new zt,this.observer.on(x.FRAG_DECRYPTED,l),this.observer.on(x.ERROR,l);var u=Ne(o.preferManagedMediaSource)||{isTypeSupported:function(){return!1}},d={mpeg:u.isTypeSupported("audio/mpeg"),mp3:u.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:!1},f=navigator.vendor;if(this.useWorker&&typeof Worker<"u"){var h=o.workerPath||Gs();if(h){try{o.workerPath?(A.log("loading Web Worker "+o.workerPath+' for "'+e+'"'),this.workerContext=Vs(o.workerPath)):(A.log('injecting Web Worker for "'+e+'"'),this.workerContext=Hs()),this.onwmsg=function(v){return s.onWorkerMessage(v)};var c=this.workerContext.worker;c.addEventListener("message",this.onwmsg),c.onerror=function(v){var m=new Error(v.message+" ("+v.filename+":"+v.lineno+")");o.enableWorker=!1,A.warn('Error in "'+e+'" Web Worker, fallback to inline'),s.hls.trigger(x.ERROR,{type:V.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:m})},c.postMessage({cmd:"init",typeSupported:d,vendor:f,id:e,config:JSON.stringify(o)})}catch(v){A.warn('Error setting up "'+e+'" Web Worker, fallback to inline',v),this.resetWorker(),this.error=null,this.transmuxer=new jt(this.observer,d,o,f,e)}return}}this.transmuxer=new jt(this.observer,d,o,f,e)}var n=a.prototype;return n.resetWorker=function(){if(this.workerContext){var e=this.workerContext,t=e.worker,r=e.objectURL;r&&self.URL.revokeObjectURL(r),t.removeEventListener("message",this.onwmsg),t.onerror=null,t.terminate(),this.workerContext=null}},n.destroy=function(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null},n.push=function(e,t,r,s,o,l,u,d,f,h){var c,v,m=this;f.transmuxing.start=self.performance.now();var g=this.transmuxer,p=l?l.start:o.start,y=o.decryptdata,E=this.frag,S=!(E&&o.cc===E.cc),L=!(E&&f.level===E.level),D=E?f.sn-E.sn:-1,R=this.part?f.part-this.part.index:-1,T=D===0&&f.id>1&&f.id===E?.stats.chunkCount,b=!L&&(D===1||D===0&&(R===1||T&&R<=0)),I=self.performance.now();(L||D||o.stats.parsing.start===0)&&(o.stats.parsing.start=I),l&&(R||!b)&&(l.stats.parsing.start=I);var P=!(E&&((c=o.initSegment)==null?void 0:c.url)===((v=E.initSegment)==null?void 0:v.url)),C=new Ms(S,b,d,L,p,P);if(!b||S||P){A.log("[transmuxer-interface, "+o.type+"]: Starting new transmux session for sn: "+f.sn+" p: "+f.part+" level: "+f.level+" id: "+f.id+`
9
+ discontinuity: `+S+`
10
+ trackSwitch: `+L+`
11
+ contiguous: `+b+`
12
+ accurateTimeOffset: `+d+`
13
+ timeOffset: `+p+`
14
+ initSegmentChange: `+P);var w=new Os(r,s,t,u,h);this.configureTransmuxer(w)}if(this.frag=o,this.part=l,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:y,chunkMeta:f,state:C},e instanceof ArrayBuffer?[e]:[]);else if(g){var M=g.push(e,y,f,C);Be(M)?(g.async=!0,M.then(function(F){m.handleTransmuxComplete(F)}).catch(function(F){m.transmuxerError(F,f,"transmuxer-interface push error")})):(g.async=!1,this.handleTransmuxComplete(M))}},n.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(r){var s=r.flush(e),o=Be(s);o||r.async?(Be(s)||(s=Promise.resolve(s)),s.then(function(l){t.handleFlushResult(l,e)}).catch(function(l){t.transmuxerError(l,e,"transmuxer-interface flush error")})):this.handleFlushResult(s,e)}},n.transmuxerError=function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(x.ERROR,{type:V.MEDIA_ERROR,details:_.FRAG_PARSING_ERROR,chunkMeta:t,fatal:!1,error:e,err:e,reason:r}))},n.handleFlushResult=function(e,t){var r=this;e.forEach(function(s){r.handleTransmuxComplete(s)}),this.onFlush(t)},n.onWorkerMessage=function(e){var t=e.data,r=this.hls;switch(t.event){case"init":{var s,o=(s=this.workerContext)==null?void 0:s.objectURL;o&&self.URL.revokeObjectURL(o);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":A[t.data.logType]&&A[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,r.trigger(t.event,t.data);break}}},n.configureTransmuxer=function(e){var t=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)},n.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},a}(),Ws=250,vt=2,Ys=.1,qs=.05,js=function(){function a(i,e,t,r){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=i,this.media=e,this.fragmentTracker=t,this.hls=r}var n=a.prototype;return n.destroy=function(){this.media=null,this.hls=this.fragmentTracker=null},n.poll=function(e,t){var r=this.config,s=this.media,o=this.stalled;if(s!==null){var l=s.currentTime,u=s.seeking,d=this.seeking&&!u,f=!this.seeking&&u;if(this.seeking=u,l!==e){if(this.moved=!0,u||(this.nudgeRetry=0),o!==null){if(this.stallReported){var h=self.performance.now()-o;A.warn("playback not stuck anymore @"+l+", after "+Math.round(h)+"ms"),this.stallReported=!1}this.stalled=null}return}if(f||d){this.stalled=null;return}if(s.paused&&!u||s.ended||s.playbackRate===0||!ae.getBuffered(s).length){this.nudgeRetry=0;return}var c=ae.bufferInfo(s,l,0),v=c.nextStart||0;if(u){var m=c.len>vt,g=!v||t&&t.start<=l||v-l>vt&&!this.fragmentTracker.getPartialFragment(l);if(m||g)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var p,y=c.len>0;if(!y&&!v)return;var E=Math.max(v,c.start||0)-l,S=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,L=S==null||(p=S.details)==null?void 0:p.live,D=L?S.details.targetduration*2:vt,R=this.fragmentTracker.getPartialFragment(l);if(E>0&&(E<=D||R)){s.paused||this._trySkipBufferHole(R);return}}var T=self.performance.now();if(o===null){this.stalled=T;return}var b=T-o;if(!(!u&&b>=Ws&&(this._reportStall(c),!this.media))){var I=ae.bufferInfo(s,l,r.maxBufferHole);this._tryFixBufferStall(I,b)}}},n._tryFixBufferStall=function(e,t){var r=this.config,s=this.fragmentTracker,o=this.media;if(o!==null){var l=o.currentTime,u=s.getPartialFragment(l);if(u){var d=this._trySkipBufferHole(u);if(d||!this.media)return}(e.len>r.maxBufferHole||e.nextStart&&e.nextStart-l<r.maxBufferHole)&&t>r.highBufferWatchdogPeriod*1e3&&(A.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}},n._reportStall=function(e){var t=this.hls,r=this.media,s=this.stallReported;if(!s&&r){this.stallReported=!0;var o=new Error("Playback stalling at @"+r.currentTime+" due to low buffer ("+JSON.stringify(e)+")");A.warn(o.message),t.trigger(x.ERROR,{type:V.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,fatal:!1,error:o,buffer:e.len})}},n._trySkipBufferHole=function(e){var t=this.config,r=this.hls,s=this.media;if(s===null)return 0;var o=s.currentTime,l=ae.bufferInfo(s,o,0),u=o<l.start?l.start:l.nextStart;if(u){var d=l.len<=t.maxBufferHole,f=l.len>0&&l.len<1&&s.readyState<3,h=u-o;if(h>0&&(d||f)){if(h>t.maxBufferHole){var c=this.fragmentTracker,v=!1;if(o===0){var m=c.getAppendedFrag(0,j.MAIN);m&&u<m.end&&(v=!0)}if(!v){var g=e||c.getAppendedFrag(o,j.MAIN);if(g){for(var p=!1,y=g.end;y<u;){var E=c.getPartialFragment(y);if(E)y+=E.duration;else{p=!0;break}}if(p)return 0}}}var S=Math.max(u+qs,o+Ys);if(A.warn("skipping hole, adjusting currentTime from "+o+" to "+S),this.moved=!0,this.stalled=null,s.currentTime=S,e&&!e.gap){var L=new Error("fragment loaded with buffer holes, seeking from "+o+" to "+S);r.trigger(x.ERROR,{type:V.MEDIA_ERROR,details:_.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:L,reason:L.message,frag:e})}return S}}return 0},n._tryNudgeBuffer=function(){var e=this.config,t=this.hls,r=this.media,s=this.nudgeRetry;if(r!==null){var o=r.currentTime;if(this.nudgeRetry++,s<e.nudgeMaxRetry){var l=o+(s+1)*e.nudgeOffset,u=new Error("Nudging 'currentTime' from "+o+" to "+l);A.warn(u.message),r.currentTime=l,t.trigger(x.ERROR,{type:V.MEDIA_ERROR,details:_.BUFFER_NUDGE_ON_STALL,error:u,fatal:!1})}else{var d=new Error("Playhead still not moving while enough data buffered @"+o+" after "+e.nudgeMaxRetry+" nudges");A.error(d.message),t.trigger(x.ERROR,{type:V.MEDIA_ERROR,details:_.BUFFER_STALLED_ERROR,error:d,fatal:!0})}}},a}(),Xs=100,zs=function(a){Re(n,a);function n(e,t,r){var s;return s=a.call(this,e,t,r,"[stream-controller]",j.MAIN)||this,s.audioCodecSwap=!1,s.gapController=null,s.level=-1,s._forceStartLoad=!1,s.altAudio=!1,s.audioOnly=!1,s.fragPlaying=null,s.onvplaying=null,s.onvseeked=null,s.fragLastKbps=0,s.couldBacktrack=!1,s.backtrackFragment=null,s.audioCodecSwitch=!1,s.videoBuffer=null,s._registerListeners(),s}var i=n.prototype;return i._registerListeners=function(){var t=this.hls;t.on(x.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(x.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(x.MANIFEST_LOADING,this.onManifestLoading,this),t.on(x.MANIFEST_PARSED,this.onManifestParsed,this),t.on(x.LEVEL_LOADING,this.onLevelLoading,this),t.on(x.LEVEL_LOADED,this.onLevelLoaded,this),t.on(x.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(x.ERROR,this.onError,this),t.on(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(x.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(x.BUFFER_CREATED,this.onBufferCreated,this),t.on(x.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(x.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(x.FRAG_BUFFERED,this.onFragBuffered,this)},i._unregisterListeners=function(){var t=this.hls;t.off(x.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(x.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(x.MANIFEST_LOADING,this.onManifestLoading,this),t.off(x.MANIFEST_PARSED,this.onManifestParsed,this),t.off(x.LEVEL_LOADED,this.onLevelLoaded,this),t.off(x.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(x.ERROR,this.onError,this),t.off(x.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(x.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(x.BUFFER_CREATED,this.onBufferCreated,this),t.off(x.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(x.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(x.FRAG_BUFFERED,this.onFragBuffered,this)},i.onHandlerDestroying=function(){this._unregisterListeners(),a.prototype.onHandlerDestroying.call(this)},i.startLoad=function(t){if(this.levels){var r=this.lastCurrentTime,s=this.hls;if(this.stopLoad(),this.setInterval(Xs),this.level=-1,!this.startFragRequested){var o=s.startLevel;o===-1&&(s.config.testBandwidth&&this.levels.length>1?(o=0,this.bitrateTest=!0):o=s.firstAutoLevel),s.nextLoadLevel=o,this.level=s.loadLevel,this.loadedmetadata=!1}r>0&&t===-1&&(this.log("Override startPosition with lastCurrentTime @"+r.toFixed(3)),t=r),this.state=k.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=k.STOPPED},i.stopLoad=function(){this._forceStartLoad=!1,a.prototype.stopLoad.call(this)},i.doTick=function(){switch(this.state){case k.WAITING_LEVEL:{var t=this.levels,r=this.level,s=t?.[r],o=s?.details;if(o&&(!o.live||this.levelLastLoaded===s)){if(this.waitForCdnTuneIn(o))break;this.state=k.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=k.IDLE;break}break}case k.FRAG_LOADING_WAITING_RETRY:{var l,u=self.performance.now(),d=this.retryDate;if(!d||u>=d||(l=this.media)!=null&&l.seeking){var f=this.levels,h=this.level,c=f?.[h];this.resetStartWhenNotLoaded(c||null),this.state=k.IDLE}}break}this.state===k.IDLE&&this.doTickIdle(),this.onTickEnd()},i.onTickEnd=function(){a.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},i.doTickIdle=function(){var t=this.hls,r=this.levelLastLoaded,s=this.levels,o=this.media;if(!(r===null||!o&&(this.startFragRequested||!t.config.startFragPrefetch))&&!(this.altAudio&&this.audioOnly)){var l=t.nextLoadLevel;if(s!=null&&s[l]){var u=s[l],d=this.getMainFwdBufferInfo();if(d!==null){var f=this.getLevelDetails();if(f&&this._streamEnded(d,f)){var h={};this.altAudio&&(h.type="video"),this.hls.trigger(x.BUFFER_EOS,h),this.state=k.ENDED;return}t.loadLevel!==l&&t.manualLevel===-1&&this.log("Adapting to level "+l+" from level "+this.level),this.level=t.nextLoadLevel=l;var c=u.details;if(!c||this.state===k.WAITING_LEVEL||c.live&&this.levelLastLoaded!==u){this.level=l,this.state=k.WAITING_LEVEL;return}var v=d.len,m=this.getMaxBufferLength(u.maxBitrate);if(!(v>=m)){this.backtrackFragment&&this.backtrackFragment.start>d.end&&(this.backtrackFragment=null);var g=this.backtrackFragment?this.backtrackFragment.start:d.end,p=this.getNextFragment(g,c);if(this.couldBacktrack&&!this.fragPrevious&&p&&p.sn!=="initSegment"&&this.fragmentTracker.getState(p)!==me.OK){var y,E=((y=this.backtrackFragment)!=null?y:p).sn,S=E-c.startSN,L=c.fragments[S-1];L&&p.cc===L.cc&&(p=L,this.fragmentTracker.removeFragment(L))}else this.backtrackFragment&&d.len&&(this.backtrackFragment=null);if(p&&this.isLoopLoading(p,g)){var D=p.gap;if(!D){var R=this.audioOnly&&!this.altAudio?$.AUDIO:$.VIDEO,T=(R===$.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;T&&this.afterBufferFlushed(T,R,j.MAIN)}p=this.getNextFragmentLoopLoading(p,c,d,j.MAIN,m)}p&&(p.initSegment&&!p.initSegment.data&&!this.bitrateTest&&(p=p.initSegment),this.loadFragment(p,u,g))}}}}},i.loadFragment=function(t,r,s){var o=this.fragmentTracker.getState(t);this.fragCurrent=t,o===me.NOT_LOADED||o===me.PARTIAL?t.sn==="initSegment"?this._loadInitSegment(t,r):this.bitrateTest?(this.log("Fragment "+t.sn+" of level "+t.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(t,r)):(this.startFragRequested=!0,a.prototype.loadFragment.call(this,t,r,s)):this.clearTrackerIfNeeded(t)},i.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,j.MAIN)},i.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.end+.5):null},i.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},i.nextLevelSwitch=function(){var t=this.levels,r=this.media;if(r!=null&&r.readyState){var s,o=this.getAppendedFrag(r.currentTime);o&&o.start>1&&this.flushMainBuffer(0,o.start-1);var l=this.getLevelDetails();if(l!=null&&l.live){var u=this.getMainFwdBufferInfo();if(!u||u.len<l.targetduration*2)return}if(!r.paused&&t){var d=this.hls.nextLoadLevel,f=t[d],h=this.fragLastKbps;h&&this.fragCurrent?s=this.fragCurrent.duration*f.maxBitrate/(1e3*h)+1:s=0}else s=0;var c=this.getBufferedFrag(r.currentTime+s);if(c){var v=this.followingBufferedFrag(c);if(v){this.abortCurrentFrag();var m=v.maxStartPTS?v.maxStartPTS:v.start,g=v.duration,p=Math.max(c.end,m+Math.min(Math.max(g-this.config.maxFragLookUpTolerance,g*(this.couldBacktrack?.5:.125)),g*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(p,Number.POSITIVE_INFINITY)}}}},i.abortCurrentFrag=function(){var t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case k.KEY_LOADING:case k.FRAG_LOADING:case k.FRAG_LOADING_WAITING_RETRY:case k.PARSING:case k.PARSED:this.state=k.IDLE;break}this.nextLoadPosition=this.getLoadPosition()},i.flushMainBuffer=function(t,r){a.prototype.flushMainBuffer.call(this,t,r,this.altAudio?"video":null)},i.onMediaAttached=function(t,r){a.prototype.onMediaAttached.call(this,t,r);var s=r.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 js(this.config,s,this.fragmentTracker,this.hls)},i.onMediaDetaching=function(){var t=this.media;t&&this.onvplaying&&this.onvseeked&&(t.removeEventListener("playing",this.onvplaying),t.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),a.prototype.onMediaDetaching.call(this)},i.onMediaPlaying=function(){this.tick()},i.onMediaSeeked=function(){var t=this.media,r=t?t.currentTime:null;O(r)&&this.log("Media seeked to "+r.toFixed(3));var s=this.getMainFwdBufferInfo();if(s===null||s.len===0){this.warn('Main forward buffer length on "seeked" event '+(s?s.len:"empty")+")");return}this.tick()},i.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(x.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},i.onManifestParsed=function(t,r){var s=!1,o=!1;r.levels.forEach(function(l){var u=l.audioCodec;u&&(s=s||u.indexOf("mp4a.40.2")!==-1,o=o||u.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=s&&o&&!is(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=r.levels,this.startFragRequested=!1},i.onLevelLoading=function(t,r){var s=this.levels;if(!(!s||this.state!==k.IDLE)){var o=s[r.level];(!o.details||o.details.live&&this.levelLastLoaded!==o||this.waitForCdnTuneIn(o.details))&&(this.state=k.WAITING_LEVEL)}},i.onLevelLoaded=function(t,r){var s,o=this.levels,l=r.level,u=r.details,d=u.totalduration;if(!o){this.warn("Levels were reset while loading level "+l);return}this.log("Level "+l+" loaded ["+u.startSN+","+u.endSN+"]"+(u.lastPartSn?"[part-"+u.lastPartSn+"-"+u.lastPartIndex+"]":"")+", cc ["+u.startCC+", "+u.endCC+"] duration:"+d);var f=o[l],h=this.fragCurrent;h&&(this.state===k.FRAG_LOADING||this.state===k.FRAG_LOADING_WAITING_RETRY)&&h.level!==r.level&&h.loader&&this.abortCurrentFrag();var c=0;if(u.live||(s=f.details)!=null&&s.live){var v;if(this.checkLiveUpdate(u),u.deltaUpdateFailed)return;c=this.alignPlaylists(u,f.details,(v=this.levelLastLoaded)==null?void 0:v.details)}if(f.details=u,this.levelLastLoaded=f,this.hls.trigger(x.LEVEL_UPDATED,{details:u,level:l}),this.state===k.WAITING_LEVEL){if(this.waitForCdnTuneIn(u))return;this.state=k.IDLE}this.startFragRequested?u.live&&this.synchronizeToLiveEdge(u):this.setStartPosition(u,c),this.tick()},i._handleFragmentLoadProgress=function(t){var r,s=t.frag,o=t.part,l=t.payload,u=this.levels;if(!u){this.warn("Levels were reset while fragment load was in progress. Fragment "+s.sn+" of level "+s.level+" will not be buffered");return}var d=u[s.level],f=d.details;if(!f){this.warn("Dropping fragment "+s.sn+" of level "+s.level+" after level details were reset"),this.fragmentTracker.removeFragment(s);return}var h=d.videoCodec,c=f.PTSKnown||!f.live,v=(r=s.initSegment)==null?void 0:r.data,m=this._getAudioCodec(d),g=this.transmuxer=this.transmuxer||new Ks(this.hls,j.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),p=o?o.index:-1,y=p!==-1,E=new oi(s.level,s.sn,s.stats.chunkCount,l.byteLength,p,y),S=this.initPTS[s.cc];g.push(l,v,m,h,s,o,f.totalduration,c,E,S)},i.onAudioTrackSwitching=function(t,r){var s=this.altAudio,o=!!r.url;if(!o){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var l=this.fragCurrent;l&&(this.log("Switching to main audio track, cancel main fragment load"),l.abortRequests(),this.fragmentTracker.removeFragment(l)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var u=this.hls;s&&(u.trigger(x.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),u.trigger(x.AUDIO_TRACK_SWITCHED,r)}},i.onAudioTrackSwitched=function(t,r){var s=r.id,o=!!this.hls.audioTracks[s].url;if(o){var l=this.videoBuffer;l&&this.mediaBuffer!==l&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=l)}this.altAudio=o,this.tick()},i.onBufferCreated=function(t,r){var s=r.tracks,o,l,u=!1;for(var d in s){var f=s[d];if(f.id==="main"){if(l=d,o=f,d==="video"){var h=s[d];h&&(this.videoBuffer=h.buffer)}}else u=!0}u&&o?(this.log("Alternate track found, use "+l+".buffered to schedule main fragment loading"),this.mediaBuffer=o.buffer):this.mediaBuffer=this.media},i.onFragBuffered=function(t,r){var s=r.frag,o=r.part;if(!(s&&s.type!==j.MAIN)){if(this.fragContextChanged(s)){this.warn("Fragment "+s.sn+(o?" p: "+o.index:"")+" of level "+s.level+" finished buffering, but was aborted. state: "+this.state),this.state===k.PARSED&&(this.state=k.IDLE);return}var l=o?o.stats:s.stats;this.fragLastKbps=Math.round(8*l.total/(l.buffering.end-l.loading.first)),s.sn!=="initSegment"&&(this.fragPrevious=s),this.fragBufferedComplete(s,o)}},i.onError=function(t,r){var s;if(r.fatal){this.state=k.ERROR;return}switch(r.details){case _.FRAG_GAP:case _.FRAG_PARSING_ERROR:case _.FRAG_DECRYPT_ERROR:case _.FRAG_LOAD_ERROR:case _.FRAG_LOAD_TIMEOUT:case _.KEY_LOAD_ERROR:case _.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(j.MAIN,r);break;case _.LEVEL_LOAD_ERROR:case _.LEVEL_LOAD_TIMEOUT:case _.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===k.WAITING_LEVEL&&((s=r.context)==null?void 0:s.type)===Y.LEVEL&&(this.state=k.IDLE);break;case _.BUFFER_APPEND_ERROR:case _.BUFFER_FULL_ERROR:if(!r.parent||r.parent!=="main")return;if(r.details===_.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(r)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case _.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}},i.checkBuffer=function(){var t=this.media,r=this.gapController;if(!(!t||!r||!t.readyState)){if(this.loadedmetadata||!ae.getBuffered(t).length){var s=this.state!==k.IDLE?this.fragCurrent:null;r.poll(this.lastCurrentTime,s)}this.lastCurrentTime=t.currentTime}},i.onFragLoadEmergencyAborted=function(){this.state=k.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},i.onBufferFlushed=function(t,r){var s=r.type;if(s!==$.AUDIO||this.audioOnly&&!this.altAudio){var o=(s===$.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(o,s,j.MAIN),this.tick()}},i.onLevelsUpdated=function(t,r){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=r.levels},i.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},i.seekToStartPos=function(){var t=this.media;if(t){var r=t.currentTime,s=this.startPosition;if(s>=0&&r<s){if(t.seeking){this.log("could not seek to "+s+", already seeking at "+r);return}var o=ae.getBuffered(t),l=o.length?o.start(0):0,u=l-s;u>0&&(u<this.config.maxBufferHole||u<this.config.maxFragLookUpTolerance)&&(this.log("adjusting start position by "+u+" to match buffer start"),s+=u,this.startPosition=s),this.log("seek to target start position "+s+" from current time "+r),t.currentTime=s}}},i._getAudioCodec=function(t){var r=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&r&&(this.log("Swapping audio codec"),r.indexOf("mp4a.40.5")!==-1?r="mp4a.40.2":r="mp4a.40.5"),r},i._loadBitrateTestFrag=function(t,r){var s=this;t.bitrateTest=!0,this._doFragLoad(t,r).then(function(o){var l=s.hls;if(!(!o||s.fragContextChanged(t))){r.fragmentError=0,s.state=k.IDLE,s.startFragRequested=!1,s.bitrateTest=!1;var u=t.stats;u.parsing.start=u.parsing.end=u.buffering.start=u.buffering.end=self.performance.now(),l.trigger(x.FRAG_LOADED,o),t.bitrateTest=!1}})},i._handleTransmuxComplete=function(t){var r,s="main",o=this.hls,l=t.remuxResult,u=t.chunkMeta,d=this.getCurrentContext(u);if(!d){this.resetWhenMissingContext(u);return}var f=d.frag,h=d.part,c=d.level,v=l.video,m=l.text,g=l.id3,p=l.initSegment,y=c.details,E=this.altAudio?void 0:l.audio;if(this.fragContextChanged(f)){this.fragmentTracker.removeFragment(f);return}if(this.state=k.PARSING,p){if(p!=null&&p.tracks){var S=f.initSegment||f;this._bufferInitSegment(c,p.tracks,S,u),o.trigger(x.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:s,tracks:p.tracks})}var L=p.initPTS,D=p.timescale;O(L)&&(this.initPTS[f.cc]={baseTime:L,timescale:D},o.trigger(x.INIT_PTS_FOUND,{frag:f,id:s,initPTS:L,timescale:D}))}if(v&&y&&f.sn!=="initSegment"){var R=y.fragments[f.sn-1-y.startSN],T=f.sn===y.startSN,b=!R||f.cc>R.cc;if(l.independent!==!1){var I=v.startPTS,P=v.endPTS,C=v.startDTS,w=v.endDTS;if(h)h.elementaryStreams[v.type]={startPTS:I,endPTS:P,startDTS:C,endDTS:w};else if(v.firstKeyFrame&&v.independent&&u.id===1&&!b&&(this.couldBacktrack=!0),v.dropped&&v.independent){var M=this.getMainFwdBufferInfo(),F=(M?M.end:this.getLoadPosition())+this.config.maxBufferHole,H=v.firstKeyFramePTS?v.firstKeyFramePTS:I;if(!T&&F<H-this.config.maxBufferHole&&!b){this.backtrack(f);return}else b&&(f.gap=!0);f.setElementaryStreamInfo(v.type,f.start,P,f.start,w,!0)}else T&&I>vt&&(f.gap=!0);f.setElementaryStreamInfo(v.type,I,P,C,w),this.backtrackFragment&&(this.backtrackFragment=f),this.bufferFragmentData(v,f,h,u,T||b)}else if(T||b)f.gap=!0;else{this.backtrack(f);return}}if(E){var U=E.startPTS,W=E.endPTS,K=E.startDTS,B=E.endDTS;h&&(h.elementaryStreams[$.AUDIO]={startPTS:U,endPTS:W,startDTS:K,endDTS:B}),f.setElementaryStreamInfo($.AUDIO,U,W,K,B),this.bufferFragmentData(E,f,h,u)}if(y&&g!=null&&(r=g.samples)!=null&&r.length){var Q={id:s,frag:f,details:y,samples:g.samples};o.trigger(x.FRAG_PARSING_METADATA,Q)}if(y&&m){var q={id:s,frag:f,details:y,samples:m.samples};o.trigger(x.FRAG_PARSING_USERDATA,q)}},i._bufferInitSegment=function(t,r,s,o){var l=this;if(this.state===k.PARSING){this.audioOnly=!!r.audio&&!r.video,this.altAudio&&!this.audioOnly&&delete r.audio;var u=r.audio,d=r.video,f=r.audiovideo;if(u){var h=t.audioCodec,c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5"),u.metadata.channelCount!==1&&c.indexOf("firefox")===-1&&(h="mp4a.40.5")),h&&h.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&u.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log("Android: force audio codec to "+h)),t.audioCodec&&t.audioCodec!==h&&this.log('Swapping manifest audio codec "'+t.audioCodec+'" for "'+h+'"'),u.levelCodec=h,u.id="main",this.log("Init audio buffer, container:"+u.container+", codecs[selected/level/parsed]=["+(h||"")+"/"+(t.audioCodec||"")+"/"+u.codec+"]")}d&&(d.levelCodec=t.videoCodec,d.id="main",this.log("Init video buffer, container:"+d.container+", codecs[level/parsed]=["+(t.videoCodec||"")+"/"+d.codec+"]")),f&&this.log("Init audiovideo buffer, container:"+f.container+", codecs[level/parsed]=["+t.codecs+"/"+f.codec+"]"),this.hls.trigger(x.BUFFER_CODECS,r),Object.keys(r).forEach(function(v){var m=r[v],g=m.initSegment;g!=null&&g.byteLength&&l.hls.trigger(x.BUFFER_APPENDING,{type:v,data:g,frag:s,part:null,chunkMeta:o,parent:s.type})}),this.tickImmediate()}},i.getMainFwdBufferInfo=function(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,j.MAIN)},i.backtrack=function(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=k.IDLE},i.checkFragmentChanged=function(){var t=this.media,r=null;if(t&&t.readyState>1&&t.seeking===!1){var s=t.currentTime;if(ae.isBuffered(t,s)?r=this.getAppendedFrag(s):ae.isBuffered(t,s+.1)&&(r=this.getAppendedFrag(s+.1)),r){this.backtrackFragment=null;var o=this.fragPlaying,l=r.level;(!o||r.sn!==o.sn||o.level!==l)&&(this.fragPlaying=r,this.hls.trigger(x.FRAG_CHANGED,{frag:r}),(!o||o.level!==l)&&this.hls.trigger(x.LEVEL_SWITCHED,{level:l}))}}},he(n,[{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"currentFrag",get:function(){var t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}},{key:"currentProgramDateTime",get:function(){var t=this.media;if(t){var r=t.currentTime,s=this.currentFrag;if(s&&O(r)&&O(s.programDateTime)){var o=s.programDateTime+(r-s.start)*1e3;return new Date(o)}}return null}},{key:"currentLevel",get:function(){var t=this.currentFrag;return t?t.level:-1}},{key:"nextBufferedFrag",get:function(){var t=this.currentFrag;return t?this.followingBufferedFrag(t):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}]),n}(ts),ki=function(){a.isMSESupported=function(){return di()},a.isSupported=function(){return rs()},a.getMediaSource=function(){return Ne()};function a(i){i===void 0&&(i={}),this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new zt,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,sr(i.debug||!1,"Hls instance");var e=this.config=Na(a.DefaultConfig,i);this.userConfig=i,e.progressive&&Ba(e);var t=e.abrController,r=e.bufferController,s=e.capLevelController,o=e.errorController,l=e.fpsController,u=new o(this),d=this.abrController=new t(this),f=this.bufferController=new r(this),h=this.capLevelController=new s(this),c=new l(this),v=new Un(this),m=new jn(this),g=e.contentSteeringController,p=g?new g(this):null,y=this.levelController=new Ua(this,p),E=new Ga(this),S=new Va(this.config),L=this.streamController=new zs(this,E,S);h.setStreamController(L),c.setStreamController(L);var D=[v,y,L];p&&D.splice(1,0,p),this.networkControllers=D;var R=[d,f,h,c,m,E];this.audioTrackController=this.createController(e.audioTrackController,D);var T=e.audioStreamController;T&&D.push(new T(this,E,S)),this.subtitleTrackController=this.createController(e.subtitleTrackController,D);var b=e.subtitleStreamController;b&&D.push(new b(this,E,S)),this.createController(e.timelineController,R),S.emeController=this.emeController=this.createController(e.emeController,R),this.cmcdController=this.createController(e.cmcdController,R),this.latencyController=this.createController(Xn,R),this.coreComponents=R,D.push(u);var I=u.onErrorOut;typeof I=="function"&&this.on(x.ERROR,I,u)}var n=a.prototype;return n.createController=function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null},n.on=function(e,t,r){r===void 0&&(r=this),this._emitter.on(e,t,r)},n.once=function(e,t,r){r===void 0&&(r=this),this._emitter.once(e,t,r)},n.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},n.off=function(e,t,r,s){r===void 0&&(r=this),this._emitter.off(e,t,r,s)},n.listeners=function(e){return this._emitter.listeners(e)},n.emit=function(e,t,r){return this._emitter.emit(e,t,r)},n.trigger=function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(A.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;var r=e===x.ERROR;this.trigger(x.ERROR,{type:V.OTHER_ERROR,details:_.INTERNAL_EXCEPTION,fatal:r,event:e,error:s}),this.triggeringException=!1}}return!1},n.listenerCount=function(e){return this._emitter.listenerCount(e)},n.destroy=function(){A.log("destroy"),this.trigger(x.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(function(t){return t.destroy()}),this.networkControllers.length=0,this.coreComponents.forEach(function(t){return t.destroy()}),this.coreComponents.length=0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null},n.attachMedia=function(e){A.log("attachMedia"),this._media=e,this.trigger(x.MEDIA_ATTACHING,{media:e})},n.detachMedia=function(){A.log("detachMedia"),this.trigger(x.MEDIA_DETACHING,void 0),this._media=null},n.loadSource=function(e){this.stopLoad();var t=this.media,r=this.url,s=this.url=xt.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,A.log("loadSource:"+s),t&&r&&(r!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(x.MANIFEST_LOADING,{url:e})},n.startLoad=function(e){e===void 0&&(e=-1),A.log("startLoad("+e+")"),this.started=!0,this.networkControllers.forEach(function(t){t.startLoad(e)})},n.stopLoad=function(){A.log("stopLoad"),this.started=!1,this.networkControllers.forEach(function(e){e.stopLoad()})},n.resumeBuffering=function(){this.started&&this.networkControllers.forEach(function(e){"fragmentLoader"in e&&e.startLoad(-1)})},n.pauseBuffering=function(){this.networkControllers.forEach(function(e){"fragmentLoader"in e&&e.stopLoad()})},n.swapAudioCodec=function(){A.log("swapAudioCodec"),this.streamController.swapAudioCodec()},n.recoverMediaError=function(){A.log("recoverMediaError");var e=this._media;this.detachMedia(),e&&this.attachMedia(e)},n.removeLevel=function(e){this.levelController.removeLevel(e)},n.setAudioOption=function(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)},n.setSubtitleOption=function(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null},he(a,[{key:"levels",get:function(){var e=this.levelController.levels;return e||[]}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(e){A.log("set currentLevel:"+e),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(e){A.log("set nextLevel:"+e),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(e){A.log("set loadLevel:"+e),this.levelController.manualLevel=e}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(e){this.levelController.nextLoadLevel=e}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(e){A.log("set firstLevel:"+e),this.levelController.firstLevel=e}},{key:"startLevel",get:function(){var e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e},set:function(e){A.log("set startLevel:"+e),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(A.log("set autoLevelCapping:"+e),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){zn(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return this.levelController.manualLevel===-1}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,s=0;s<r;s++)if(e[s].maxBitrate>=t)return s;return 0}},{key:"maxAutoLevel",get:function(){var e=this.levels,t=this.autoLevelCapping,r=this.maxHdcpLevel,s;if(t===-1&&e!=null&&e.length?s=e.length-1:s=t,r)for(var o=s;o--;){var l=e[o].attrs["HDCP-LEVEL"];if(l&&l<=r)return o}return s}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return e?e.subtitleDisplay:!1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}],[{key:"version",get:function(){return"1.5.8"}},{key:"Events",get:function(){return x}},{key:"ErrorTypes",get:function(){return V}},{key:"ErrorDetails",get:function(){return _}},{key:"DefaultConfig",get:function(){return a.defaultConfig?a.defaultConfig:ri},set:function(e){a.defaultConfig=e}}]),a}();return ki.defaultConfig=void 0,ki})})(!1)})(Gi);var oo=Gi.exports;const Hi=so(oo);export{Hi as Hls,Hi as default};