@alirezahosseini/sibtorsh-player 0.1.8 → 0.1.10

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/index.d.ts CHANGED
@@ -2,3 +2,5 @@ export { default as VideoPlayer } from './VideoPlayer';
2
2
  export type { default as VideoPlayerInterface } from './interfaces/VideoPlayerInterface';
3
3
  export { default as VideoPlayerControl } from './components/VideoPlayerControl';
4
4
  export type { VideoPlayerControlInterface } from './interfaces/VideoPlayerControlInterface';
5
+ import VideoPlayer from "./VideoPlayer.tsx";
6
+ export default VideoPlayer;
@@ -38561,5 +38561,6 @@ function VideoPlayer({
38561
38561
  }
38562
38562
  export {
38563
38563
  VideoPlayer,
38564
- VideoPlayerControl
38564
+ VideoPlayerControl,
38565
+ VideoPlayer as default
38565
38566
  };
@@ -322,4 +322,4 @@ Schedule: ${c.map(T=>segmentToString(T))} pos: ${this.timelinePos}`),f.length&&t
322
322
  `).split(`
323
323
  `),u=[],f=e?toMpegTsClockFromTimescale(e.baseTime,e.timescale):0;let d="00:00.000",g=0,y=0,m,T=!0;o.oncue=function(E){const b=t[i];let A=t.ccOffset;const C=(g-f)/9e4;if(b!=null&&b.new&&(y!==void 0?A=t.ccOffset=b.start:calculateOffset(t,i,C)),C){if(!e){m=new Error("Missing initPTS for VTT MPEGTS");return}A=C-t.presentationOffset}const L=E.endTime-E.startTime,D=normalizePts((E.startTime+A-y)*9e4,s*9e4)/9e4;E.startTime=Math.max(D,0),E.endTime=Math.max(D+L,0);const V=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(V)),E.id||(E.id=generateCueId(E.startTime,E.endTime,V)),E.endTime>0&&u.push(E)},o.onparsingerror=function(E){m=E},o.onflush=function(){if(m){a(m);return}n(u)},c.forEach(E=>{if(T)if(startsWith(E,"X-TIMESTAMP-MAP=")){T=!1,E.slice(16).split(",").forEach(b=>{startsWith(b,"LOCAL:")?d=b.slice(6):startsWith(b,"MPEGTS:")&&(g=parseInt(b.slice(7)))});try{y=cueString2millis(d)/1e3}catch(b){m=b}return}else E===""&&(T=!1);o.parse(E+`
324
324
  `)}),o.flush()}const IMSC1_CODEC="stpp.ttml.im1t",HMSF_REGEX=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,TIME_UNIT_REGEX=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,textAlignToLineAlign={left:"start",center:"center",right:"end",start:"start",end:"end"};function parseIMSC1(r,e,t,i){const s=findBox(new Uint8Array(r),["mdat"]);if(s.length===0){i(new Error("Could not parse IMSC1 mdat"));return}const n=s.map(o=>utf8ArrayToStr(o)),a=toTimescaleFromScale(e.baseTime,1,e.timescale);try{n.forEach(o=>t(parseTTML(o,a)))}catch(o){i(o)}}function parseTTML(r,e){const s=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(n).reduce((d,g)=>(d[g]=s.getAttribute(`ttp:${g}`)||n[g],d),{}),o=s.getAttribute("xml:space")!=="preserve",c=collectionToDictionary(getElementCollection(s,"styling","style")),u=collectionToDictionary(getElementCollection(s,"layout","region")),f=getElementCollection(s,"body","[begin]");return[].map.call(f,d=>{const g=getTextContent(d,o);if(!g||!d.hasAttribute("begin"))return null;const y=parseTtmlTime(d.getAttribute("begin"),a),m=parseTtmlTime(d.getAttribute("dur"),a);let T=parseTtmlTime(d.getAttribute("end"),a);if(y===null)throw timestampParsingError(d);if(T===null){if(m===null)throw timestampParsingError(d);T=y+m}const E=new VTTCue(y-e,T-e,g);E.id=generateCueId(E.startTime,E.endTime,E.text);const b=u[d.getAttribute("region")],A=c[d.getAttribute("style")],C=getTtmlStyles(b,A,c),{textAlign:L}=C;if(L){const D=textAlignToLineAlign[L];D&&(E.lineAlign=D),E.align=L}return _extends(E,C),E}).filter(d=>d!==null)}function getElementCollection(r,e,t){const i=r.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(t)):[]}function collectionToDictionary(r){return r.reduce((e,t)=>{const i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function getTextContent(r,e){return[].slice.call(r.childNodes).reduce((t,i,s)=>{var n;return i.nodeName==="br"&&s?t+`
325
- `:(n=i.childNodes)!=null&&n.length?getTextContent(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function getTtmlStyles(r,e,t){const i="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),n.reduce((o,c)=>{const u=getAttributeNS(e,i,c)||getAttributeNS(r,i,c)||getAttributeNS(s,i,c);return u&&(o[c]=u),o},{})}function getAttributeNS(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function timestampParsingError(r){return new Error(`Could not parse ttml timestamp ${r}`)}function parseTtmlTime(r,e){if(!r)return null;let t=parseTimeStamp(r);return t===null&&(HMSF_REGEX.test(r)?t=parseHoursMinutesSecondsFrames(r,e):TIME_UNIT_REGEX.test(r)&&(t=parseTimeUnits(r,e))),t}function parseHoursMinutesSecondsFrames(r,e){const t=HMSF_REGEX.exec(r),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function parseTimeUnits(r,e){const t=TIME_UNIT_REGEX.exec(r),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class OutputFilter{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class TimelineController{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Events.FRAG_LOADING,this.onFragLoading,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this),e.on(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Events.FRAG_LOADING,this.onFragLoading,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this),e.off(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new OutputFilter(this,"textTrack1"),t=new OutputFilter(this,"textTrack2"),i=new OutputFilter(this,"textTrack3"),s=new OutputFilter(this,"textTrack4");this.cea608Parser1=new Cea608Parser(1,e,t),this.cea608Parser2=new Cea608Parser(3,i,s)}addCues(e,t,i,s,n){let a=!1;for(let o=n.length;o--;){const c=n[o],u=intersection(c[0],c[1],t,i);if(u>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],i),a=!0,u/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,i,s)}else{const o=this.Cues.newCue(null,t,i,s);this.hls.trigger(Events.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n,trackId:a}){const{unparsedVttFrags:o}=this;i===PlaylistLevelType.MAIN&&(this.initPTS[t.cc]={baseTime:s,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(Events.FRAG_LOADED,c):this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const n=i.textTracks[s];if(canReuseVttTextTrack(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)i[e]=o,clearCurrentCues(i[e]),sendAddTrackEvent(i[e],s);else{const c=this.createTextTrack("captions",n,a);c&&(c[e]=!0,i[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach(n=>{clearCurrentCues(s[n]),delete s[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;i<t.length;i++)clearCurrentCues(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some(n=>n.textCodec===IMSC1_CODEC);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(subtitleOptionsIdentical(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,o=a?filterSubtitleTracks(a.textTracks):null;if(this.tracks.forEach((c,u)=>{let f;if(o){let d=null;for(let g=0;g<o.length;g++)if(o[g]&&canReuseVttTextTrack(o[g],c)){d=o[g],o[g]=null;break}d&&(f=d)}if(f)clearCurrentCues(f);else{const d=captionsOrSubtitlesFromCharacteristics(c);f=this.createTextTrack(d,c.name,c.lang),f&&(f.mode="disabled")}f&&this.textTracks.push(f)}),o!=null&&o.length){const c=o.filter(u=>u!==null).map(u=>u.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===PlaylistLevelType.MAIN){var i,s;const{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:c,sn:u}=t.frag,f=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;n&&a&&(u!==o+1||u===o&&f!==this.lastPartIndex+1||c!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=c,this.lastSn=u,this.lastPartIndex=f}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===PlaylistLevelType.SUBTITLE)if(s.byteLength){const n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){const o=this.tracks[i.level],c=this.vttCCs;c[i.cc]||(c[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===IMSC1_CODEC?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;parseIMSC1(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{i.logger.log(`Failed to parse IMSC1: ${s}`),i.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}const c=this.hls,u=(t=i.initSegment)!=null&&t.data?appendUint8Array(i.initSegment.data,new Uint8Array(s)).buffer:s;parseWebVTT(u,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,f=>{this._appendCues(f,i.level),c.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},f=>{const d=f.message==="Missing initPTS for VTT MPEGTS";d?a.push(e):this._fallbackToIMSC1(i,s),c.logger.log(`Failed to parse VTT cue: ${f}`),!(d&&o>i.cc)&&c.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:f})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||parseIMSC1(t,this.initPTS[e.cc],()=>{i.textCodec=IMSC1_CODEC,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(n=>addCueToTrack(s,n))}else{const s=this.tracks[t];if(!s)return;const n=s.default?"default":"subtitles"+t;i.trigger(Events.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===PlaylistLevelType.SUBTITLE&&this.onFragLoaded(Events.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=t;if(!(i.type===PlaylistLevelType.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<s.length;n++){const a=s[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(s[n].pts,o[0]),this.cea608Parser2.addData(s[n].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:n}){const{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(c=>removeCuesInRange(o[c],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>removeCuesInRange(o[c],t,s))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let s=2;for(let n=0;n<i;n++){const a=e[s++],o=127&e[s++],c=127&e[s++];if(o===0&&c===0)continue;if((4&a)!==0){const f=3&a;(f===0||f===1)&&(t[f].push(o),t[f].push(c))}}return t}}function captionsOrSubtitlesFromCharacteristics(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function canReuseVttTextTrack(r,e){return!!r&&r.kind===captionsOrSubtitlesFromCharacteristics(e)&&subtitleTrackMatchesTextTrack(e,r)}function intersection(r,e,t,i){return Math.min(e,i)-Math.max(r,t)}function newVTTCCs(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const WHITESPACE_CHAR=/\s/,Cues={newCue(r,e,t,i){const s=[];let n,a,o,c,u;const f=self.VTTCue||self.TextTrackCue;for(let g=0;g<i.rows.length;g++)if(n=i.rows[g],o=!0,c=0,u="",!n.isEmpty()){var d;for(let T=0;T<n.chars.length;T++)WHITESPACE_CHAR.test(n.chars[T].uchar)&&o?c++:(u+=n.chars[T].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const y=fixLineBreaks(u.trim()),m=generateCueId(e,t,y);r!=null&&(d=r.cues)!=null&&d.getCueById(m)||(a=new f(e,t,y),a.id=m,a.line=g+1,a.align="left",a.position=10+Math.min(80,Math.floor(c*8/32)*10),s.push(a))}return r&&s.length&&(s.sort((g,y)=>g.line==="auto"||y.line==="auto"?0:g.line>8&&y.line>8?y.line-g.line:g.line-y.line),s.forEach(g=>addCueToTrack(r,g))),s}};function fetchSupported(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const BYTERANGE=/(\d+)-(\d+)\/(\d+)/;class FetchLoader{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||getRequest,this.controller=new self.AbortController,this.stats=new LoadStats}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 n=getRequestParameters(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=c&&isFiniteNumber(c)?c:u,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},t.timeout),(isPromise(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var g;this.response=this.loader=d;const y=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},u-(y-s.loading.start)),!d.ok){const{status:T,statusText:E}=d;throw new FetchError(E||"fetch, bad network response",T,d)}s.loading.first=y,s.total=getContentLength(d.headers)||s.total;const m=(g=this.callbacks)==null?void 0:g.onProgress;return m&&isFiniteNumber(t.highWaterMark)?this.loadProgressively(d,s,e,t.highWaterMark,m):a?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var g,y;const m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const T=d[o];T&&(s.loaded=s.total=T);const E={url:m.url,data:d,code:m.status},b=(g=this.callbacks)==null?void 0:g.onProgress;b&&!isFiniteNumber(t.highWaterMark)&&b(s,e,d,m),(y=this.callbacks)==null||y.onSuccess(E,s,e,m)}).catch(d=>{var g;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const y=d&&d.code||0,m=d?d.message:null;(g=this.callbacks)==null||g.onError({code:y,text:m},e,d?d.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,n){const a=new ChunkCache,o=e.body.getReader(),c=()=>o.read().then(u=>{if(u.done)return a.dataLength&&n(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const f=u.value,d=f.length;return t.loaded+=d,d<s||a.dataLength?(a.push(f),a.dataLength>=s&&n(t,i,a.flush().buffer,e)):n(t,i,f.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function getRequestParameters(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(_extends({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function getByteRangeLength(r){const e=BYTERANGE.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function getContentLength(r){const e=r.get("Content-Range");if(e){const i=getByteRangeLength(e);if(isFiniteNumber(i))return i}const t=r.get("Content-Length");if(t)return parseInt(t)}function getRequest(r,e){return new self.Request(r.url,e)}class FetchError extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const AGE_HEADER_LINE_REGEX=/^age:\s*[\d.]+\s*$/im;class XhrLoader{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 LoadStats,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,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 n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.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:n,maxLoadTimeMs:a}=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=n&&isFiniteNumber(n)?n:a,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,n=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const u=t.status,f=t.responseType==="text"?t.responseText:null;if(u>=200&&u<300){const m=f??t.response;if(m!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);const T=t.responseType==="arraybuffer"?m.byteLength:m.length;i.loaded=i.total=T,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const E=(a=this.callbacks)==null?void 0:a.onProgress;E&&E(i,e,m,t);const b={url:t.responseURL,data:m,code:u};(o=this.callbacks)==null||o.onSuccess(b,i,e,t);return}}const d=n.loadPolicy.errorRetry,g=i.retry,y={url:e.url,data:void 0,code:u};if(shouldRetry(d,g,!1,y))this.retry(d);else{var c;logger.error(`${u} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:u,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(shouldRetry(e,t,!0))this.retry(e);else{var i;logger.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=getRetryDelay(e,i.retry),i.retry++,logger.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&&AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const defaultLoadPolicy={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},hlsDefaultConfig=_objectSpread2(_objectSpread2({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,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,ignorePlaylistParsingErrors:!1,loader:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:AbrController,bufferController:BufferController,capLevelController:CapLevelController,errorController:ErrorController,fpsController:FPSController,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:requestMediaKeySystemAccess,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:defaultLoadPolicy},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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,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},timelineConfig()),{},{subtitleStreamController:SubtitleStreamController,subtitleTrackController:SubtitleTrackController,timelineController:TimelineController,audioStreamController:AudioStreamController,audioTrackController:AudioTrackController,emeController:EMEController,cmcdController:CMCDController,contentSteeringController:ContentSteeringController,interstitialsController:InterstitialsController});function timelineConfig(){return{cueHandler:Cues,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function mergeConfig(r,e,t){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 i=deepCpy(r),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,c=e[o]===void 0,u=[];n.forEach(f=>{const d=`${a}Loading${f}`,g=e[d];if(g!==void 0&&c){u.push(d);const y=i[o].default;switch(e[o]={default:y},f){case"TimeOut":y.maxLoadTimeMs=g,y.maxTimeToFirstByteMs=g;break;case"MaxRetry":y.errorRetry.maxNumRetry=g,y.timeoutRetry.maxNumRetry=g;break;case"RetryDelay":y.errorRetry.retryDelayMs=g,y.timeoutRetry.retryDelayMs=g;break;case"MaxRetryTimeout":y.errorRetry.maxRetryDelayMs=g,y.timeoutRetry.maxRetryDelayMs=g;break}}}),u.length&&t.warn(`hls.js config: "${u.join('", "')}" setting(s) are deprecated, use "${o}": ${stringify(e[o])}`)}),_objectSpread2(_objectSpread2({},i),e)}function deepCpy(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(deepCpy):Object.keys(r).reduce((e,t)=>(e[t]=deepCpy(r[t]),e),{}):r}function enableStreamingMode(r,e){const t=r.loader;t!==FetchLoader&&t!==XhrLoader?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):fetchSupported()&&(r.loader=FetchLoader,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const MAX_START_GAP_JUMP=2,SKIP_BUFFER_HOLE_STEP_SECONDS=.1,SKIP_BUFFER_RANGE_START=.05,TICK_INTERVAL$1=100;class GapController extends TaskLoop{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(Events.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(TICK_INTERVAL$1),this.mediaSource=t.mediaSource;const i=this.media=t.media;addEventListener(i,"playing",this.onMediaPlaying),addEventListener(i,"waiting",this.onMediaWaiting),addEventListener(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(removeEventListener(i,"playing",this.onMediaPlaying),removeEventListener(i,"waiting",this.onMediaWaiting),removeEventListener(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,s;const n=(i=this.hls)==null?void 0:i.config;if(!n)return;const a=this.media;if(!a)return;const{seeking:o}=a,c=this.seeking&&!o,u=!this.seeking&&o,f=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!f&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(u||c){c&&this.stallResolved(e);return}if(f){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(Events.MEDIA_ENDED,{stalled:!1}));return}if(!BufferHelper.getBuffered(a).length){this.nudgeRetry=0;return}const d=BufferHelper.bufferInfo(a,e,0),g=d.nextStart||0,y=this.fragmentTracker;if(o&&y&&this.hls){const V=getInFlightDependency(this.hls.inFlightFragments,e),M=d.len>MAX_START_GAP_JUMP,N=!g||V||g-e>MAX_START_GAP_JUMP&&!y.getPartialFragment(e);if(M||N)return;this.moved=!1}const m=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&y){if(!(d.len>0)&&!g)return;const M=Math.max(g,d.start||0)-e,F=!!(m!=null&&m.live)?m.targetduration*2:MAX_START_GAP_JUMP,O=appendedFragAtPosition(e,y);if(M>0&&(M<=F||O)){a.paused||this._trySkipBufferHole(O);return}}const T=n.detectStallWithCurrentTimeMs,E=self.performance.now(),b=this.waiting;let A=this.stalled;if(A===null)if(b>0&&E-b<T)A=this.stalled=b;else{this.stalled=E;return}const C=E-A;if(!o&&(C>=T||b)&&this.hls){var L;if(((L=this.mediaSource)==null?void 0:L.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-(m?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(Events.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}const D=BufferHelper.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(D,C,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Events.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&e>s.end(0)){const n=BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){const a=BufferHelper.timeRangesToArray(s),o=BufferHelper.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const c=BufferHelper.bufferedInfo(a,e,0).bufferedIndex,u=a[o].end,f=a[o+1].start;if((c===-1||c>o)&&f-u<1&&e-u<2){const d=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${u} -> ${f} buffered index: ${c}`);this.warn(d.message),this.media.currentTime+=1e-6;let g=appendedFragAtPosition(e,this.fragmentTracker);g&&"fragment"in g?g=g.fragment:g||(g=void 0);const y=BufferHelper.bufferInfo(this.media,e,0);this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:g,buffer:y.len,bufferInfo:y})}}}}}_tryFixBufferStall(e,t,i){var s,n;const{fragmentTracker:a,media:o}=this,c=(s=this.hls)==null?void 0:s.config;if(!o||!a||!c)return;const u=(n=this.hls)==null?void 0:n.latestLevelDetails,f=appendedFragAtPosition(i,a);if((f||u!=null&&u.live&&i<u.fragmentStart)&&(this._trySkipBufferHole(f)||!this.media))return;const d=e.buffered,g=this.adjacentTraversal(e,i);(d&&d.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-i<c.maxBufferHole||g))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,s=e.nextStart;if(i&&s){const n=i.getFragAtPos(t,PlaylistLevelType.MAIN),a=i.getFragAtPos(s,PlaylistLevelType.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:n}=this;if(!s&&n!==null&&i&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${stringify(e)})`);this.warn(a.message),t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:s}=this,n=(t=this.hls)==null?void 0:t.config;if(!s||!i||!n)return 0;const a=s.currentTime,o=BufferHelper.bufferInfo(s,a,0),c=a<o.start?o.start:o.nextStart;if(c&&this.hls){const f=o.len<=n.maxBufferHole,d=o.len>0&&o.len<1&&s.readyState<3,g=c-a;if(g>0&&(f||d)){if(g>n.maxBufferHole){let m=!1;if(a===0){const T=i.getAppendedFrag(0,PlaylistLevelType.MAIN);T&&c<T.end&&(m=!0)}if(!m&&e){var u;if(!((u=this.hls.loadLevelObj)!=null&&u.details)||getInFlightDependency(this.hls.inFlightFragments,c))return 0;let E=!1,b=e.end;for(;b<c;){const A=appendedFragAtPosition(b,i);if(A)b+=A.duration;else{E=!0;break}}if(E)return 0}}const y=Math.max(c+SKIP_BUFFER_RANGE_START,a+SKIP_BUFFER_HOLE_STEP_SECONDS);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${y}`),this.moved=!0,s.currentTime=y,!(e!=null&&e.gap)){const m=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${y}`),T={type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?T.part=e:T.frag=e),this.hls.trigger(Events.ERROR,T)}return y}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:s}=this,n=t?.config;if(!i||!n)return 0;const a=i.currentTime;if(this.nudgeRetry++,s<n.nudgeMaxRetry){const o=a+(s+1)*n.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(c.message),i.currentTime=o,t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function getInFlightDependency(r,e){const t=inFlight(r.main);if(t&&t.start<=e)return t;const i=inFlight(r.audio);return i&&i.start<=e?i:null}function inFlight(r){if(!r)return null;switch(r.state){case State.IDLE:case State.STOPPED:case State.ENDED:case State.ERROR:return null}return r.frag}function appendedFragAtPosition(r,e){return e.getAppendedFrag(r,PlaylistLevelType.MAIN)||e.getPartialFragment(r)}const MIN_CUE_DURATION=.25;function getCueClass(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function createCueWithDataFields(r,e,t,i,s){let n=new r(e,t,"");try{n.value=i,s&&(n.type=s)}catch{n=new r(e,t,stringify(s?_objectSpread2({type:s},i):i))}return n}const MAX_CUE_ENDTIME=(()=>{const r=getCueClass();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class ID3TrackController{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(Events.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&clearCurrentCues(this.id3Track,this.onEventCueEnter),this.id3Track=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 sendAddTrackEvent(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=getCueClass();if(a)for(let o=0;o<n.length;o++){const c=n[o].type;if(c===MetadataSchema.emsg&&!i||!s)continue;const u=getId3Frames(n[o].data),f=n[o].pts;let d=f+n[o].duration;d>MAX_CUE_ENDTIME&&(d=MAX_CUE_ENDTIME),d-f<=0&&(d=f+MIN_CUE_DURATION);for(let y=0;y<u.length;y++){const m=u[y];if(!isId3TimestampFrame(m)){this.updateId3CueEnds(f,c);const T=createCueWithDataFields(a,f,d,m,c);T&&this.id3Track.addCue(T)}}}}updateId3CueEnds(e,t){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let n=s.length;n--;){const a=s[n];a.type===t&&a.startTime<e&&a.endTime===MAX_CUE_ENDTIME&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=a;if(n&&(o||c)){let u;s==="audio"?u=f=>f.type===MetadataSchema.audioId3&&c:s==="video"?u=f=>f.type===MetadataSchema.emsg&&o:u=f=>f.type===MetadataSchema.audioId3&&c||f.type===MetadataSchema.emsg&&o,removeCuesInRange(n,t,i,u)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=getCueClass();if(i&&s&&!a){const{fragmentStart:T,fragmentEnd:E}=e;let b=this.assetCue;b?(b.startTime=T,b.endTime=E):o&&(b=this.assetCue=createCueWithDataFields(o,T,E,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),b&&(b.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(b),b.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:u}=e,f=Object.keys(u);let d=this.dateRangeCuesAppended;if(c&&t){var g;if((g=c.cues)!=null&&g.length){const T=Object.keys(d).filter(E=>!f.includes(E));for(let E=T.length;E--;){var y;const b=T[E],A=(y=d[b])==null?void 0:y.cues;delete d[b],A&&Object.keys(A).forEach(C=>{const L=A[C];if(L){L.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(L)}catch{}}})}}else d=this.dateRangeCuesAppended={}}const m=e.fragments[e.fragments.length-1];if(!(f.length===0||!isFiniteNumber(m?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let T=0;T<f.length;T++){const E=f[T],b=u[E],A=b.startTime,C=d[E],L=C?.cues||{};let D=C?.durationKnown||!1,V=MAX_CUE_ENDTIME;const{duration:M,endDate:N}=b;if(N&&M!==null)V=A+M,D=!0;else if(b.endOnNext&&!D){const O=f.reduce(($,Q)=>{if(Q!==b.id){const J=u[Q];if(J.class===b.class&&J.startDate>b.startDate&&(!$||b.startDate<$.startDate))return J}return $},null);O&&(V=O.startTime,D=!0)}const F=Object.keys(b.attr);for(let O=0;O<F.length;O++){const $=F[O];if(!isDateRangeCueAttribute($))continue;const Q=L[$];if(Q)D&&!(C!=null&&C.durationKnown)?Q.endTime=V:Math.abs(Q.startTime-A)>.01&&(Q.startTime=A,Q.endTime=V);else if(o){let J=b.attr[$];isSCTE35Attribute($)&&(J=hexToArrayBuffer(J));const ae=createCueWithDataFields(o,A,V,{key:$,data:J},MetadataSchema.dateRange);ae&&(ae.id=E,this.id3Track.addCue(ae),L[$]=ae,a&&($==="X-ASSET-LIST"||$==="X-ASSET-URL")&&ae.addEventListener("enter",this.onEventCueEnter))}}d[E]={cues:L,dateRange:b,durationKnown:D}}}}}class LatencyController{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(s===null)return;this._latency=s;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!i.live)return;const o=this.targetLatency;if(o===null)return;const c=s-o,u=Math.min(this.maxLatency,o+i.targetduration);if(c<u&&c>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,a)),g=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,y=Math.min(d,Math.max(1,g));this.changeMediaPlaybackRate(t,y)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let u=o&&i||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||u===0)&&(u=n!==void 0?n:a*s);const f=s;return u+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,f)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const i=this.levelDetails;if(i===null)return null;const s=i.edge,n=e-t-this.edgeStalled,a=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;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}=this,t=this.levelDetails;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.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===ErrorDetails.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class LevelController extends BasePlaylistController{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(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.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=[],n={},a={};let o=!1,c=!1,u=!1;t.levels.forEach(f=>{const d=f.attrs;let{audioCodec:g,videoCodec:y}=f;g&&(f.audioCodec=g=getCodecCompatibleName(g,i)||void 0),y&&(y=f.videoCodec=convertAVC1ToAVCOTI(y));const{width:m,height:T,unknownCodecs:E}=f,b=E?.length||0;if(o||(o=!!(m&&T)),c||(c=!!y),u||(u=!!g),b||g&&!this.isAudioSupported(g)||y&&!this.isVideoSupported(y)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}const{CODECS:A,"FRAME-RATE":C,"HDCP-LEVEL":L,"PATHWAY-ID":D,RESOLUTION:V,"VIDEO-RANGE":M}=d,F=`${`${D||"."}-`}${f.bitrate}-${V}-${C}-${A}-${M}-${L}`;if(n[F])if(n[F].uri!==f.url&&!f.attrs["PATHWAY-ID"]){const O=a[F]+=1;f.attrs["PATHWAY-ID"]=new Array(O+1).join(".");const $=this.createLevel(f);n[F]=$,s.push($)}else n[F].addGroupId("audio",d.AUDIO),n[F].addGroupId("text",d.SUBTITLES);else{const O=this.createLevel(f);n[F]=O,a[F]=1,s.push(O)}}),this.filterAndSortMediaOptions(s,t,o,c,u)}createLevel(e){const t=new Level(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=getUnsupportedResult(s,[])}return t}isAudioSupported(e){return areCodecsMediaSourceSupported(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return areCodecsMediaSourceSupported(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,n){var a;let o=[],c=[],u=e;const f=((a=t.stats)==null?void 0:a.parsing)||{};if((i||s)&&n&&(u=u.filter(({videoCodec:A,videoRange:C,width:L,height:D})=>(!!A||!!(L&&D))&&isVideoRange(C))),u.length===0){Promise.resolve().then(()=>{if(this.hls){let A="no level with compatible codecs found in manifest",C=A;t.levels.length&&(C=`one or more CODECS in variant not supported: ${stringify(t.levels.map(D=>D.attrs.CODECS).filter((D,V,M)=>M.indexOf(D)===V))}`,this.warn(C),A+=` (${C})`);const L=new Error(A);this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:L,reason:C})}}),f.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(A=>!A.audioCodec||this.isAudioSupported(A.audioCodec)),assignTrackIdsByGroup(o)),t.subtitles&&(c=t.subtitles,assignTrackIdsByGroup(c));const d=u.slice(0);u.sort((A,C)=>{if(A.attrs["HDCP-LEVEL"]!==C.attrs["HDCP-LEVEL"])return(A.attrs["HDCP-LEVEL"]||"")>(C.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&A.height!==C.height)return A.height-C.height;if(A.frameRate!==C.frameRate)return A.frameRate-C.frameRate;if(A.videoRange!==C.videoRange)return VideoRangeValues.indexOf(A.videoRange)-VideoRangeValues.indexOf(C.videoRange);if(A.videoCodec!==C.videoCodec){const L=videoCodecPreferenceValue(A.videoCodec),D=videoCodecPreferenceValue(C.videoCodec);if(L!==D)return D-L}if(A.uri===C.uri&&A.codecSet!==C.codecSet){const L=codecsSetSelectionPreferenceValue(A.codecSet),D=codecsSetSelectionPreferenceValue(C.codecSet);if(L!==D)return D-L}return A.averageBitrate!==C.averageBitrate?A.averageBitrate-C.averageBitrate:0});let g=d[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==d.length)){for(let A=0;A<d.length;A++)if(d[A].pathwayId===u[0].pathwayId){g=d[A];break}}this._levels=u;for(let A=0;A<u.length;A++)if(u[A]===g){var y;this._firstLevel=A;const C=g.bitrate,L=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${C}`),((y=this.hls.userConfig)==null?void 0:y.abrEwmaDefaultEstimate)===void 0){const D=Math.min(C,this.hls.config.abrEwmaDefaultEstimateMax);D>L&&L===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=D)}break}const m=n&&!s,T=this.hls.config,E=!!(T.audioStreamController&&T.audioTrackController),b={levels:u,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:E&&!m&&o.some(A=>!!A.url)};f.end=performance.now(),this.hls.trigger(Events.MANIFEST_PARSED,b)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const f=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:f,reason:f.message}),d)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&s&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);const c={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(Events.LEVEL_SWITCHING,c);const u=a.details;if(!u||u.live){const f=this.switchParams(a.uri,s?.details,u);this.loadPlaylist(f)}}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}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter(s=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===PlaylistContextType.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===PlaylistLevelType.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))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:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let c=a.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(s,t,c)}else(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(Events.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||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;if(this._levels.length===1)return;const i=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));reassignFragmentLevelIndexes(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(Events.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(Events.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function assignTrackIdsByGroup(r){const e={};r.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function getSourceBuffer(){return self.SourceBuffer||self.WebKitSourceBuffer}function isMSESupported(){if(!getMediaSource())return!1;const e=getSourceBuffer();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function isSupported(){if(!isMSESupported())return!1;const r=getMediaSource();return typeof r?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(mimeTypeForCodec(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(mimeTypeForCodec(e,"audio"))))}function changeTypeSupported(){var r;const e=getSourceBuffer();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}const TICK_INTERVAL=100;class StreamController extends BaseStreamController{constructor(e,t,i){super(e,t,i,"stream-controller",PlaylistLevelType.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const s=this.media,n=s?s.currentTime:null;if(n===null||!isFiniteNumber(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;const a=this.getFwdBufferInfoAtPos(s,n,PlaylistLevelType.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this),e.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this),e.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(TICK_INTERVAL),this.level=-1,!this.startFragRequested){let n=s.startLevel;n===-1&&(s.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=s.firstAutoLevel),s.nextLoadLevel=n,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=State.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=State.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case State.WAITING_LEVEL:{const{levels:e,level:t}=this,i=e?.[t],s=i?.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=State.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=State.IDLE;break}break}case State.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===State.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;const a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const T={};this.altAudio===2&&(T.type="video"),this.hls.trigger(Events.BUFFER_EOS,T),this.state=State.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const u=a.details;if(!u||this.state===State.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=State.WAITING_LEVEL,this.startFragRequested=!1;return}const f=o.len,d=this.getMaxBufferLength(a.maxBitrate);if(f>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const g=this.backtrackFragment?this.backtrackFragment.start:o.end;let y=this.getNextFragment(g,u);if(this.couldBacktrack&&!this.fragPrevious&&y&&isMediaFragment(y)&&this.fragmentTracker.getState(y)!==FragmentState.OK){var m;const E=((m=this.backtrackFragment)!=null?m:y).sn-u.startSN,b=u.fragments[E-1];b&&y.cc===b.cc&&(y=b,this.fragmentTracker.removeFragment(b))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(y&&this.isLoopLoading(y,g)){if(!y.gap){const E=this.audioOnly&&!this.altAudio?ElementaryStreamTypes.AUDIO:ElementaryStreamTypes.VIDEO,b=(E===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;b&&this.afterBufferFlushed(b,E,PlaylistLevelType.MAIN)}y=this.getNextFragmentLoopLoading(y,u,o,PlaylistLevelType.MAIN,d)}y&&(y.initSegment&&!y.initSegment.data&&!this.bitrateTest&&(y=y.initSegment),this.loadFragment(y,a,g))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===FragmentState.NOT_LOADED||s===FragmentState.PARTIAL?isMediaFragment(e)?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)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,PlaylistLevelType.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 n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,c=e[o],u=this.fragLastKbps;u&&this.fragCurrent?i=this.fragCurrent.duration*c.maxBitrate/(1e3*u)+1:i=0}else i=0;const a=this.getBufferedFrag(t.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const c=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,f=Math.max(a.end,c+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(f,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 State.KEY_LOADING:case State.FRAG_LOADING:case State.FRAG_LOADING_WAITING_RETRY:case State.PARSING:case State.PARSED:this.state=State.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;addEventListener(i,"playing",this.onMediaPlaying),addEventListener(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(removeEventListener(i,"playing",this.onMediaPlaying),removeEventListener(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Events.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let n=0;n<t.levels.length;n++){const a=t.levels[n].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&s&&!changeTypeSupported(),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!==State.IDLE)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=State.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:n}=this,a=t.level,o=t.details,c=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);const u=t.levelInfo,f=this.fragCurrent;f&&(this.state===State.FRAG_LOADING||this.state===State.FRAG_LOADING_WAITING_RETRY)&&f.level!==t.level&&f.loader&&this.abortCurrentFrag();let d=0;if(o.live||(i=u.details)!=null&&i.live){var g;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,u.details,(g=this.levelLastLoaded)==null?void 0:g.details)}if(u.details=o,this.levelLastLoaded=u,n||this.setStartPosition(o,d),this.hls.trigger(Events.LEVEL_UPDATED,{details:o,level:a}),this.state===State.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=State.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,c=n>=a-t.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!c)){const f=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&i.readyState<4||n<o-f)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var u;const d=BufferHelper.bufferInfo(i,s,0);if(!((u=d.buffered)!=null&&u.length)){i.currentTime=s;return}if(d.start<=n){i.currentTime=s;return}const{nextStart:y}=BufferHelper.bufferedInfo(d.buffered,n,0);y&&(i.currentTime=y)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}const c=o.details;if(!c){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const u=o.videoCodec,f=c.PTSKnown||!c.live,d=(t=i.initSegment)==null?void 0:t.data,g=this._getAudioCodec(o),y=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,PlaylistLevelType.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=s?s.index:-1,T=m!==-1,E=new ChunkMetadata(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,T),b=this.initPTS[i.cc];y.push(n,d,g,u,i,s,c.totalduration,f,E,b)}onAudioTrackSwitching(e,t){const i=this.hls,s=this.altAudio!==0;if(useAlternateAudio(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(Events.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(Events.AUDIO_TRACK_SWITCHED,t)}),i.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(Events.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=useAlternateAudio(t.url,this.hls);if(i){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,n,a=!1;for(const o in i){const c=i[o];if(c.id==="main"){if(n=o,s=c,o==="video"){const u=i[o];u&&(this.videoBuffer=u.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t,n=i.type===PlaylistLevelType.MAIN;if(n){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===State.PARSED&&(this.state=State.IDLE);return}const o=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),isMediaFragment(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const a=this.media;a&&(!this._hasEnoughToStart&&BufferHelper.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=State.ERROR;return}switch(t.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN,t);break;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===State.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===PlaylistContextType.LEVEL&&(this.state=State.IDLE);break;case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ErrorDetails.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=State.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ElementaryStreamTypes.AUDIO||!this.altAudio){const i=(t===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,PlaylistLevelType.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),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=this.timelineOffset;s&&i&&(i+=s);const n=this.getLevelDetails(),a=BufferHelper.getBuffered(e),o=a.length?a.start(0):0,c=o-i,u=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<u||this.loadingParts&&c<2*(n?.partTarget||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),i+=c,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),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,n=i?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=State.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),s.trigger(Events.FRAG_LOADED,i),n.bitrateTest=!1}).catch(i=>{this.state===State.STOPPED||this.state===State.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}const{frag:o,part:c,level:u}=a,{video:f,text:d,id3:g,initSegment:y}=s,{details:m}=u,T=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=State.PARSING,y){const E=y.tracks;if(E){const L=o.initSegment||o;if(this.unhandledEncryptionError(y,o))return;this._bufferInitSegment(u,E,L,n),i.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:L,id:t,tracks:E})}const b=y.initPTS,A=y.timescale,C=this.initPTS[o.cc];if(isFiniteNumber(b)&&(!C||C.baseTime!==b||C.timescale!==A)){const L=y.trackId;this.initPTS[o.cc]={baseTime:b,timescale:A,trackId:L},i.trigger(Events.INIT_PTS_FOUND,{frag:o,id:t,initPTS:b,timescale:A,trackId:L})}}if(f&&m){T&&f.type==="audiovideo"&&this.logMuxedErr(o);const E=m.fragments[o.sn-1-m.startSN],b=o.sn===m.startSN,A=!E||o.cc>E.cc;if(s.independent!==!1){const{startPTS:C,endPTS:L,startDTS:D,endDTS:V}=f;if(c)c.elementaryStreams[f.type]={startPTS:C,endPTS:L,startDTS:D,endDTS:V};else if(f.firstKeyFrame&&f.independent&&n.id===1&&!A&&(this.couldBacktrack=!0),f.dropped&&f.independent){const M=this.getMainFwdBufferInfo(),N=(M?M.end:this.getLoadPosition())+this.config.maxBufferHole,F=f.firstKeyFramePTS?f.firstKeyFramePTS:C;if(!b&&N<F-this.config.maxBufferHole&&!A){this.backtrack(o);return}else A&&(o.gap=!0);o.setElementaryStreamInfo(f.type,o.start,L,o.start,V,!0)}else b&&C-(m.appliedTimelineOffset||0)>MAX_START_GAP_JUMP&&(o.gap=!0);o.setElementaryStreamInfo(f.type,C,L,D,V),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(f,o,c,n,b||A)}else if(b||A)o.gap=!0;else{this.backtrack(o);return}}if(T){const{startPTS:E,endPTS:b,startDTS:A,endDTS:C}=T;c&&(c.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:E,endPTS:b,startDTS:A,endDTS:C}),o.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,E,b,A,C),this.bufferFragmentData(T,o,c,n)}if(m&&g!=null&&g.samples.length){const E={id:t,frag:o,details:m,samples:g.samples};i.trigger(Events.FRAG_PARSING_METADATA,E)}if(m&&d){const E={id:t,frag:o,details:m,samples:d.samples};i.trigger(Events.FRAG_PARSING_USERDATA,E)}}logMuxedErr(e){this.warn(`${isMediaFragment(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==State.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:n,video:a,audiovideo:o}=t;if(n){const u=e.audioCodec;let f=pickMostCompleteCodecName(n.codec,u);f==="mp4a"&&(f="mp4a.40.5");const d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){f&&(f.indexOf("mp4a.40.5")!==-1?f="mp4a.40.2":f="mp4a.40.5");const g=n.metadata;g&&"channelCount"in g&&(g.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(f="mp4a.40.5")}f&&f.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(f="mp4a.40.2",this.log(`Android: force audio codec to ${f}`)),u&&u!==f&&this.log(`Swapping manifest audio codec "${u}" for "${f}"`),n.levelCodec=f,n.id=PlaylistLevelType.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${f||""}/${u||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=PlaylistLevelType.MAIN;const u=a.codec;if(u?.length===4)switch(u){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${u}]${a.codec!==u?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(Events.BUFFER_CODECS,t),!this.hls)return;c.forEach(u=>{const d=t[u].initSegment;d!=null&&d.byteLength&&this.hls.trigger(Events.BUFFER_APPENDING,{type:u,data:d,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,PlaylistLevelType.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}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=State.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(BufferHelper.isBuffered(e,i)?t=this.getAppendedFrag(i):BufferHelper.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const s=this.fragPlaying,n=t.level;(!s||t.sn!==s.sn||s.level!==n)&&(this.fragPlaying=t,this.hls.trigger(Events.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(Events.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return isFiniteNumber(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(isFiniteNumber(t)){const i=this.getLevelDetails(),s=this.currentFrag||(i?findFragmentByPTS(null,i.fragments,t):null);if(s){const n=s.programDateTime;if(n!==null){const a=n+(t-s.start)*1e3;return new Date(a)}}}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 KeyLoader extends Logger{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[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.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=ErrorDetails.KEY_LOAD_ERROR,i,s,n){return new LoadError({type:ErrorTypes.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:s})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,n=t.length;s<n;s++){const a=t[s];if(e.cc<=a.cc&&(!isMediaFragment(e)||!isMediaFragment(a)||e.sn<a.sn)||!i&&s==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const c=keySystemFormatToKeySystemDomain(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const s=getKeySystemsForConfig(this.config);if(s.length)return this.emeController.getKeySystemAccess(s)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const u=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,u))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=getKeyId(n);let c=this.keyIdToKeyInfo[o];if((i=c)!=null&&i.decryptdata.key)return n.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(s=c)!=null&&s.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(f=>{const{keyInfo:d}=f;return n.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+arrayToHex(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var s;if(!e.decryptdata.keyId&&(s=t.initSegment)!=null&&s.data){const a=parseKeyIdsFromTenc(t.initSegment.data);if(a.length){let o=a[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${arrayToHex(o)}`),LevelKey.setKeyIdForUri(e.decryptdata.uri,o)):(o=LevelKey.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${arrayToHex(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!isMediaFragment(t))return Promise.resolve(i);const n=this.emeController.loadKey(i);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,i))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=i.loader,n=new s(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},u=i.keyLoadPolicy.default,f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(g,y,m,T)=>{const{frag:E,keyInfo:b}=m,A=getKeyId(b.decryptdata);if(!E.decryptdata||b!==this.keyIdToKeyInfo[A])return o(this.createKeyLoadError(E,ErrorDetails.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),T));b.decryptdata.key=E.decryptdata.key=new Uint8Array(g.data),E.keyLoader=null,b.loader=null,a({frag:E,keyInfo:b})},onError:(g,y,m,T)=>{this.resetLoader(y),o(this.createKeyLoadError(t,ErrorDetails.KEY_LOAD_ERROR,new Error(`HTTP Error ${g.code} loading key ${g.text}`),m,_objectSpread2({url:c.url,data:void 0},g)))},onTimeout:(g,y,m)=>{this.resetLoader(y),o(this.createKeyLoadError(t,ErrorDetails.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(g,y,m)=>{this.resetLoader(y),o(this.createKeyLoadError(t,ErrorDetails.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(c,f,d)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null);const a=getKeyId(i.decryptdata)||s;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}function getKeyId(r){if(r.keyFormat!==KeySystemFormats.FAIRPLAY){const e=r.keyId;if(e)return arrayToHex(e)}return r.uri}function mapContextToLevelType(r){const{type:e}=r;switch(e){case PlaylistContextType.AUDIO_TRACK:return PlaylistLevelType.AUDIO;case PlaylistContextType.SUBTITLE_TRACK:return PlaylistLevelType.SUBTITLE;default:return PlaylistLevelType.MAIN}}function getResponseUrl(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class PlaylistLoader{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,n=i||s,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:PlaylistContextType.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:c}=t;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:PlaylistContextType.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:PlaylistContextType.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:PlaylistContextType.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const i=this.loaders[PlaylistContextType.LEVEL];if(i){const s=i.context;s&&!t.levels.some(n=>n===s.levelOrTrack)&&(i.abort(),delete this.loaders[PlaylistContextType.LEVEL])}}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const u=this.hls.logger,f=s.context;if(f&&f.levelOrTrack===e.levelOrTrack&&(f.url===e.url||f.deliveryDirectives&&!e.deliveryDirectives)){f.url===e.url?u.log(`[playlist-loader]: ignore ${e.url} ongoing request`):u.log(`[playlist-loader]: ignore ${e.url} in favor of ${f.url}`);return}u.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===PlaylistContextType.MANIFEST?n=i.manifestLoadPolicy.default:n=_extends({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),isFiniteNumber((t=e.deliveryDirectives)==null?void 0:t.part)){let u;if(e.type===PlaylistContextType.LEVEL&&e.level!==null?u=this.hls.levels[e.level].details:e.type===PlaylistContextType.AUDIO_TRACK&&e.id!==null?u=this.hls.audioTracks[e.id].details:e.type===PlaylistContextType.SUBTITLE_TRACK&&e.id!==null&&(u=this.hls.subtitleTracks[e.id].details),u){const f=u.partTarget,d=u.targetduration;if(f&&d){const g=Math.max(f*3,d*.8)*1e3;n=_extends({},n,{maxTimeToFirstByteMs:Math.min(g,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(g,n.maxTimeToFirstByteMs)})}}}const a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(u,f,d,g)=>{const y=this.getInternalLoader(d);this.resetInternalLoader(d.type);const m=u.data;f.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(m)||d.type!==PlaylistContextType.MANIFEST?this.handleTrackOrLevelPlaylist(u,f,d,g||null,y):this.handleMasterPlaylist(u,f,d,g)},onError:(u,f,d,g)=>{this.handleNetworkError(f,d,!1,u,g)},onTimeout:(u,f,d)=>{this.handleNetworkError(f,d,!0,void 0,u)}};s.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){const n=this.hls,a=e.data,o=getResponseUrl(e,i),c=M3U8Parser.parseMasterPlaylist(a,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,c.playlistParsingError,s,t);return}const{contentSteering:u,levels:f,sessionData:d,sessionKeys:g,startTimeOffset:y,variableList:m}=c;this.variableList=m,f.forEach(A=>{const{unknownCodecs:C}=A;if(C){const{preferManagedMediaSource:L}=this.hls.config;let{audioCodec:D,videoCodec:V}=A;for(let M=C.length;M--;){const N=C[M];areCodecsMediaSourceSupported(N,"audio",L)?(A.audioCodec=D=D?`${D},${N}`:N,sampleEntryCodesISO.audio[D.substring(0,4)]=2,C.splice(M,1)):areCodecsMediaSourceSupported(N,"video",L)&&(A.videoCodec=V=V?`${V},${N}`:N,sampleEntryCodesISO.video[V.substring(0,4)]=2,C.splice(M,1))}}});const{AUDIO:T=[],SUBTITLES:E,"CLOSED-CAPTIONS":b}=M3U8Parser.parseMasterPlaylistMedia(a,o,c);T.length&&!T.some(C=>!C.url)&&f[0].audioCodec&&!f[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),T.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new AttrList({}),bitrate:0,url:""})),n.trigger(Events.MANIFEST_LOADED,{levels:f,audioTracks:T,subtitles:E,captions:b,contentSteering:u,url:o,stats:t,networkDetails:s,sessionData:d,sessionKeys:g,startTimeOffset:y,variableList:m})}handleTrackOrLevelPlaylist(e,t,i,s,n){const a=this.hls,{id:o,level:c,type:u}=i,f=getResponseUrl(e,i),d=isFiniteNumber(c)?c:isFiniteNumber(o)?o:0,g=mapContextToLevelType(i),y=M3U8Parser.parseLevelPlaylist(e.data,f,d,g,0,this.variableList);if(u===PlaylistContextType.MANIFEST){const m={attrs:new AttrList({}),bitrate:0,details:y,name:"",url:f};y.requestScheduled=t.loading.start+computeReloadInterval(y,0),a.trigger(Events.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:f,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=y,this.handlePlaylistLoaded(y,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.MANIFEST_PARSING_ERROR,fatal:t.type===PlaylistContextType.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,i=!1,s,n){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===PlaylistContextType.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===PlaylistContextType.AUDIO_TRACK||e.type===PlaylistContextType.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=ErrorDetails.UNKNOWN,u=!1;const f=this.getInternalLoader(e);switch(e.type){case PlaylistContextType.MANIFEST:c=i?ErrorDetails.MANIFEST_LOAD_TIMEOUT:ErrorDetails.MANIFEST_LOAD_ERROR,u=!0;break;case PlaylistContextType.LEVEL:c=i?ErrorDetails.LEVEL_LOAD_TIMEOUT:ErrorDetails.LEVEL_LOAD_ERROR,u=!1;break;case PlaylistContextType.AUDIO_TRACK:c=i?ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case PlaylistContextType.SUBTITLE_TRACK:c=i?ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:ErrorDetails.SUBTITLE_LOAD_ERROR,u=!1;break}f&&this.resetInternalLoader(e.type);const d={type:ErrorTypes.NETWORK_ERROR,details:c,fatal:u,url:e.url,loader:f,context:e,error:o,networkDetails:t,stats:n};if(s){const g=t?.url||e.url;d.response=_objectSpread2({url:g,data:void 0},s)}this.hls.trigger(Events.ERROR,d)}handlePlaylistLoaded(e,t,i,s,n,a){const o=this.hls,{type:c,level:u,levelOrTrack:f,id:d,groupId:g,deliveryDirectives:y}=s,m=getResponseUrl(t,s),T=mapContextToLevelType(s);let E=typeof s.level=="number"&&T===PlaylistLevelType.MAIN?u:void 0;const b=e.playlistParsingError;if(b){if(this.hls.logger.warn(`${b} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:b,reason:b.message,response:t,context:s,level:E,parent:T,networkDetails:n,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const A=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:A,reason:A.message,response:t,context:s,level:E,parent:T,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case PlaylistContextType.MANIFEST:case PlaylistContextType.LEVEL:if(E){if(!f)E=0;else if(f!==o.levels[E]){const A=o.levels.indexOf(f);A>-1&&(E=A)}}o.trigger(Events.LEVEL_LOADED,{details:e,levelInfo:f||o.levels[0],level:E||0,id:d||0,stats:i,networkDetails:n,deliveryDirectives:y,withoutMultiVariant:c===PlaylistContextType.MANIFEST});break;case PlaylistContextType.AUDIO_TRACK:o.trigger(Events.AUDIO_TRACK_LOADED,{details:e,track:f,id:d||0,groupId:g||"",stats:i,networkDetails:n,deliveryDirectives:y});break;case PlaylistContextType.SUBTITLE_TRACK:o.trigger(Events.SUBTITLE_TRACK_LOADED,{details:e,track:f,id:d||0,groupId:g||"",stats:i,networkDetails:n,deliveryDirectives:y});break}}}class Hls{static get version(){return version}static isMSESupported(){return isMSESupported()}static isSupported(){return isSupported()}static getMediaSource(){return getMediaSource()}static get Events(){return Events}static get MetadataSchema(){return MetadataSchema}static get ErrorTypes(){return ErrorTypes}static get ErrorDetails(){return ErrorDetails}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:hlsDefaultConfig}static set DefaultConfig(e){Hls.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new EventEmitter,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=enableLogs(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=mergeConfig(Hls.DefaultConfig,e,t);this.userConfig=e,i.progressive&&enableStreamingMode(i,t);const{abrController:s,bufferController:n,capLevelController:a,errorController:o,fpsController:c}=i,u=new o(this),f=this.abrController=new s(this),d=new FragmentTracker(this),g=i.interstitialsController,y=g?this.interstitialsController=new g(this,Hls):null,m=this.bufferController=new n(this,d),T=this.capLevelController=new a(this),E=new c(this),b=new PlaylistLoader(this),A=i.contentSteeringController,C=A?new A(this):null,L=this.levelController=new LevelController(this,C),D=new ID3TrackController(this),V=new KeyLoader(this.config,this.logger),M=this.streamController=new StreamController(this,d,V),N=this.gapController=new GapController(this,d);T.setStreamController(M),E.setStreamController(M);const F=[b,L,M];y&&F.splice(1,0,y),C&&F.splice(1,0,C),this.networkControllers=F;const O=[f,m,N,T,E,D,d];this.audioTrackController=this.createController(i.audioTrackController,F);const $=i.audioStreamController;$&&F.push(this.audioStreamController=new $(this,d,V)),this.subtitleTrackController=this.createController(i.subtitleTrackController,F);const Q=i.subtitleStreamController;Q&&F.push(this.subtititleStreamController=new Q(this,d,V)),this.createController(i.timelineController,O),V.emeController=this.emeController=this.createController(i.emeController,O),this.cmcdController=this.createController(i.cmcdController,O),this.latencyController=this.createController(LatencyController,O),this.coreComponents=O,F.push(u);const J=u.onErrorOut;typeof J=="function"&&this.on(Events.ERROR,J,u),this.on(Events.MANIFEST_LOADED,b.onManifestLoaded,b)}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(this.logger.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===Events.ERROR;this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(Events.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){if(!e||"media"in e&&!e.media){const n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(Events.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(Events.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(Events.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,s=this._url=urlToolkitExports.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Events.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[PlaylistLevelType.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[PlaylistLevelType.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[PlaylistLevelType.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=uuid()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.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){this.logger.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){this.logger.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 abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){isHdcpLevel(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 n=s;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}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()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0: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}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const i=getAudioTracksByGroup(t);return getMediaDecodingInfoPromise(e,i,navigator.mediaCapabilities)}}Hls.defaultConfig=void 0;const checkPwaInstalled=()=>{const r=window.matchMedia("(display-mode: standalone)").matches,e=/iphone|ipad|ipod/i.test(window.navigator.userAgent),t=window.navigator.standalone===!0;return r||e&&t},usePWAInstalled=()=>{const[r,e]=React.useState(checkPwaInstalled());return React.useEffect(()=>{const t=()=>{e(checkPwaInstalled())};return window.addEventListener("DOMContentLoaded",t),window.addEventListener("appinstalled",t),()=>{window.removeEventListener("DOMContentLoaded",t),window.removeEventListener("appinstalled",t)}},[]),r};function VideoPlayer({src:r,reverseSrc:e,poster:t,keySrc:i,onPlay:s,onPause:n}){const[a,o]=React.useState(!1),[c,u]=React.useState(!1),f=React.useRef(null),{os:d,browser:g}=useUserAgent(),y=useDeviceType(),[m,T]=React.useState(!1),[E,b]=React.useState(!1),[A,C]=React.useState(0),[L,D]=React.useState(0),[V,M]=React.useState([]),[N,F]=React.useState(!1),[O,$]=React.useState(!1),Q=usePWAInstalled(),[J,ie]=React.useState([{value:.5,label:"0.5x",active:!1},{value:1,label:"1x",active:!0},{value:1.25,label:"1.25x",active:!1},{value:1.5,label:"1.5x",active:!1},{value:1.75,label:"1.75x",active:!1},{value:2,label:"2x",active:!1},{value:2.5,label:"2.5x",active:!1},{value:3,label:"3x",active:!1}]),ae=React.useRef(null),le=React.useRef(null),[me,Y]=React.useState(!1),Z=React.useRef(null),j=React.useRef(!1);React.useEffect(()=>(ee(),document.addEventListener("keypress",H),()=>{Z.current?.destroy(),Z.current=null,document.removeEventListener("keypress",H)}),[r,i]);function H(De){De.preventDefault(),De.code.toUpperCase()==="SPACE"&&Je()}async function ee(){if(!f.current||!r)return;const De=r.endsWith(".m3u8");if(Hls.isSupported()&&De)try{const rt=new Hls({xhrSetup:function(Le,st){st.includes(".key")&&i&&Le.open("GET",i,!0)},maxBufferLength:30,maxMaxBufferLength:60,maxBufferSize:3e7,maxBufferHole:1,startPosition:-1,autoStartLoad:!0});rt.on(Hls.Events.ERROR,function(Le,st){console.error("Hls error:",st)}),Z.current=rt,rt.loadSource(r),rt.attachMedia(f.current)}catch{$(!0)}else f.current.canPlayType("application/vnd.apple.mpegurl")&&De?e&&(f.current.src=e):f.current.src=r;f.current.poster=t??"",f.current.addEventListener("canplay",oe),f.current.addEventListener("loadedmetadata",Ee),f.current.addEventListener("play",z),f.current.addEventListener("pause",he),f.current.addEventListener("timeupdate",ye),f.current.addEventListener("progress",se),f.current.addEventListener("error",fe),f.current.addEventListener("playing",te),f.current.addEventListener("waiting",xe),document.addEventListener("visibilitychange",Te),W()}React.useEffect(()=>{a&&c&&F(!0)},[a,c]),React.useEffect(()=>{const De=setTimeout(()=>{F(!1)},1e4);return()=>{clearTimeout(De)}},[N]);function oe(){o(!0),$(!1)}function fe(){$(!0),o(!1),u(!1);const De=f.current?.error;if(De)switch(De.code){case MediaError.MEDIA_ERR_ABORTED:console.log("خطا: بارگذاری ویدیو قطع شد.");break;case MediaError.MEDIA_ERR_NETWORK:console.log("خطا: مشکل شبکه هنگام بارگذاری ویدیو.");break;case MediaError.MEDIA_ERR_DECODE:console.log("خطا: مشکل در رمزگشایی فایل ویدیو.");break;case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:console.log("خطا: فرمت یا سورس ویدیو پشتیبانی نمی‌شود.");break;default:console.log("خطای نامشخص در ویدیو.");break}else console.log("خطای ناشناخته در پخش ویدیو")}function se(){const De=f.current;if(!De)return;const rt=[],Le=De.buffered;for(let st=0;st<Le.length;st++){const ii=Le.start(st),Rr=Le.end(st);rt.push({start:ii,end:Rr})}M(rt)}function Ee(){o(!0),$(!1),D(f.current?.duration??0)}function ye(){C(f.current?.currentTime??0)}function Te(){f.current?.pause()}function W(){new IntersectionObserver(rt=>{for(const Le of rt){const st=Le.target;Le.intersectionRatio<.5?!st.paused&&!st.ended&&(st.pause(),j.current=!0):Le.isIntersecting&&(j.current&&st.play().catch(()=>{}),j.current=!1)}},{threshold:[0,.5,1]}).observe(f.current)}function z(){u(!0),s?.()}function he(){u(!1),n?.()}function te(){o(!0),u(!0)}function xe(){o(!1),u(!1),$(!1)}async function ve(){if(d.name?.toUpperCase().includes("IOS")||g.name?.toUpperCase().includes("SAFARI")&&d.name?.toUpperCase().includes("MAC")&&(y===DeviceTypeEnum.MOBILE||Q))E?(f.current?.classList.remove("!object-contain"),f.current?.parentElement?.classList.remove("!z-[999]")):(f.current?.classList.add("!object-contain"),f.current?.parentElement?.classList.add("!z-[999]")),b(!E);else{if(document.fullscreenElement)await document.exitFullscreen(),f.current?.classList.remove("!object-contain"),f.current?.parentElement?.classList.remove("!z-[9999999]");else{const De=f.current?.parentElement;if(De){const rt=De.requestFullscreen||De.webkitRequestFullscreen||De.mozRequestFullScreen||De.msRequestFullscreen;if(rt){const Le=rt.call(De);Le&&Le.catch(st=>{console.error("Error attempting to enable full-screen mode:",st)})}else console.warn("Fullscreen API is not supported by this browser.")}f.current?.classList.add("!object-contain"),f.current?.parentElement?.classList.add("!z-[9999999]")}Be()}}React.useEffect(()=>{Be()},[E]);function $e(){f.current&&(f.current.currentTime+=15)}function Pe(){f.current&&(f.current.currentTime-=15)}function Me(){f.current&&(m?f.current.muted=!1:f.current.muted=!0,T(!m))}function Je(){c?f.current?.pause():f.current?.play()}function dt(){let De=lodashExports.findIndex(J,Le=>Le.active),rt=J[De].value;De+1==J.length?De=0:De+=1,ie(J.map((Le,st)=>st==De?(rt=Le.value,{value:Le.value,label:Le.label,active:!0}):{value:Le.value,label:Le.label,active:!1})),f.current&&(f.current.playbackRate=rt)}function ze(De){f.current&&(f.current.currentTime=De)}function Be(){document.fullscreenElement||E?document.body.classList.add("landscape-allowed"):document.body.classList.remove("landscape-allowed")}const ot=React.useRef(lodashExports.debounce(()=>{F(!0)})).current;function mt(){$(!1),ee()}function Ct(){ae.current&&(clearTimeout(ae.current),ae.current=null),$e()}function pt(){ae.current&&(clearTimeout(ae.current),ae.current=null),Pe()}function tt(){Y(!1),le.current=setTimeout(()=>{Y(!0),ie(J.map(De=>De.value==2?{value:De.value,label:De.label,active:!0}:{value:De.value,label:De.label,active:!1})),f.current&&(f.current.playbackRate=2)},1e3)}function It(){me&&(ie(J.map(De=>De.value==1?{value:De.value,label:De.label,active:!0}:{value:De.value,label:De.label,active:!1})),f.current&&(f.current.playbackRate=1)),le.current&&(clearTimeout(le.current),le.current=null)}return jsxRuntimeExports.jsxs("section",{onMouseMove:ot,onTouchMove:ot,onMouseDown:tt,onMouseUp:It,onTouchStart:tt,onTouchEnd:It,onClick:()=>{if(me){Y(!1);return}ae.current!==null&&(clearTimeout(ae.current),ae.current=null),c?ae.current=setTimeout(()=>{f.current?.pause()},300):f.current?.play()},className:E?"fullscreen-safari":"w-full h-full relative",children:[jsxRuntimeExports.jsx("video",{width:"100%",height:"100%",className:"w-full h-full object-cover",ref:f,playsInline:!0,"webkit-playsinline":"true",controls:!1}),jsxRuntimeExports.jsx(VideoPlayerControl,{isError:O,isShowControl:N,onSeek:ze,bufferedRanges:V,rates:J,currentTime:A,duration:L,onTogglePlay:Je,isMuted:m,onToggleMute:Me,onBackwardCurrentTime:Pe,onForwardCurrentTime:$e,onDoubleClickInRight:Ct,onDoubleClickInLeft:pt,onMaximize:ve,canPlay:a,isPlayed:c,onChangeRate:dt,onTryAgain:mt})]})}exports.VideoPlayer=VideoPlayer,exports.VideoPlayerControl=VideoPlayerControl,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}));
325
+ `:(n=i.childNodes)!=null&&n.length?getTextContent(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function getTtmlStyles(r,e,t){const i="http://www.w3.org/ns/ttml#styling";let s=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=r!=null&&r.hasAttribute("style")?r.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(s=t[a]),n.reduce((o,c)=>{const u=getAttributeNS(e,i,c)||getAttributeNS(r,i,c)||getAttributeNS(s,i,c);return u&&(o[c]=u),o},{})}function getAttributeNS(r,e,t){return r&&r.hasAttributeNS(e,t)?r.getAttributeNS(e,t):null}function timestampParsingError(r){return new Error(`Could not parse ttml timestamp ${r}`)}function parseTtmlTime(r,e){if(!r)return null;let t=parseTimeStamp(r);return t===null&&(HMSF_REGEX.test(r)?t=parseHoursMinutesSecondsFrames(r,e):TIME_UNIT_REGEX.test(r)&&(t=parseTimeUnits(r,e))),t}function parseHoursMinutesSecondsFrames(r,e){const t=HMSF_REGEX.exec(r),i=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+i/e.frameRate}function parseTimeUnits(r,e){const t=TIME_UNIT_REGEX.exec(r),i=Number(t[1]);switch(t[2]){case"h":return i*3600;case"m":return i*60;case"ms":return i*1e3;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}class OutputFilter{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class TimelineController{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Events.FRAG_LOADING,this.onFragLoading,this),e.on(Events.FRAG_LOADED,this.onFragLoaded,this),e.on(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Events.FRAG_LOADING,this.onFragLoading,this),e.off(Events.FRAG_LOADED,this.onFragLoaded,this),e.off(Events.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Events.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Events.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Events.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new OutputFilter(this,"textTrack1"),t=new OutputFilter(this,"textTrack2"),i=new OutputFilter(this,"textTrack3"),s=new OutputFilter(this,"textTrack4");this.cea608Parser1=new Cea608Parser(1,e,t),this.cea608Parser2=new Cea608Parser(3,i,s)}addCues(e,t,i,s,n){let a=!1;for(let o=n.length;o--;){const c=n[o],u=intersection(c[0],c[1],t,i);if(u>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],i),a=!0,u/(i-t)>.5))return}if(a||n.push([t,i]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,i,s)}else{const o=this.Cues.newCue(null,t,i,s);this.hls.trigger(Events.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:s,timescale:n,trackId:a}){const{unparsedVttFrags:o}=this;i===PlaylistLevelType.MAIN&&(this.initPTS[t.cc]={baseTime:s,timescale:n,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(Events.FRAG_LOADED,c):this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:i}=this;if(i)for(let s=0;s<i.textTracks.length;s++){const n=i.textTracks[s];if(canReuseVttTextTrack(n,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return n}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:i,media:s}=this,{label:n,languageCode:a}=t[e],o=this.getExistingTrack(n,a);if(o)i[e]=o,clearCurrentCues(i[e]),sendAddTrackEvent(i[e],s);else{const c=this.createTextTrack("captions",n,a);c&&(c[e]=!0,i[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const i=t.label,s={_id:e,label:i,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=s,this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[s]})}createTextTrack(e,t,i){const s=this.media;if(s)return s.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const i=!!t.transferMedia;if(this.media=null,i)return;const{captionsTracks:s}=this;Object.keys(s).forEach(n=>{clearCurrentCues(s[n]),delete s[n]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=newVTTCCs(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let i=0;i<t.length;i++)clearCurrentCues(t[i])}onSubtitleTracksUpdated(e,t){const i=t.subtitleTracks||[],s=i.some(n=>n.textCodec===IMSC1_CODEC);if(this.config.enableWebVTT||s&&this.config.enableIMSC1){if(subtitleOptionsIdentical(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){const a=this.media,o=a?filterSubtitleTracks(a.textTracks):null;if(this.tracks.forEach((c,u)=>{let f;if(o){let d=null;for(let g=0;g<o.length;g++)if(o[g]&&canReuseVttTextTrack(o[g],c)){d=o[g],o[g]=null;break}d&&(f=d)}if(f)clearCurrentCues(f);else{const d=captionsOrSubtitlesFromCharacteristics(c);f=this.createTextTrack(d,c.name,c.lang),f&&(f.mode="disabled")}f&&this.textTracks.push(f)}),o!=null&&o.length){const c=o.filter(u=>u!==null).map(u=>u.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(i=>{const s=/(?:CC|SERVICE)([1-4])/.exec(i.instreamId);if(!s)return;const n=`textTrack${s[1]}`,a=this.captionsProperties[n];a&&(a.label=i.name,i.lang&&(a.languageCode=i.lang),a.media=i)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===PlaylistLevelType.MAIN){var i,s;const{cea608Parser1:n,cea608Parser2:a,lastSn:o}=this,{cc:c,sn:u}=t.frag,f=(i=(s=t.part)==null?void 0:s.index)!=null?i:-1;n&&a&&(u!==o+1||u===o&&f!==this.lastPartIndex+1||c!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=c,this.lastSn=u,this.lastPartIndex=f}}onFragLoaded(e,t){const{frag:i,payload:s}=t;if(i.type===PlaylistLevelType.SUBTITLE)if(s.byteLength){const n=i.decryptdata,a="stats"in t;if(n==null||!n.encrypted||a){const o=this.tracks[i.level],c=this.vttCCs;c[i.cc]||(c[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),o&&o.textCodec===IMSC1_CODEC?this._parseIMSC1(i,s):this._parseVTTs(t)}}else this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const i=this.hls;parseIMSC1(t,this.initPTS[e.cc],s=>{this._appendCues(s,e.level),i.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},s=>{i.logger.log(`Failed to parse IMSC1: ${s}`),i.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:s})})}_parseVTTs(e){var t;const{frag:i,payload:s}=e,{initPTS:n,unparsedVttFrags:a}=this,o=n.length-1;if(!n[i.cc]&&o===-1){a.push(e);return}const c=this.hls,u=(t=i.initSegment)!=null&&t.data?appendUint8Array(i.initSegment.data,new Uint8Array(s)).buffer:s;parseWebVTT(u,this.initPTS[i.cc],this.vttCCs,i.cc,i.start,f=>{this._appendCues(f,i.level),c.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i})},f=>{const d=f.message==="Missing initPTS for VTT MPEGTS";d?a.push(e):this._fallbackToIMSC1(i,s),c.logger.log(`Failed to parse VTT cue: ${f}`),!(d&&o>i.cc)&&c.trigger(Events.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:f})})}_fallbackToIMSC1(e,t){const i=this.tracks[e.level];i.textCodec||parseIMSC1(t,this.initPTS[e.cc],()=>{i.textCodec=IMSC1_CODEC,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){const i=this.hls;if(this.config.renderTextTracksNatively){const s=this.textTracks[t];if(!s||s.mode==="disabled")return;e.forEach(n=>addCueToTrack(s,n))}else{const s=this.tracks[t];if(!s)return;const n=s.default?"default":"subtitles"+t;i.trigger(Events.CUES_PARSED,{type:"subtitles",cues:e,track:n})}}onFragDecrypted(e,t){const{frag:i}=t;i.type===PlaylistLevelType.SUBTITLE&&this.onFragLoaded(Events.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=t;if(!(i.type===PlaylistLevelType.MAIN&&this.closedCaptionsForLevel(i)==="NONE"))for(let n=0;n<s.length;n++){const a=s[n].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(s[n].pts,o[0]),this.cea608Parser2.addData(s[n].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:s,type:n}){const{media:a}=this;if(!(!a||a.currentTime<i)){if(!n||n==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(c=>removeCuesInRange(o[c],t,i))}if(this.config.renderTextTracksNatively&&t===0&&s!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>removeCuesInRange(o[c],t,s))}}}extractCea608Data(e){const t=[[],[]],i=e[0]&31;let s=2;for(let n=0;n<i;n++){const a=e[s++],o=127&e[s++],c=127&e[s++];if(o===0&&c===0)continue;if((4&a)!==0){const f=3&a;(f===0||f===1)&&(t[f].push(o),t[f].push(c))}}return t}}function captionsOrSubtitlesFromCharacteristics(r){return r.characteristics&&/transcribes-spoken-dialog/gi.test(r.characteristics)&&/describes-music-and-sound/gi.test(r.characteristics)?"captions":"subtitles"}function canReuseVttTextTrack(r,e){return!!r&&r.kind===captionsOrSubtitlesFromCharacteristics(e)&&subtitleTrackMatchesTextTrack(e,r)}function intersection(r,e,t,i){return Math.min(e,i)-Math.max(r,t)}function newVTTCCs(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const WHITESPACE_CHAR=/\s/,Cues={newCue(r,e,t,i){const s=[];let n,a,o,c,u;const f=self.VTTCue||self.TextTrackCue;for(let g=0;g<i.rows.length;g++)if(n=i.rows[g],o=!0,c=0,u="",!n.isEmpty()){var d;for(let T=0;T<n.chars.length;T++)WHITESPACE_CHAR.test(n.chars[T].uchar)&&o?c++:(u+=n.chars[T].uchar,o=!1);n.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const y=fixLineBreaks(u.trim()),m=generateCueId(e,t,y);r!=null&&(d=r.cues)!=null&&d.getCueById(m)||(a=new f(e,t,y),a.id=m,a.line=g+1,a.align="left",a.position=10+Math.min(80,Math.floor(c*8/32)*10),s.push(a))}return r&&s.length&&(s.sort((g,y)=>g.line==="auto"||y.line==="auto"?0:g.line>8&&y.line>8?y.line-g.line:g.line-y.line),s.forEach(g=>addCueToTrack(r,g))),s}};function fetchSupported(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const BYTERANGE=/(\d+)-(\d+)\/(\d+)/;class FetchLoader{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||getRequest,this.controller=new self.AbortController,this.stats=new LoadStats}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 n=getRequestParameters(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=c&&isFiniteNumber(c)?c:u,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},t.timeout),(isPromise(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var g;this.response=this.loader=d;const y=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(s,e,this.response))},u-(y-s.loading.start)),!d.ok){const{status:T,statusText:E}=d;throw new FetchError(E||"fetch, bad network response",T,d)}s.loading.first=y,s.total=getContentLength(d.headers)||s.total;const m=(g=this.callbacks)==null?void 0:g.onProgress;return m&&isFiniteNumber(t.highWaterMark)?this.loadProgressively(d,s,e,t.highWaterMark,m):a?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var g,y;const m=this.response;if(!m)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const T=d[o];T&&(s.loaded=s.total=T);const E={url:m.url,data:d,code:m.status},b=(g=this.callbacks)==null?void 0:g.onProgress;b&&!isFiniteNumber(t.highWaterMark)&&b(s,e,d,m),(y=this.callbacks)==null||y.onSuccess(E,s,e,m)}).catch(d=>{var g;if(self.clearTimeout(this.requestTimeout),s.aborted)return;const y=d&&d.code||0,m=d?d.message:null;(g=this.callbacks)==null||g.onError({code:y,text:m},e,d?d.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,n){const a=new ChunkCache,o=e.body.getReader(),c=()=>o.read().then(u=>{if(u.done)return a.dataLength&&n(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const f=u.value,d=f.length;return t.loaded+=d,d<s||a.dataLength?(a.push(f),a.dataLength>=s&&n(t,i,a.flush().buffer,e)):n(t,i,f.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function getRequestParameters(r,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(_extends({},r.headers))};return r.rangeEnd&&t.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),t}function getByteRangeLength(r){const e=BYTERANGE.exec(r);if(e)return parseInt(e[2])-parseInt(e[1])+1}function getContentLength(r){const e=r.get("Content-Range");if(e){const i=getByteRangeLength(e);if(isFiniteNumber(i))return i}const t=r.get("Content-Length");if(t)return parseInt(t)}function getRequest(r,e){return new self.Request(r.url,e)}class FetchError extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}const AGE_HEADER_LINE_REGEX=/^age:\s*[\d.]+\s*$/im;class XhrLoader{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 LoadStats,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,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 n=this.xhrSetup;n?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return n(i,t.url)}).catch(a=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),n(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:i.status,text:a.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:n,maxLoadTimeMs:a}=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=n&&isFiniteNumber(n)?n:a,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,n=this.config;if(!i.aborted&&s>=2&&(i.loading.first===0&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),s===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const u=t.status,f=t.responseType==="text"?t.responseText:null;if(u>=200&&u<300){const m=f??t.response;if(m!=null){var a,o;i.loading.end=Math.max(self.performance.now(),i.loading.first);const T=t.responseType==="arraybuffer"?m.byteLength:m.length;i.loaded=i.total=T,i.bwEstimate=i.total*8e3/(i.loading.end-i.loading.first);const E=(a=this.callbacks)==null?void 0:a.onProgress;E&&E(i,e,m,t);const b={url:t.responseURL,data:m,code:u};(o=this.callbacks)==null||o.onSuccess(b,i,e,t);return}}const d=n.loadPolicy.errorRetry,g=i.retry,y={url:e.url,data:void 0,code:u};if(shouldRetry(d,g,!1,y))this.retry(d);else{var c;logger.error(`${u} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:u,text:t.statusText},e,t,i)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(shouldRetry(e,t,!0))this.retry(e);else{var i;logger.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const s=this.callbacks;s&&(this.abortInternal(),s.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:i}=this;this.retryDelay=getRetryDelay(e,i.retry),i.retry++,logger.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&&AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const defaultLoadPolicy={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},hlsDefaultConfig=_objectSpread2(_objectSpread2({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,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,ignorePlaylistParsingErrors:!1,loader:XhrLoader,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:AbrController,bufferController:BufferController,capLevelController:CapLevelController,errorController:ErrorController,fpsController:FPSController,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:requestMediaKeySystemAccess,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:defaultLoadPolicy},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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,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},timelineConfig()),{},{subtitleStreamController:SubtitleStreamController,subtitleTrackController:SubtitleTrackController,timelineController:TimelineController,audioStreamController:AudioStreamController,audioTrackController:AudioTrackController,emeController:EMEController,cmcdController:CMCDController,contentSteeringController:ContentSteeringController,interstitialsController:InterstitialsController});function timelineConfig(){return{cueHandler:Cues,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function mergeConfig(r,e,t){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 i=deepCpy(r),s=["manifest","level","frag"],n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,c=e[o]===void 0,u=[];n.forEach(f=>{const d=`${a}Loading${f}`,g=e[d];if(g!==void 0&&c){u.push(d);const y=i[o].default;switch(e[o]={default:y},f){case"TimeOut":y.maxLoadTimeMs=g,y.maxTimeToFirstByteMs=g;break;case"MaxRetry":y.errorRetry.maxNumRetry=g,y.timeoutRetry.maxNumRetry=g;break;case"RetryDelay":y.errorRetry.retryDelayMs=g,y.timeoutRetry.retryDelayMs=g;break;case"MaxRetryTimeout":y.errorRetry.maxRetryDelayMs=g,y.timeoutRetry.maxRetryDelayMs=g;break}}}),u.length&&t.warn(`hls.js config: "${u.join('", "')}" setting(s) are deprecated, use "${o}": ${stringify(e[o])}`)}),_objectSpread2(_objectSpread2({},i),e)}function deepCpy(r){return r&&typeof r=="object"?Array.isArray(r)?r.map(deepCpy):Object.keys(r).reduce((e,t)=>(e[t]=deepCpy(r[t]),e),{}):r}function enableStreamingMode(r,e){const t=r.loader;t!==FetchLoader&&t!==XhrLoader?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),r.progressive=!1):fetchSupported()&&(r.loader=FetchLoader,r.progressive=!0,r.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const MAX_START_GAP_JUMP=2,SKIP_BUFFER_HOLE_STEP_SECONDS=.1,SKIP_BUFFER_RANGE_START=.05,TICK_INTERVAL$1=100;class GapController extends TaskLoop{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var i;(i=this.media)!=null&&i.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var i;this.ended=((i=this.media)==null?void 0:i.currentTime)||1,this.hls.trigger(Events.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(TICK_INTERVAL$1),this.mediaSource=t.mediaSource;const i=this.media=t.media;addEventListener(i,"playing",this.onMediaPlaying),addEventListener(i,"waiting",this.onMediaWaiting),addEventListener(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:i}=this;i&&(removeEventListener(i,"playing",this.onMediaPlaying),removeEventListener(i,"waiting",this.onMediaWaiting),removeEventListener(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,s;const n=(i=this.hls)==null?void 0:i.config;if(!n)return;const a=this.media;if(!a)return;const{seeking:o}=a,c=this.seeking&&!o,u=!this.seeking&&o,f=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!f&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(u||c){c&&this.stallResolved(e);return}if(f){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(Events.MEDIA_ENDED,{stalled:!1}));return}if(!BufferHelper.getBuffered(a).length){this.nudgeRetry=0;return}const d=BufferHelper.bufferInfo(a,e,0),g=d.nextStart||0,y=this.fragmentTracker;if(o&&y&&this.hls){const V=getInFlightDependency(this.hls.inFlightFragments,e),M=d.len>MAX_START_GAP_JUMP,N=!g||V||g-e>MAX_START_GAP_JUMP&&!y.getPartialFragment(e);if(M||N)return;this.moved=!1}const m=(s=this.hls)==null?void 0:s.latestLevelDetails;if(!this.moved&&this.stalled!==null&&y){if(!(d.len>0)&&!g)return;const M=Math.max(g,d.start||0)-e,F=!!(m!=null&&m.live)?m.targetduration*2:MAX_START_GAP_JUMP,O=appendedFragAtPosition(e,y);if(M>0&&(M<=F||O)){a.paused||this._trySkipBufferHole(O);return}}const T=n.detectStallWithCurrentTimeMs,E=self.performance.now(),b=this.waiting;let A=this.stalled;if(A===null)if(b>0&&E-b<T)A=this.stalled=b;else{this.stalled=E;return}const C=E-A;if(!o&&(C>=T||b)&&this.hls){var L;if(((L=this.mediaSource)==null?void 0:L.readyState)==="ended"&&!(m!=null&&m.live)&&Math.abs(e-(m?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(Events.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}const D=BufferHelper.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(D,C,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Events.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(i=this.buffered.audio)!=null&&i.length&&s&&s.length>1&&e>s.end(0)){const n=BufferHelper.bufferedInfo(BufferHelper.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){const a=BufferHelper.timeRangesToArray(s),o=BufferHelper.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const c=BufferHelper.bufferedInfo(a,e,0).bufferedIndex,u=a[o].end,f=a[o+1].start;if((c===-1||c>o)&&f-u<1&&e-u<2){const d=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${u} -> ${f} buffered index: ${c}`);this.warn(d.message),this.media.currentTime+=1e-6;let g=appendedFragAtPosition(e,this.fragmentTracker);g&&"fragment"in g?g=g.fragment:g||(g=void 0);const y=BufferHelper.bufferInfo(this.media,e,0);this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:g,buffer:y.len,bufferInfo:y})}}}}}_tryFixBufferStall(e,t,i){var s,n;const{fragmentTracker:a,media:o}=this,c=(s=this.hls)==null?void 0:s.config;if(!o||!a||!c)return;const u=(n=this.hls)==null?void 0:n.latestLevelDetails,f=appendedFragAtPosition(i,a);if((f||u!=null&&u.live&&i<u.fragmentStart)&&(this._trySkipBufferHole(f)||!this.media))return;const d=e.buffered,g=this.adjacentTraversal(e,i);(d&&d.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-i<c.maxBufferHole||g))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const i=this.fragmentTracker,s=e.nextStart;if(i&&s){const n=i.getFragAtPos(t,PlaylistLevelType.MAIN),a=i.getFragAtPos(s,PlaylistLevelType.MAIN);if(n&&a)return a.sn-n.sn<2}return!1}_reportStall(e){const{hls:t,media:i,stallReported:s,stalled:n}=this;if(!s&&n!==null&&i&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${stringify(e)})`);this.warn(a.message),t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:i,media:s}=this,n=(t=this.hls)==null?void 0:t.config;if(!s||!i||!n)return 0;const a=s.currentTime,o=BufferHelper.bufferInfo(s,a,0),c=a<o.start?o.start:o.nextStart;if(c&&this.hls){const f=o.len<=n.maxBufferHole,d=o.len>0&&o.len<1&&s.readyState<3,g=c-a;if(g>0&&(f||d)){if(g>n.maxBufferHole){let m=!1;if(a===0){const T=i.getAppendedFrag(0,PlaylistLevelType.MAIN);T&&c<T.end&&(m=!0)}if(!m&&e){var u;if(!((u=this.hls.loadLevelObj)!=null&&u.details)||getInFlightDependency(this.hls.inFlightFragments,c))return 0;let E=!1,b=e.end;for(;b<c;){const A=appendedFragAtPosition(b,i);if(A)b+=A.duration;else{E=!0;break}}if(E)return 0}}const y=Math.max(c+SKIP_BUFFER_RANGE_START,a+SKIP_BUFFER_HOLE_STEP_SECONDS);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${y}`),this.moved=!0,s.currentTime=y,!(e!=null&&e.gap)){const m=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${y}`),T={type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:m,reason:m.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?T.part=e:T.frag=e),this.hls.trigger(Events.ERROR,T)}return y}}return 0}_tryNudgeBuffer(e){const{hls:t,media:i,nudgeRetry:s}=this,n=t?.config;if(!i||!n)return 0;const a=i.currentTime;if(this.nudgeRetry++,s<n.nudgeMaxRetry){const o=a+(s+1)*n.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(c.message),i.currentTime=o,t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${n.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function getInFlightDependency(r,e){const t=inFlight(r.main);if(t&&t.start<=e)return t;const i=inFlight(r.audio);return i&&i.start<=e?i:null}function inFlight(r){if(!r)return null;switch(r.state){case State.IDLE:case State.STOPPED:case State.ENDED:case State.ERROR:return null}return r.frag}function appendedFragAtPosition(r,e){return e.getAppendedFrag(r,PlaylistLevelType.MAIN)||e.getPartialFragment(r)}const MIN_CUE_DURATION=.25;function getCueClass(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function createCueWithDataFields(r,e,t,i,s){let n=new r(e,t,"");try{n.value=i,s&&(n.type=s)}catch{n=new r(e,t,stringify(s?_objectSpread2({type:s},i):i))}return n}const MAX_CUE_ENDTIME=(()=>{const r=getCueClass();try{r&&new r(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class ID3TrackController{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(Events.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Events.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,((i=t.overrides)==null?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&clearCurrentCues(this.id3Track,this.onEventCueEnter),this.id3Track=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 sendAddTrackEvent(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:n}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=getCueClass();if(a)for(let o=0;o<n.length;o++){const c=n[o].type;if(c===MetadataSchema.emsg&&!i||!s)continue;const u=getId3Frames(n[o].data),f=n[o].pts;let d=f+n[o].duration;d>MAX_CUE_ENDTIME&&(d=MAX_CUE_ENDTIME),d-f<=0&&(d=f+MIN_CUE_DURATION);for(let y=0;y<u.length;y++){const m=u[y];if(!isId3TimestampFrame(m)){this.updateId3CueEnds(f,c);const T=createCueWithDataFields(a,f,d,m,c);T&&this.id3Track.addCue(T)}}}}updateId3CueEnds(e,t){var i;const s=(i=this.id3Track)==null?void 0:i.cues;if(s)for(let n=s.length;n--;){const a=s[n];a.type===t&&a.startTime<e&&a.endTime===MAX_CUE_ENDTIME&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:s}){const{id3Track:n,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=a;if(n&&(o||c)){let u;s==="audio"?u=f=>f.type===MetadataSchema.audioId3&&c:s==="video"?u=f=>f.type===MetadataSchema.emsg&&o:u=f=>f.type===MetadataSchema.audioId3&&c||f.type===MetadataSchema.emsg&&o,removeCuesInRange(n,t,i,u)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:i,timelineOffset:s,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=getCueClass();if(i&&s&&!a){const{fragmentStart:T,fragmentEnd:E}=e;let b=this.assetCue;b?(b.startTime=T,b.endTime=E):o&&(b=this.assetCue=createCueWithDataFields(o,T,E,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),b&&(b.id=i,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(b),b.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:u}=e,f=Object.keys(u);let d=this.dateRangeCuesAppended;if(c&&t){var g;if((g=c.cues)!=null&&g.length){const T=Object.keys(d).filter(E=>!f.includes(E));for(let E=T.length;E--;){var y;const b=T[E],A=(y=d[b])==null?void 0:y.cues;delete d[b],A&&Object.keys(A).forEach(C=>{const L=A[C];if(L){L.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(L)}catch{}}})}}else d=this.dateRangeCuesAppended={}}const m=e.fragments[e.fragments.length-1];if(!(f.length===0||!isFiniteNumber(m?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let T=0;T<f.length;T++){const E=f[T],b=u[E],A=b.startTime,C=d[E],L=C?.cues||{};let D=C?.durationKnown||!1,V=MAX_CUE_ENDTIME;const{duration:M,endDate:N}=b;if(N&&M!==null)V=A+M,D=!0;else if(b.endOnNext&&!D){const O=f.reduce(($,Q)=>{if(Q!==b.id){const J=u[Q];if(J.class===b.class&&J.startDate>b.startDate&&(!$||b.startDate<$.startDate))return J}return $},null);O&&(V=O.startTime,D=!0)}const F=Object.keys(b.attr);for(let O=0;O<F.length;O++){const $=F[O];if(!isDateRangeCueAttribute($))continue;const Q=L[$];if(Q)D&&!(C!=null&&C.durationKnown)?Q.endTime=V:Math.abs(Q.startTime-A)>.01&&(Q.startTime=A,Q.endTime=V);else if(o){let J=b.attr[$];isSCTE35Attribute($)&&(J=hexToArrayBuffer(J));const ae=createCueWithDataFields(o,A,V,{key:$,data:J},MetadataSchema.dateRange);ae&&(ae.id=E,this.id3Track.addCue(ae),L[$]=ae,a&&($==="X-ASSET-LIST"||$==="X-ASSET-URL")&&ae.addEventListener("enter",this.onEventCueEnter))}}d[E]={cues:L,dateRange:b,durationKnown:D}}}}}class LatencyController{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,i=this.levelDetails;if(!t||!i)return;this.currentTime=t.currentTime;const s=this.computeLatency();if(s===null)return;this._latency=s;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=this.config;if(!n||a===1||!i.live)return;const o=this.targetLatency;if(o===null)return;const c=s-o,u=Math.min(this.maxLatency,o+i.targetduration);if(c<u&&c>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,a)),g=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,y=Math.min(d,Math.max(1,g));this.changeMediaPlaybackRate(t,y)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:i,targetduration:s}=e,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let u=o&&i||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||u===0)&&(u=n!==void 0?n:a*s);const f=s;return u+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,f)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const i=this.levelDetails;if(i===null)return null;const s=i.edge,n=e-t-this.edgeStalled,a=s-i.totalduration,o=s-(this.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(a,n),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;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}=this,t=this.levelDetails;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.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Events.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(Events.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Events.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Events.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===ErrorDetails.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(i=this.levelDetails)!=null&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,s;e.playbackRate!==t&&((i=this.hls)==null||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(s=this.targetLatency)==null?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class LevelController extends BasePlaylistController{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(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Events.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Events.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=[],n={},a={};let o=!1,c=!1,u=!1;t.levels.forEach(f=>{const d=f.attrs;let{audioCodec:g,videoCodec:y}=f;g&&(f.audioCodec=g=getCodecCompatibleName(g,i)||void 0),y&&(y=f.videoCodec=convertAVC1ToAVCOTI(y));const{width:m,height:T,unknownCodecs:E}=f,b=E?.length||0;if(o||(o=!!(m&&T)),c||(c=!!y),u||(u=!!g),b||g&&!this.isAudioSupported(g)||y&&!this.isVideoSupported(y)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}const{CODECS:A,"FRAME-RATE":C,"HDCP-LEVEL":L,"PATHWAY-ID":D,RESOLUTION:V,"VIDEO-RANGE":M}=d,F=`${`${D||"."}-`}${f.bitrate}-${V}-${C}-${A}-${M}-${L}`;if(n[F])if(n[F].uri!==f.url&&!f.attrs["PATHWAY-ID"]){const O=a[F]+=1;f.attrs["PATHWAY-ID"]=new Array(O+1).join(".");const $=this.createLevel(f);n[F]=$,s.push($)}else n[F].addGroupId("audio",d.AUDIO),n[F].addGroupId("text",d.SUBTITLES);else{const O=this.createLevel(f);n[F]=O,a[F]=1,s.push(O)}}),this.filterAndSortMediaOptions(s,t,o,c,u)}createLevel(e){const t=new Level(e),i=e.supplemental;if(i!=null&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){const s=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(s.message),t.supportedResult=getUnsupportedResult(s,[])}return t}isAudioSupported(e){return areCodecsMediaSourceSupported(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return areCodecsMediaSourceSupported(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,s,n){var a;let o=[],c=[],u=e;const f=((a=t.stats)==null?void 0:a.parsing)||{};if((i||s)&&n&&(u=u.filter(({videoCodec:A,videoRange:C,width:L,height:D})=>(!!A||!!(L&&D))&&isVideoRange(C))),u.length===0){Promise.resolve().then(()=>{if(this.hls){let A="no level with compatible codecs found in manifest",C=A;t.levels.length&&(C=`one or more CODECS in variant not supported: ${stringify(t.levels.map(D=>D.attrs.CODECS).filter((D,V,M)=>M.indexOf(D)===V))}`,this.warn(C),A+=` (${C})`);const L=new Error(A);this.hls.trigger(Events.ERROR,{type:ErrorTypes.MEDIA_ERROR,details:ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:L,reason:C})}}),f.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(A=>!A.audioCodec||this.isAudioSupported(A.audioCodec)),assignTrackIdsByGroup(o)),t.subtitles&&(c=t.subtitles,assignTrackIdsByGroup(c));const d=u.slice(0);u.sort((A,C)=>{if(A.attrs["HDCP-LEVEL"]!==C.attrs["HDCP-LEVEL"])return(A.attrs["HDCP-LEVEL"]||"")>(C.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&A.height!==C.height)return A.height-C.height;if(A.frameRate!==C.frameRate)return A.frameRate-C.frameRate;if(A.videoRange!==C.videoRange)return VideoRangeValues.indexOf(A.videoRange)-VideoRangeValues.indexOf(C.videoRange);if(A.videoCodec!==C.videoCodec){const L=videoCodecPreferenceValue(A.videoCodec),D=videoCodecPreferenceValue(C.videoCodec);if(L!==D)return D-L}if(A.uri===C.uri&&A.codecSet!==C.codecSet){const L=codecsSetSelectionPreferenceValue(A.codecSet),D=codecsSetSelectionPreferenceValue(C.codecSet);if(L!==D)return D-L}return A.averageBitrate!==C.averageBitrate?A.averageBitrate-C.averageBitrate:0});let g=d[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==d.length)){for(let A=0;A<d.length;A++)if(d[A].pathwayId===u[0].pathwayId){g=d[A];break}}this._levels=u;for(let A=0;A<u.length;A++)if(u[A]===g){var y;this._firstLevel=A;const C=g.bitrate,L=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${C}`),((y=this.hls.userConfig)==null?void 0:y.abrEwmaDefaultEstimate)===void 0){const D=Math.min(C,this.hls.config.abrEwmaDefaultEstimateMax);D>L&&L===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=D)}break}const m=n&&!s,T=this.hls.config,E=!!(T.audioStreamController&&T.audioTrackController),b={levels:u,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:s,altAudio:E&&!m&&o.some(A=>!!A.url)};f.end=performance.now(),this.hls.trigger(Events.MANIFEST_PARSED,b)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const f=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:f,reason:f.message}),d)return;e=Math.min(e,t.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,n=s?s.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&s&&n===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${i}${n?" with Pathway "+n:""}`);const c={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(Events.LEVEL_SWITCHING,c);const u=a.details;if(!u||u.live){const f=this.switchParams(a.uri,s?.details,u);this.loadPlaylist(f)}}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}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),i=e.filter(s=>t.indexOf(s)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===PlaylistContextType.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===PlaylistLevelType.MAIN){const i=t.elementaryStreams;if(!Object.keys(i).some(n=>!!i[n]))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:n}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${s}`),(o=t.deliveryDirectives)!=null&&o.skip&&(n.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let c=a.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(s,t,c)}else(i=t.deliveryDirectives)!=null&&i.skip&&(n.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const i=this.getUrlWithDirectives(e.uri,t),s=this.currentLevelIndex,n=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${s}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n?" Pathway "+n:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(Events.LEVEL_LOADING,{url:i,level:s,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||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;if(this._levels.length===1)return;const i=this._levels.filter((n,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(n),n===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,n.details&&n.details.fragments.forEach(o=>o.level=-1)),!1));reassignFragmentLevelIndexes(i),this._levels=i,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(Events.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(Events.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function assignTrackIdsByGroup(r){const e={};r.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}function getSourceBuffer(){return self.SourceBuffer||self.WebKitSourceBuffer}function isMSESupported(){if(!getMediaSource())return!1;const e=getSourceBuffer();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function isSupported(){if(!isMSESupported())return!1;const r=getMediaSource();return typeof r?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>r.isTypeSupported(mimeTypeForCodec(e,"video")))||["mp4a.40.2","fLaC"].some(e=>r.isTypeSupported(mimeTypeForCodec(e,"audio"))))}function changeTypeSupported(){var r;const e=getSourceBuffer();return typeof(e==null||(r=e.prototype)==null?void 0:r.changeType)=="function"}const TICK_INTERVAL=100;class StreamController extends BaseStreamController{constructor(e,t,i){super(e,t,i,"stream-controller",PlaylistLevelType.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const s=this.media,n=s?s.currentTime:null;if(n===null||!isFiniteNumber(n)||(this.log(`Media seeked to ${n.toFixed(3)}`),!this.getBufferedFrag(n)))return;const a=this.getFwdBufferInfoAtPos(s,n,PlaylistLevelType.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${n} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Events.BUFFER_CREATED,this.onBufferCreated,this),e.on(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Events.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(Events.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Events.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Events.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Events.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Events.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Events.BUFFER_CREATED,this.onBufferCreated,this),e.off(Events.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Events.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(TICK_INTERVAL),this.level=-1,!this.startFragRequested){let n=s.startLevel;n===-1&&(s.config.testBandwidth&&this.levels.length>1?(n=0,this.bitrateTest=!0):n=s.firstAutoLevel),s.nextLoadLevel=n,this.level=s.loadLevel,this._hasEnoughToStart=!!t}i>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=State.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=State.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case State.WAITING_LEVEL:{const{levels:e,level:t}=this,i=e?.[t],s=i?.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=State.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=State.IDLE;break}break}case State.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===State.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:i,media:s}=this;if(t===null||!s&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const n=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(i!=null&&i[n]))return;const a=i[n],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const T={};this.altAudio===2&&(T.type="video"),this.hls.trigger(Events.BUFFER_EOS,T),this.state=State.ENDED;return}if(!this.buffering)return;e.loadLevel!==n&&e.manualLevel===-1&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=e.nextLoadLevel=n;const u=a.details;if(!u||this.state===State.WAITING_LEVEL||this.waitForLive(a)){this.level=n,this.state=State.WAITING_LEVEL,this.startFragRequested=!1;return}const f=o.len,d=this.getMaxBufferLength(a.maxBitrate);if(f>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const g=this.backtrackFragment?this.backtrackFragment.start:o.end;let y=this.getNextFragment(g,u);if(this.couldBacktrack&&!this.fragPrevious&&y&&isMediaFragment(y)&&this.fragmentTracker.getState(y)!==FragmentState.OK){var m;const E=((m=this.backtrackFragment)!=null?m:y).sn-u.startSN,b=u.fragments[E-1];b&&y.cc===b.cc&&(y=b,this.fragmentTracker.removeFragment(b))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(y&&this.isLoopLoading(y,g)){if(!y.gap){const E=this.audioOnly&&!this.altAudio?ElementaryStreamTypes.AUDIO:ElementaryStreamTypes.VIDEO,b=(E===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;b&&this.afterBufferFlushed(b,E,PlaylistLevelType.MAIN)}y=this.getNextFragmentLoopLoading(y,u,o,PlaylistLevelType.MAIN,d)}y&&(y.initSegment&&!y.initSegment.data&&!this.bitrateTest&&(y=y.initSegment),this.loadFragment(y,a,g))}loadFragment(e,t,i){const s=this.fragmentTracker.getState(e);s===FragmentState.NOT_LOADED||s===FragmentState.PARTIAL?isMediaFragment(e)?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)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,PlaylistLevelType.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 n=this.getLevelDetails();if(n!=null&&n.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<n.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,c=e[o],u=this.fragLastKbps;u&&this.fragCurrent?i=this.fragCurrent.duration*c.maxBitrate/(1e3*u)+1:i=0}else i=0;const a=this.getBufferedFrag(t.currentTime+i);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const c=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,f=Math.max(a.end,c+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(f,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 State.KEY_LOADING:case State.FRAG_LOADING:case State.FRAG_LOADING_WAITING_RETRY:case State.PARSING:case State.PARSED:this.state=State.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const i=t.media;addEventListener(i,"playing",this.onMediaPlaying),addEventListener(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:i}=this;i&&(removeEventListener(i,"playing",this.onMediaPlaying),removeEventListener(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Events.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let i=!1,s=!1;for(let n=0;n<t.levels.length;n++){const a=t.levels[n].audioCodec;a&&(i=i||a.indexOf("mp4a.40.2")!==-1,s=s||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=i&&s&&!changeTypeSupported(),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!==State.IDLE)return;const s=t.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=State.WAITING_LEVEL)}onLevelLoaded(e,t){var i;const{levels:s,startFragRequested:n}=this,a=t.level,o=t.details,c=o.totalduration;if(!s){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);const u=t.levelInfo,f=this.fragCurrent;f&&(this.state===State.FRAG_LOADING||this.state===State.FRAG_LOADING_WAITING_RETRY)&&f.level!==t.level&&f.loader&&this.abortCurrentFrag();let d=0;if(o.live||(i=u.details)!=null&&i.live){var g;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,u.details,(g=this.levelLastLoaded)==null?void 0:g.details)}if(u.details=o,this.levelLastLoaded=u,n||this.setStartPosition(o,d),this.hls.trigger(Events.LEVEL_UPDATED,{details:o,level:a}),this.state===State.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=State.IDLE}n&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,n=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,c=n>=a-t.maxFragLookUpTolerance&&n<=o;if(s!==null&&i.duration>s&&(n<s||!c)){const f=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&i.readyState<4||n<o-f)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${n.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${s.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var u;const d=BufferHelper.bufferInfo(i,s,0);if(!((u=d.buffered)!=null&&u.length)){i.currentTime=s;return}if(d.start<=n){i.currentTime=s;return}const{nextStart:y}=BufferHelper.bufferedInfo(d.buffered,n,0);y&&(i.currentTime=y)}else i.currentTime=s}}_handleFragmentLoadProgress(e){var t;const i=e.frag,{part:s,payload:n}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);return}const o=a[i.level];if(!o){this.warn(`Level ${i.level} not found on progress`);return}const c=o.details;if(!c){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}const u=o.videoCodec,f=c.PTSKnown||!c.live,d=(t=i.initSegment)==null?void 0:t.data,g=this._getAudioCodec(o),y=this.transmuxer=this.transmuxer||new TransmuxerInterface(this.hls,PlaylistLevelType.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),m=s?s.index:-1,T=m!==-1,E=new ChunkMetadata(i.level,i.sn,i.stats.chunkCount,n.byteLength,m,T),b=this.initPTS[i.cc];y.push(n,d,g,u,i,s,c.totalduration,f,E,b)}onAudioTrackSwitching(e,t){const i=this.hls,s=this.altAudio!==0;if(useAlternateAudio(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(Events.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(Events.AUDIO_TRACK_SWITCHED,t)}),i.trigger(Events.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}i.trigger(Events.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const i=useAlternateAudio(t.url,this.hls);if(i){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i?2:0,this.tick()}onBufferCreated(e,t){const i=t.tracks;let s,n,a=!1;for(const o in i){const c=i[o];if(c.id==="main"){if(n=o,s=c,o==="video"){const u=i[o];u&&(this.videoBuffer=u.buffer)}}else a=!0}a&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:i,part:s}=t,n=i.type===PlaylistLevelType.MAIN;if(n){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===State.PARSED&&(this.state=State.IDLE);return}const o=s?s.stats:i.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),isMediaFragment(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s)}const a=this.media;a&&(!this._hasEnoughToStart&&BufferHelper.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=State.ERROR;return}switch(t.details){case ErrorDetails.FRAG_GAP:case ErrorDetails.FRAG_PARSING_ERROR:case ErrorDetails.FRAG_DECRYPT_ERROR:case ErrorDetails.FRAG_LOAD_ERROR:case ErrorDetails.FRAG_LOAD_TIMEOUT:case ErrorDetails.KEY_LOAD_ERROR:case ErrorDetails.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN,t);break;case ErrorDetails.LEVEL_LOAD_ERROR:case ErrorDetails.LEVEL_LOAD_TIMEOUT:case ErrorDetails.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===State.WAITING_LEVEL&&((i=t.context)==null?void 0:i.type)===PlaylistContextType.LEVEL&&(this.state=State.IDLE);break;case ErrorDetails.BUFFER_ADD_CODEC_ERROR:case ErrorDetails.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case ErrorDetails.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case ErrorDetails.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=State.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ElementaryStreamTypes.AUDIO||!this.altAudio){const i=(t===ElementaryStreamTypes.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,t,PlaylistLevelType.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),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=this.timelineOffset;s&&i&&(i+=s);const n=this.getLevelDetails(),a=BufferHelper.getBuffered(e),o=a.length?a.start(0):0,c=o-i,u=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<u||this.loadingParts&&c<2*(n?.partTarget||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),i+=c,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${o}`),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,n=i?.frag;if(!n||this.fragContextChanged(n))return;t.fragmentError=0,this.state=State.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=n.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),s.trigger(Events.FRAG_LOADED,i),n.bitrateTest=!1}).catch(i=>{this.state===State.STOPPED||this.state===State.ERROR||(this.warn(i),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:i}=this,{remuxResult:s,chunkMeta:n}=e,a=this.getCurrentContext(n);if(!a){this.resetWhenMissingContext(n);return}const{frag:o,part:c,level:u}=a,{video:f,text:d,id3:g,initSegment:y}=s,{details:m}=u,T=this.altAudio?void 0:s.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=State.PARSING,y){const E=y.tracks;if(E){const L=o.initSegment||o;if(this.unhandledEncryptionError(y,o))return;this._bufferInitSegment(u,E,L,n),i.trigger(Events.FRAG_PARSING_INIT_SEGMENT,{frag:L,id:t,tracks:E})}const b=y.initPTS,A=y.timescale,C=this.initPTS[o.cc];if(isFiniteNumber(b)&&(!C||C.baseTime!==b||C.timescale!==A)){const L=y.trackId;this.initPTS[o.cc]={baseTime:b,timescale:A,trackId:L},i.trigger(Events.INIT_PTS_FOUND,{frag:o,id:t,initPTS:b,timescale:A,trackId:L})}}if(f&&m){T&&f.type==="audiovideo"&&this.logMuxedErr(o);const E=m.fragments[o.sn-1-m.startSN],b=o.sn===m.startSN,A=!E||o.cc>E.cc;if(s.independent!==!1){const{startPTS:C,endPTS:L,startDTS:D,endDTS:V}=f;if(c)c.elementaryStreams[f.type]={startPTS:C,endPTS:L,startDTS:D,endDTS:V};else if(f.firstKeyFrame&&f.independent&&n.id===1&&!A&&(this.couldBacktrack=!0),f.dropped&&f.independent){const M=this.getMainFwdBufferInfo(),N=(M?M.end:this.getLoadPosition())+this.config.maxBufferHole,F=f.firstKeyFramePTS?f.firstKeyFramePTS:C;if(!b&&N<F-this.config.maxBufferHole&&!A){this.backtrack(o);return}else A&&(o.gap=!0);o.setElementaryStreamInfo(f.type,o.start,L,o.start,V,!0)}else b&&C-(m.appliedTimelineOffset||0)>MAX_START_GAP_JUMP&&(o.gap=!0);o.setElementaryStreamInfo(f.type,C,L,D,V),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(f,o,c,n,b||A)}else if(b||A)o.gap=!0;else{this.backtrack(o);return}}if(T){const{startPTS:E,endPTS:b,startDTS:A,endDTS:C}=T;c&&(c.elementaryStreams[ElementaryStreamTypes.AUDIO]={startPTS:E,endPTS:b,startDTS:A,endDTS:C}),o.setElementaryStreamInfo(ElementaryStreamTypes.AUDIO,E,b,A,C),this.bufferFragmentData(T,o,c,n)}if(m&&g!=null&&g.samples.length){const E={id:t,frag:o,details:m,samples:g.samples};i.trigger(Events.FRAG_PARSING_METADATA,E)}if(m&&d){const E={id:t,frag:o,details:m,samples:d.samples};i.trigger(Events.FRAG_PARSING_USERDATA,E)}}logMuxedErr(e){this.warn(`${isMediaFragment(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,s){if(this.state!==State.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));const{audio:n,video:a,audiovideo:o}=t;if(n){const u=e.audioCodec;let f=pickMostCompleteCodecName(n.codec,u);f==="mp4a"&&(f="mp4a.40.5");const d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){f&&(f.indexOf("mp4a.40.5")!==-1?f="mp4a.40.2":f="mp4a.40.5");const g=n.metadata;g&&"channelCount"in g&&(g.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(f="mp4a.40.5")}f&&f.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&n.container!=="audio/mpeg"&&(f="mp4a.40.2",this.log(`Android: force audio codec to ${f}`)),u&&u!==f&&this.log(`Swapping manifest audio codec "${u}" for "${f}"`),n.levelCodec=f,n.id=PlaylistLevelType.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${f||""}/${u||""}/${n.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=PlaylistLevelType.MAIN;const u=a.codec;if(u?.length===4)switch(u){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${u}]${a.codec!==u?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(Events.BUFFER_CODECS,t),!this.hls)return;c.forEach(u=>{const d=t[u].initSegment;d!=null&&d.byteLength&&this.hls.trigger(Events.BUFFER_APPENDING,{type:u,data:d,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,PlaylistLevelType.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}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=State.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const i=e.currentTime;if(BufferHelper.isBuffered(e,i)?t=this.getAppendedFrag(i):BufferHelper.isBuffered(e,i+.1)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;const s=this.fragPlaying,n=t.level;(!s||t.sn!==s.sn||s.level!==n)&&(this.fragPlaying=t,this.hls.trigger(Events.FRAG_CHANGED,{frag:t}),(!s||s.level!==n)&&this.hls.trigger(Events.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return isFiniteNumber(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(isFiniteNumber(t)){const i=this.getLevelDetails(),s=this.currentFrag||(i?findFragmentByPTS(null,i.fragments,t):null);if(s){const n=s.programDateTime;if(n!==null){const a=n+(t-s.start)*1e3;return new Date(a)}}}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 KeyLoader extends Logger{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const i in this.keyIdToKeyInfo){const s=this.keyIdToKeyInfo[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.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=ErrorDetails.KEY_LOAD_ERROR,i,s,n){return new LoadError({type:ErrorTypes.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:i,networkDetails:s})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let s=0,n=t.length;s<n;s++){const a=t[s];if(e.cc<=a.cc&&(!isMediaFragment(e)||!isMediaFragment(a)||e.sn<a.sn)||!i&&s==n-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const c=keySystemFormatToKeySystemDomain(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const s=getKeySystemsForConfig(this.config);if(s.length)return this.emeController.getKeySystemAccess(s)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,s;t&&e.setKeyFormat(t);const n=e.decryptdata;if(!n){const u=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,u))}const a=n.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=getKeyId(n);let c=this.keyIdToKeyInfo[o];if((i=c)!=null&&i.decryptdata.key)return n.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(s=c)!=null&&s.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(f=>{const{keyInfo:d}=f;return n.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${n.keyId?" keyId: "+arrayToHex(n.keyId):""} URI: ${n.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={decryptdata:n,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return n.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,ErrorDetails.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${n.method}"`)))}}loadKeyEME(e,t){const i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var s;if(!e.decryptdata.keyId&&(s=t.initSegment)!=null&&s.data){const a=parseKeyIdsFromTenc(t.initSegment.data);if(a.length){let o=a[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${arrayToHex(o)}`),LevelKey.setKeyIdForUri(e.decryptdata.uri,o)):(o=LevelKey.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${arrayToHex(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!isMediaFragment(t))return Promise.resolve(i);const n=this.emeController.loadKey(i);return(e.keyLoadPromise=n.then(a=>(e.mediaKeySessionContext=a,i))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(i)}loadKeyHTTP(e,t){const i=this.config,s=i.loader,n=new s(i);return t.keyLoader=e.loader=n,e.keyLoadPromise=new Promise((a,o)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},u=i.keyLoadPolicy.default,f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(g,y,m,T)=>{const{frag:E,keyInfo:b}=m,A=getKeyId(b.decryptdata);if(!E.decryptdata||b!==this.keyIdToKeyInfo[A])return o(this.createKeyLoadError(E,ErrorDetails.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),T));b.decryptdata.key=E.decryptdata.key=new Uint8Array(g.data),E.keyLoader=null,b.loader=null,a({frag:E,keyInfo:b})},onError:(g,y,m,T)=>{this.resetLoader(y),o(this.createKeyLoadError(t,ErrorDetails.KEY_LOAD_ERROR,new Error(`HTTP Error ${g.code} loading key ${g.text}`),m,_objectSpread2({url:c.url,data:void 0},g)))},onTimeout:(g,y,m)=>{this.resetLoader(y),o(this.createKeyLoadError(t,ErrorDetails.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),m))},onAbort:(g,y,m)=>{this.resetLoader(y),o(this.createKeyLoadError(t,ErrorDetails.INTERNAL_ABORTED,new Error("key loading aborted"),m))}};n.load(c,f,d)})}resetLoader(e){const{frag:t,keyInfo:i,url:s}=e,n=i.loader;t.keyLoader===n&&(t.keyLoader=null,i.loader=null);const a=getKeyId(i.decryptdata)||s;delete this.keyIdToKeyInfo[a],n&&n.destroy()}}function getKeyId(r){if(r.keyFormat!==KeySystemFormats.FAIRPLAY){const e=r.keyId;if(e)return arrayToHex(e)}return r.uri}function mapContextToLevelType(r){const{type:e}=r;switch(e){case PlaylistContextType.AUDIO_TRACK:return PlaylistLevelType.AUDIO;case PlaylistContextType.SUBTITLE_TRACK:return PlaylistLevelType.SUBTITLE;default:return PlaylistLevelType.MAIN}}function getResponseUrl(r,e){let t=r.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class PlaylistLoader{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Events.LEVEL_LOADING,this.onLevelLoading,this),e.on(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Events.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(Events.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Events.LEVEL_LOADING,this.onLevelLoading,this),e.off(Events.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Events.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Events.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,i=t.pLoader,s=t.loader,n=i||s,a=new n(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:PlaylistContextType.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:i,level:s,pathwayId:n,url:a,deliveryDirectives:o,levelInfo:c}=t;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:PlaylistContextType.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:PlaylistContextType.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:i,groupId:s,url:n,deliveryDirectives:a,track:o}=t;this.load({id:i,groupId:s,level:null,responseType:"text",type:PlaylistContextType.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const i=this.loaders[PlaylistContextType.LEVEL];if(i){const s=i.context;s&&!t.levels.some(n=>n===s.levelOrTrack)&&(i.abort(),delete this.loaders[PlaylistContextType.LEVEL])}}load(e){var t;const i=this.hls.config;let s=this.getInternalLoader(e);if(s){const u=this.hls.logger,f=s.context;if(f&&f.levelOrTrack===e.levelOrTrack&&(f.url===e.url||f.deliveryDirectives&&!e.deliveryDirectives)){f.url===e.url?u.log(`[playlist-loader]: ignore ${e.url} ongoing request`):u.log(`[playlist-loader]: ignore ${e.url} in favor of ${f.url}`);return}u.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}let n;if(e.type===PlaylistContextType.MANIFEST?n=i.manifestLoadPolicy.default:n=_extends({},i.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),isFiniteNumber((t=e.deliveryDirectives)==null?void 0:t.part)){let u;if(e.type===PlaylistContextType.LEVEL&&e.level!==null?u=this.hls.levels[e.level].details:e.type===PlaylistContextType.AUDIO_TRACK&&e.id!==null?u=this.hls.audioTracks[e.id].details:e.type===PlaylistContextType.SUBTITLE_TRACK&&e.id!==null&&(u=this.hls.subtitleTracks[e.id].details),u){const f=u.partTarget,d=u.targetduration;if(f&&d){const g=Math.max(f*3,d*.8)*1e3;n=_extends({},n,{maxTimeToFirstByteMs:Math.min(g,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(g,n.maxTimeToFirstByteMs)})}}}const a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(u,f,d,g)=>{const y=this.getInternalLoader(d);this.resetInternalLoader(d.type);const m=u.data;f.parsing.start=performance.now(),M3U8Parser.isMediaPlaylist(m)||d.type!==PlaylistContextType.MANIFEST?this.handleTrackOrLevelPlaylist(u,f,d,g||null,y):this.handleMasterPlaylist(u,f,d,g)},onError:(u,f,d,g)=>{this.handleNetworkError(f,d,!1,u,g)},onTimeout:(u,f,d)=>{this.handleNetworkError(f,d,!0,void 0,u)}};s.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,s){const n=this.hls,a=e.data,o=getResponseUrl(e,i),c=M3U8Parser.parseMasterPlaylist(a,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,c.playlistParsingError,s,t);return}const{contentSteering:u,levels:f,sessionData:d,sessionKeys:g,startTimeOffset:y,variableList:m}=c;this.variableList=m,f.forEach(A=>{const{unknownCodecs:C}=A;if(C){const{preferManagedMediaSource:L}=this.hls.config;let{audioCodec:D,videoCodec:V}=A;for(let M=C.length;M--;){const N=C[M];areCodecsMediaSourceSupported(N,"audio",L)?(A.audioCodec=D=D?`${D},${N}`:N,sampleEntryCodesISO.audio[D.substring(0,4)]=2,C.splice(M,1)):areCodecsMediaSourceSupported(N,"video",L)&&(A.videoCodec=V=V?`${V},${N}`:N,sampleEntryCodesISO.video[V.substring(0,4)]=2,C.splice(M,1))}}});const{AUDIO:T=[],SUBTITLES:E,"CLOSED-CAPTIONS":b}=M3U8Parser.parseMasterPlaylistMedia(a,o,c);T.length&&!T.some(C=>!C.url)&&f[0].audioCodec&&!f[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),T.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new AttrList({}),bitrate:0,url:""})),n.trigger(Events.MANIFEST_LOADED,{levels:f,audioTracks:T,subtitles:E,captions:b,contentSteering:u,url:o,stats:t,networkDetails:s,sessionData:d,sessionKeys:g,startTimeOffset:y,variableList:m})}handleTrackOrLevelPlaylist(e,t,i,s,n){const a=this.hls,{id:o,level:c,type:u}=i,f=getResponseUrl(e,i),d=isFiniteNumber(c)?c:isFiniteNumber(o)?o:0,g=mapContextToLevelType(i),y=M3U8Parser.parseLevelPlaylist(e.data,f,d,g,0,this.variableList);if(u===PlaylistContextType.MANIFEST){const m={attrs:new AttrList({}),bitrate:0,details:y,name:"",url:f};y.requestScheduled=t.loading.start+computeReloadInterval(y,0),a.trigger(Events.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:f,stats:t,networkDetails:s,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=y,this.handlePlaylistLoaded(y,e,t,i,s,n)}handleManifestParsingError(e,t,i,s,n){this.hls.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.MANIFEST_PARSING_ERROR,fatal:t.type===PlaylistContextType.MANIFEST,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:s,stats:n})}handleNetworkError(e,t,i=!1,s,n){let a=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${e.type}`;e.type===PlaylistContextType.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===PlaylistContextType.AUDIO_TRACK||e.type===PlaylistContextType.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=ErrorDetails.UNKNOWN,u=!1;const f=this.getInternalLoader(e);switch(e.type){case PlaylistContextType.MANIFEST:c=i?ErrorDetails.MANIFEST_LOAD_TIMEOUT:ErrorDetails.MANIFEST_LOAD_ERROR,u=!0;break;case PlaylistContextType.LEVEL:c=i?ErrorDetails.LEVEL_LOAD_TIMEOUT:ErrorDetails.LEVEL_LOAD_ERROR,u=!1;break;case PlaylistContextType.AUDIO_TRACK:c=i?ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:ErrorDetails.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case PlaylistContextType.SUBTITLE_TRACK:c=i?ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:ErrorDetails.SUBTITLE_LOAD_ERROR,u=!1;break}f&&this.resetInternalLoader(e.type);const d={type:ErrorTypes.NETWORK_ERROR,details:c,fatal:u,url:e.url,loader:f,context:e,error:o,networkDetails:t,stats:n};if(s){const g=t?.url||e.url;d.response=_objectSpread2({url:g,data:void 0},s)}this.hls.trigger(Events.ERROR,d)}handlePlaylistLoaded(e,t,i,s,n,a){const o=this.hls,{type:c,level:u,levelOrTrack:f,id:d,groupId:g,deliveryDirectives:y}=s,m=getResponseUrl(t,s),T=mapContextToLevelType(s);let E=typeof s.level=="number"&&T===PlaylistLevelType.MAIN?u:void 0;const b=e.playlistParsingError;if(b){if(this.hls.logger.warn(`${b} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:b,reason:b.message,response:t,context:s,level:E,parent:T,networkDetails:n,stats:i});return}e.playlistParsingError=null}if(!e.fragments.length){const A=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(Events.ERROR,{type:ErrorTypes.NETWORK_ERROR,details:ErrorDetails.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:A,reason:A.message,response:t,context:s,level:E,parent:T,networkDetails:n,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case PlaylistContextType.MANIFEST:case PlaylistContextType.LEVEL:if(E){if(!f)E=0;else if(f!==o.levels[E]){const A=o.levels.indexOf(f);A>-1&&(E=A)}}o.trigger(Events.LEVEL_LOADED,{details:e,levelInfo:f||o.levels[0],level:E||0,id:d||0,stats:i,networkDetails:n,deliveryDirectives:y,withoutMultiVariant:c===PlaylistContextType.MANIFEST});break;case PlaylistContextType.AUDIO_TRACK:o.trigger(Events.AUDIO_TRACK_LOADED,{details:e,track:f,id:d||0,groupId:g||"",stats:i,networkDetails:n,deliveryDirectives:y});break;case PlaylistContextType.SUBTITLE_TRACK:o.trigger(Events.SUBTITLE_TRACK_LOADED,{details:e,track:f,id:d||0,groupId:g||"",stats:i,networkDetails:n,deliveryDirectives:y});break}}}class Hls{static get version(){return version}static isMSESupported(){return isMSESupported()}static isSupported(){return isSupported()}static getMediaSource(){return getMediaSource()}static get Events(){return Events}static get MetadataSchema(){return MetadataSchema}static get ErrorTypes(){return ErrorTypes}static get ErrorDetails(){return ErrorDetails}static get DefaultConfig(){return Hls.defaultConfig?Hls.defaultConfig:hlsDefaultConfig}static set DefaultConfig(e){Hls.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new EventEmitter,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=enableLogs(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=mergeConfig(Hls.DefaultConfig,e,t);this.userConfig=e,i.progressive&&enableStreamingMode(i,t);const{abrController:s,bufferController:n,capLevelController:a,errorController:o,fpsController:c}=i,u=new o(this),f=this.abrController=new s(this),d=new FragmentTracker(this),g=i.interstitialsController,y=g?this.interstitialsController=new g(this,Hls):null,m=this.bufferController=new n(this,d),T=this.capLevelController=new a(this),E=new c(this),b=new PlaylistLoader(this),A=i.contentSteeringController,C=A?new A(this):null,L=this.levelController=new LevelController(this,C),D=new ID3TrackController(this),V=new KeyLoader(this.config,this.logger),M=this.streamController=new StreamController(this,d,V),N=this.gapController=new GapController(this,d);T.setStreamController(M),E.setStreamController(M);const F=[b,L,M];y&&F.splice(1,0,y),C&&F.splice(1,0,C),this.networkControllers=F;const O=[f,m,N,T,E,D,d];this.audioTrackController=this.createController(i.audioTrackController,F);const $=i.audioStreamController;$&&F.push(this.audioStreamController=new $(this,d,V)),this.subtitleTrackController=this.createController(i.subtitleTrackController,F);const Q=i.subtitleStreamController;Q&&F.push(this.subtititleStreamController=new Q(this,d,V)),this.createController(i.timelineController,O),V.emeController=this.emeController=this.createController(i.emeController,O),this.cmcdController=this.createController(i.cmcdController,O),this.latencyController=this.createController(LatencyController,O),this.coreComponents=O,F.push(u);const J=u.onErrorOut;typeof J=="function"&&this.on(Events.ERROR,J,u),this.on(Events.MANIFEST_LOADED,b.onManifestLoaded,b)}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(this.logger.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===Events.ERROR;this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.INTERNAL_EXCEPTION,fatal:s,event:e,error:i}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(Events.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){if(!e||"media"in e&&!e.media){const n=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(Events.ERROR,{type:ErrorTypes.OTHER_ERROR,details:ErrorDetails.ATTACH_MEDIA_ERROR,fatal:!0,error:n});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,i=t?e.media:e,s=t?e:{media:i};this._media=i,this.trigger(Events.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger(Events.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(Events.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,i=this._url,s=this._url=urlToolkitExports.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),t&&i&&(i!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Events.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[PlaylistLevelType.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[PlaylistLevelType.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[PlaylistLevelType.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=uuid()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.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){this.logger.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){this.logger.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 abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){isHdcpLevel(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 n=s;n--;){const a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}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()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0: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}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const i=getAudioTracksByGroup(t);return getMediaDecodingInfoPromise(e,i,navigator.mediaCapabilities)}}Hls.defaultConfig=void 0;const checkPwaInstalled=()=>{const r=window.matchMedia("(display-mode: standalone)").matches,e=/iphone|ipad|ipod/i.test(window.navigator.userAgent),t=window.navigator.standalone===!0;return r||e&&t},usePWAInstalled=()=>{const[r,e]=React.useState(checkPwaInstalled());return React.useEffect(()=>{const t=()=>{e(checkPwaInstalled())};return window.addEventListener("DOMContentLoaded",t),window.addEventListener("appinstalled",t),()=>{window.removeEventListener("DOMContentLoaded",t),window.removeEventListener("appinstalled",t)}},[]),r};function VideoPlayer({src:r,reverseSrc:e,poster:t,keySrc:i,onPlay:s,onPause:n}){const[a,o]=React.useState(!1),[c,u]=React.useState(!1),f=React.useRef(null),{os:d,browser:g}=useUserAgent(),y=useDeviceType(),[m,T]=React.useState(!1),[E,b]=React.useState(!1),[A,C]=React.useState(0),[L,D]=React.useState(0),[V,M]=React.useState([]),[N,F]=React.useState(!1),[O,$]=React.useState(!1),Q=usePWAInstalled(),[J,ie]=React.useState([{value:.5,label:"0.5x",active:!1},{value:1,label:"1x",active:!0},{value:1.25,label:"1.25x",active:!1},{value:1.5,label:"1.5x",active:!1},{value:1.75,label:"1.75x",active:!1},{value:2,label:"2x",active:!1},{value:2.5,label:"2.5x",active:!1},{value:3,label:"3x",active:!1}]),ae=React.useRef(null),le=React.useRef(null),[me,Y]=React.useState(!1),Z=React.useRef(null),j=React.useRef(!1);React.useEffect(()=>(ee(),document.addEventListener("keypress",H),()=>{Z.current?.destroy(),Z.current=null,document.removeEventListener("keypress",H)}),[r,i]);function H(De){De.preventDefault(),De.code.toUpperCase()==="SPACE"&&Je()}async function ee(){if(!f.current||!r)return;const De=r.endsWith(".m3u8");if(Hls.isSupported()&&De)try{const rt=new Hls({xhrSetup:function(Le,st){st.includes(".key")&&i&&Le.open("GET",i,!0)},maxBufferLength:30,maxMaxBufferLength:60,maxBufferSize:3e7,maxBufferHole:1,startPosition:-1,autoStartLoad:!0});rt.on(Hls.Events.ERROR,function(Le,st){console.error("Hls error:",st)}),Z.current=rt,rt.loadSource(r),rt.attachMedia(f.current)}catch{$(!0)}else f.current.canPlayType("application/vnd.apple.mpegurl")&&De?e&&(f.current.src=e):f.current.src=r;f.current.poster=t??"",f.current.addEventListener("canplay",oe),f.current.addEventListener("loadedmetadata",Ee),f.current.addEventListener("play",z),f.current.addEventListener("pause",he),f.current.addEventListener("timeupdate",ye),f.current.addEventListener("progress",se),f.current.addEventListener("error",fe),f.current.addEventListener("playing",te),f.current.addEventListener("waiting",xe),document.addEventListener("visibilitychange",Te),W()}React.useEffect(()=>{a&&c&&F(!0)},[a,c]),React.useEffect(()=>{const De=setTimeout(()=>{F(!1)},1e4);return()=>{clearTimeout(De)}},[N]);function oe(){o(!0),$(!1)}function fe(){$(!0),o(!1),u(!1);const De=f.current?.error;if(De)switch(De.code){case MediaError.MEDIA_ERR_ABORTED:console.log("خطا: بارگذاری ویدیو قطع شد.");break;case MediaError.MEDIA_ERR_NETWORK:console.log("خطا: مشکل شبکه هنگام بارگذاری ویدیو.");break;case MediaError.MEDIA_ERR_DECODE:console.log("خطا: مشکل در رمزگشایی فایل ویدیو.");break;case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:console.log("خطا: فرمت یا سورس ویدیو پشتیبانی نمی‌شود.");break;default:console.log("خطای نامشخص در ویدیو.");break}else console.log("خطای ناشناخته در پخش ویدیو")}function se(){const De=f.current;if(!De)return;const rt=[],Le=De.buffered;for(let st=0;st<Le.length;st++){const ii=Le.start(st),Rr=Le.end(st);rt.push({start:ii,end:Rr})}M(rt)}function Ee(){o(!0),$(!1),D(f.current?.duration??0)}function ye(){C(f.current?.currentTime??0)}function Te(){f.current?.pause()}function W(){new IntersectionObserver(rt=>{for(const Le of rt){const st=Le.target;Le.intersectionRatio<.5?!st.paused&&!st.ended&&(st.pause(),j.current=!0):Le.isIntersecting&&(j.current&&st.play().catch(()=>{}),j.current=!1)}},{threshold:[0,.5,1]}).observe(f.current)}function z(){u(!0),s?.()}function he(){u(!1),n?.()}function te(){o(!0),u(!0)}function xe(){o(!1),u(!1),$(!1)}async function ve(){if(d.name?.toUpperCase().includes("IOS")||g.name?.toUpperCase().includes("SAFARI")&&d.name?.toUpperCase().includes("MAC")&&(y===DeviceTypeEnum.MOBILE||Q))E?(f.current?.classList.remove("!object-contain"),f.current?.parentElement?.classList.remove("!z-[999]")):(f.current?.classList.add("!object-contain"),f.current?.parentElement?.classList.add("!z-[999]")),b(!E);else{if(document.fullscreenElement)await document.exitFullscreen(),f.current?.classList.remove("!object-contain"),f.current?.parentElement?.classList.remove("!z-[9999999]");else{const De=f.current?.parentElement;if(De){const rt=De.requestFullscreen||De.webkitRequestFullscreen||De.mozRequestFullScreen||De.msRequestFullscreen;if(rt){const Le=rt.call(De);Le&&Le.catch(st=>{console.error("Error attempting to enable full-screen mode:",st)})}else console.warn("Fullscreen API is not supported by this browser.")}f.current?.classList.add("!object-contain"),f.current?.parentElement?.classList.add("!z-[9999999]")}Be()}}React.useEffect(()=>{Be()},[E]);function $e(){f.current&&(f.current.currentTime+=15)}function Pe(){f.current&&(f.current.currentTime-=15)}function Me(){f.current&&(m?f.current.muted=!1:f.current.muted=!0,T(!m))}function Je(){c?f.current?.pause():f.current?.play()}function dt(){let De=lodashExports.findIndex(J,Le=>Le.active),rt=J[De].value;De+1==J.length?De=0:De+=1,ie(J.map((Le,st)=>st==De?(rt=Le.value,{value:Le.value,label:Le.label,active:!0}):{value:Le.value,label:Le.label,active:!1})),f.current&&(f.current.playbackRate=rt)}function ze(De){f.current&&(f.current.currentTime=De)}function Be(){document.fullscreenElement||E?document.body.classList.add("landscape-allowed"):document.body.classList.remove("landscape-allowed")}const ot=React.useRef(lodashExports.debounce(()=>{F(!0)})).current;function mt(){$(!1),ee()}function Ct(){ae.current&&(clearTimeout(ae.current),ae.current=null),$e()}function pt(){ae.current&&(clearTimeout(ae.current),ae.current=null),Pe()}function tt(){Y(!1),le.current=setTimeout(()=>{Y(!0),ie(J.map(De=>De.value==2?{value:De.value,label:De.label,active:!0}:{value:De.value,label:De.label,active:!1})),f.current&&(f.current.playbackRate=2)},1e3)}function It(){me&&(ie(J.map(De=>De.value==1?{value:De.value,label:De.label,active:!0}:{value:De.value,label:De.label,active:!1})),f.current&&(f.current.playbackRate=1)),le.current&&(clearTimeout(le.current),le.current=null)}return jsxRuntimeExports.jsxs("section",{onMouseMove:ot,onTouchMove:ot,onMouseDown:tt,onMouseUp:It,onTouchStart:tt,onTouchEnd:It,onClick:()=>{if(me){Y(!1);return}ae.current!==null&&(clearTimeout(ae.current),ae.current=null),c?ae.current=setTimeout(()=>{f.current?.pause()},300):f.current?.play()},className:E?"fullscreen-safari":"w-full h-full relative",children:[jsxRuntimeExports.jsx("video",{width:"100%",height:"100%",className:"w-full h-full object-cover",ref:f,playsInline:!0,"webkit-playsinline":"true",controls:!1}),jsxRuntimeExports.jsx(VideoPlayerControl,{isError:O,isShowControl:N,onSeek:ze,bufferedRanges:V,rates:J,currentTime:A,duration:L,onTogglePlay:Je,isMuted:m,onToggleMute:Me,onBackwardCurrentTime:Pe,onForwardCurrentTime:$e,onDoubleClickInRight:Ct,onDoubleClickInLeft:pt,onMaximize:ve,canPlay:a,isPlayed:c,onChangeRate:dt,onTryAgain:mt})]})}exports.VideoPlayer=VideoPlayer,exports.VideoPlayerControl=VideoPlayerControl,exports.default=VideoPlayer,Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.1.8",
6
+ "version": "0.1.10",
7
7
  "type": "module",
8
8
  "types": "dist/index.d.ts",
9
9
  "main": "dist/sibtorsh-player.umd.js",