0){w+=m;try{S=new Uint8Array(w)}catch(O){this.observer.emit($.ERROR,$.ERROR,{type:ye.MUX_ERROR,details:q.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:w,reason:`fail allocating audio mdat ${w}`});return}d||(new DataView(S.buffer).setUint32(0,w),S.set(K.types.mdat,4))}else return;S.set(U,m);const k=U.byteLength;m+=k,h.push(new oB(!0,l,k,0)),_=W}const I=h.length;if(!I)return;const T=h[h.length-1];this.nextAudioPts=g=_+c*T.duration;const C=d?new Uint8Array(0):K.moof(e.sequenceNumber++,b/c,Pt({},e,{samples:h}));e.samples=[];const L=b/s,H=g/s,P={data1:C,data2:S,startPTS:L,endPTS:H,startDTS:L,endDTS:H,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,P}remuxEmptyAudio(e,r,n,i){const a=e.inputTimeScale,s=e.samplerate?e.samplerate:a,o=a/s,c=this.nextAudioPts,l=this._initDTS,u=l.baseTime*9e4/l.timescale,f=(c!==null?c:i.startDTS*a)+u,d=i.endDTS*a+u,h=o*sB,p=Math.ceil((d-f)/h),v=aB.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(G.warn("[mp4-remuxer]: remux empty Audio"),!v){G.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const m=[];for(let g=0;g4294967296;)t+=r;return t}function kGe(t){for(let e=0;es.pts-o.pts);const a=t.samples;return t.samples=[],{samples:a}}class oB{constructor(e,r,n,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=r,this.size=n,this.cts=i,this.flags=new OGe(e)}}class OGe{constructor(e){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=e?2:1,this.isNonSync=e?0:1}}class LGe{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,r,n,i){this.audioCodec=r,this.videoCodec=n,this.generateInitSegment(JHe(e,i)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:r,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const i=this.initData=TQ(e);r||(r=lB(i.audio,Qe.AUDIO)),n||(n=lB(i.video,Qe.VIDEO));const a={};i.audio&&i.video?a.audiovideo={container:"video/mp4",codec:r+","+n,initSegment:e,id:"main"}:i.audio?a.audio={container:"audio/mp4",codec:r,initSegment:e,id:"audio"}:i.video?a.video={container:"video/mp4",codec:n,initSegment:e,id:"main"}:G.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=a}remux(e,r,n,i,a,s){var o,c;let{initPTS:l,lastEndTime:u}=this;const f={audio:void 0,video:void 0,text:i,id3:n,initSegment:void 0};me(u)||(u=this.lastEndTime=a||0);const d=r.samples;if(!(d!=null&&d.length))return f;const h={initPTS:void 0,timescale:1};let p=this.initData;if((o=p)!=null&&o.length||(this.generateInitSegment(d),p=this.initData),!((c=p)!=null&&c.length))return G.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),f;this.emitInitSegment&&(h.tracks=this.initTracks,this.emitInitSegment=!1);const v=eze(p,d),m=v===null?a:v;(PGe(l,m,a)||h.timescale!==l.timescale&&s)&&(h.initPTS=m-a,this.initPTS=l={baseTime:h.initPTS,timescale:1});const g=tze(d,p),y=e?m-l.baseTime/l.timescale:u,x=y+g;nze(p,d,l.baseTime/l.timescale),g>0?this.lastEndTime=x:(G.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const b=!!p.audio,_=!!p.video;let S="";b&&(S+="audio"),_&&(S+="video");const w={data1:d,startPTS:y,startDTS:y,endPTS:x,endDTS:x,type:S,hasAudio:b,hasVideo:_,nb:1,dropped:0};return f.audio=w.type==="audio"?w:void 0,f.video=w.type!=="audio"?w:void 0,f.initSegment=h,f.id3=qQ(n,a,l,l),i.samples.length&&(f.text=XQ(i,a,l)),f}}function PGe(t,e,r){if(t===null)return!0;const n=e-t.baseTime/t.timescale;return n<0&&Math.abs(n-r)>1}function lB(t,e){const r=t==null?void 0:t.codec;return r&&r.length>4?r:r==="hvc1"||r==="hev1"?"hvc1.1.c.L120.90":r==="av01"?"av01.0.04M.08":r==="avc1"||e===Qe.VIDEO?"avc1.42e01e":"mp4a.40.5"}let ja;try{ja=self.performance.now.bind(self.performance)}catch{G.debug("Unable to use Performance API on this environment"),ja=typeof self<"u"&&self.Date.now}const mT=[{demux:gGe,remux:LGe},{demux:js,remux:pT},{demux:pGe,remux:pT},{demux:RGe,remux:pT}];class cB{constructor(e,r,n,i,a){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=r,this.config=n,this.vendor=i,this.id=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,r,n,i){const a=n.transmuxing;a.executeStart=ja();let s=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:u,trackSwitch:f,accurateTimeOffset:d,timeOffset:h,initSegmentChange:p}=i||o,{audioCodec:v,videoCodec:m,defaultInitPts:g,duration:y,initSegmentData:x}=c,b=NGe(s,r);if(b&&b.method==="AES-128"){const R=this.getDecrypter();if(R.isSync()){let I=R.softwareDecrypt(s,b.key.buffer,b.iv.buffer);if(n.part>-1&&(I=R.flush()),!I)return a.executeEnd=ja(),gT(n);s=new Uint8Array(I)}else return this.decryptionPromise=R.webCryptoDecrypt(s,b.key.buffer,b.iv.buffer).then(I=>{const T=this.push(I,null,n);return this.decryptionPromise=null,T}),this.decryptionPromise}const _=this.needsProbing(u,f);if(_){const R=this.configureTransmuxer(s);if(R)return G.warn(`[transmuxer] ${R.message}`),this.observer.emit($.ERROR,$.ERROR,{type:ye.MEDIA_ERROR,details:q.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),a.executeEnd=ja(),gT(n)}(u||f||p||_)&&this.resetInitSegment(x,v,m,y,r),(u||p||_)&&this.resetInitialTimestamp(g),l||this.resetContiguity();const S=this.transmux(s,b,h,d,n),w=this.currentTransmuxState;return w.contiguous=!0,w.discontinuity=!1,w.trackSwitch=!1,a.executeEnd=ja(),S}flush(e){const r=e.transmuxing;r.executeStart=ja();const{decrypter:n,currentTransmuxState:i,decryptionPromise:a}=this;if(a)return a.then(()=>this.flush(e));const s=[],{timeOffset:o}=i;if(n){const f=n.flush();f&&s.push(this.push(f,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l)return r.executeEnd=ja(),[gT(e)];const u=c.flush(o);return ry(u)?u.then(f=>(this.flushRemux(s,f,e),s)):(this.flushRemux(s,u,e),s)}flushRemux(e,r,n){const{audioTrack:i,videoTrack:a,id3Track:s,textTrack:o}=r,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;G.log(`[transmuxer.ts]: Flushed fragment ${n.sn}${n.part>-1?" p: "+n.part:""} of level ${n.level}`);const u=this.remuxer.remux(i,a,s,o,l,c,!0,this.id);e.push({remuxResult:u,chunkMeta:n}),n.transmuxing.executeEnd=ja()}resetInitialTimestamp(e){const{demuxer:r,remuxer:n}=this;!r||!n||(r.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:r}=this;!e||!r||(e.resetContiguity(),r.resetNextTimestamp())}resetInitSegment(e,r,n,i,a){const{demuxer:s,remuxer:o}=this;!s||!o||(s.resetInitSegment(e,r,n,i),o.resetInitSegment(e,r,n,a))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,r,n,i,a){let s;return r&&r.method==="SAMPLE-AES"?s=this.transmuxSampleAes(e,r,n,i,a):s=this.transmuxUnencrypted(e,n,i,a),s}transmuxUnencrypted(e,r,n,i){const{audioTrack:a,videoTrack:s,id3Track:o,textTrack:c}=this.demuxer.demux(e,r,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(a,s,o,c,r,n,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,r,n,i,a){return this.demuxer.demuxSampleAes(e,r,n).then(s=>({remuxResult:this.remuxer.remux(s.audioTrack,s.videoTrack,s.id3Track,s.textTrack,n,i,!1,this.id),chunkMeta:a}))}configureTransmuxer(e){const{config:r,observer:n,typeSupported:i,vendor:a}=this;let s;for(let f=0,d=mT.length;f0&&e!=null&&e.key!=null&&e.iv!==null&&e.method!=null&&(r=e),r}const gT=t=>({remuxResult:{},chunkMeta:t});function ry(t){return"then"in t&&t.then instanceof Function}class DGe{constructor(e,r,n,i,a){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=r,this.initSegmentData=n,this.duration=i,this.defaultInitPts=a||null}}class MGe{constructor(e,r,n,i,a,s){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=r,this.accurateTimeOffset=n,this.trackSwitch=i,this.timeOffset=a,this.initSegmentChange=s}}var np={},FGe={get exports(){return np},set exports(t){np=t}};(function(t){var e=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function i(c,l,u){this.fn=c,this.context=l,this.once=u||!1}function a(c,l,u,f,d){if(typeof u!="function")throw new TypeError("The listener must be a function");var h=new i(u,f||c,d),p=r?r+l:l;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],h]:c._events[p].push(h):(c._events[p]=h,c._eventsCount++),c}function s(c,l){--c._eventsCount===0?c._events=new n:delete c._events[l]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],u,f;if(this._eventsCount===0)return l;for(f in u=this._events)e.call(u,f)&&l.push(r?f.slice(1):f);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(u)):l},o.prototype.listeners=function(l){var u=r?r+l:l,f=this._events[u];if(!f)return[];if(f.fn)return[f.fn];for(var d=0,h=f.length,p=new Array(h);d!1};class QQ{constructor(e,r,n,i){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const a=e.config;this.hls=e,this.id=r,this.useWorker=!!a.enableWorker,this.onTransmuxComplete=n,this.onFlush=i;const s=(l,u)=>{u=u||{},u.frag=this.frag,u.id=this.id,l===$.ERROR&&(this.error=u.error),this.hls.trigger(l,u)};this.observer=new np,this.observer.on($.FRAG_DECRYPTED,s),this.observer.on($.ERROR,s);const o={mp4:vT.isTypeSupported("video/mp4"),mpeg:vT.isTypeSupported("audio/mpeg"),mp3:vT.isTypeSupported('audio/mp4; codecs="mp3"')},c=navigator.vendor;if(this.useWorker&&typeof Worker<"u"&&(a.workerPath||aGe())){try{a.workerPath?(G.log(`loading Web Worker ${a.workerPath} for "${r}"`),this.workerContext=oGe(a.workerPath)):(G.log(`injecting Web Worker for "${r}"`),this.workerContext=sGe()),this.onwmsg=f=>this.onWorkerMessage(f);const{worker:u}=this.workerContext;u.addEventListener("message",this.onwmsg),u.onerror=f=>{const d=new Error(`${f.message} (${f.filename}:${f.lineno})`);a.enableWorker=!1,G.warn(`Error in "${r}" Web Worker, fallback to inline`),this.hls.trigger($.ERROR,{type:ye.OTHER_ERROR,details:q.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})},u.postMessage({cmd:"init",typeSupported:o,vendor:c,id:r,config:JSON.stringify(a)})}catch(u){G.warn(`Error setting up "${r}" Web Worker, fallback to inline`,u),this.resetWorker(),this.error=null,this.transmuxer=new cB(this.observer,o,a,c,r)}return}this.transmuxer=new cB(this.observer,o,a,c,r)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:r}=this.workerContext;r&&self.URL.revokeObjectURL(r),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const r=this.transmuxer;r&&(r.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,r,n,i,a,s,o,c,l,u){var f,d;l.transmuxing.start=self.performance.now();const{transmuxer:h}=this,p=s?s.start:a.start,v=a.decryptdata,m=this.frag,g=!(m&&a.cc===m.cc),y=!(m&&l.level===m.level),x=m?l.sn-m.sn:-1,b=this.part?l.part-this.part.index:-1,_=x===0&&l.id>1&&l.id===(m==null?void 0:m.stats.chunkCount),S=!y&&(x===1||x===0&&(b===1||_&&b<=0)),w=self.performance.now();(y||x||a.stats.parsing.start===0)&&(a.stats.parsing.start=w),s&&(b||!S)&&(s.stats.parsing.start=w);const R=!(m&&((f=a.initSegment)==null?void 0:f.url)===((d=m.initSegment)==null?void 0:d.url)),I=new MGe(g,S,c,y,p,R);if(!S||g||R){G.log(`[transmuxer-interface, ${a.type}]: Starting new transmux session for sn: ${l.sn} p: ${l.part} level: ${l.level} id: ${l.id}
+ discontinuity: ${g}
+ trackSwitch: ${y}
+ contiguous: ${S}
+ accurateTimeOffset: ${c}
+ timeOffset: ${p}
+ initSegmentChange: ${R}`);const T=new DGe(n,i,r,o,u);this.configureTransmuxer(T)}if(this.frag=a,this.part=s,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:v,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(h){const T=h.push(e,v,l,I);ry(T)?(h.async=!0,T.then(C=>{this.handleTransmuxComplete(C)}).catch(C=>{this.transmuxerError(C,l,"transmuxer-interface push error")})):(h.async=!1,this.handleTransmuxComplete(T))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(r){let n=r.flush(e);ry(n)||r.async?(ry(n)||(n=Promise.resolve(n)),n.then(a=>{this.handleFlushResult(a,e)}).catch(a=>{this.transmuxerError(a,e,"transmuxer-interface flush error")})):this.handleFlushResult(n,e)}}transmuxerError(e,r,n){this.hls&&(this.error=e,this.hls.trigger($.ERROR,{type:ye.MEDIA_ERROR,details:q.FRAG_PARSING_ERROR,chunkMeta:r,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,r){e.forEach(n=>{this.handleTransmuxComplete(n)}),this.onFlush(r)}onWorkerMessage(e){const r=e.data,n=this.hls;switch(r.event){case"init":{var i;const a=(i=this.workerContext)==null?void 0:i.objectURL;a&&self.URL.revokeObjectURL(a);break}case"transmuxComplete":{this.handleTransmuxComplete(r.data);break}case"flush":{this.onFlush(r.data);break}case"workerLog":G[r.data.logType]&&G[r.data.logType](r.data.message);break;default:{r.data=r.data||{},r.data.frag=this.frag,r.data.id=this.id,n.trigger(r.event,r.data);break}}}configureTransmuxer(e){const{transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):r&&r.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const BGe=250,yT=2,UGe=.1,jGe=.05;class HGe{constructor(e,r,n,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=r,this.fragmentTracker=n,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,r){const{config:n,media:i,stalled:a}=this;if(i===null)return;const{currentTime:s,seeking:o}=i,c=this.seeking&&!o,l=!this.seeking&&o;if(this.seeking=o,s!==e){if(this.moved=!0,a!==null){if(this.stallReported){const g=self.performance.now()-a;G.warn(`playback not stuck anymore @${s}, after ${Math.round(g)}ms`),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}return}if(l||c){this.stalled=null;return}if(i.paused&&!o||i.ended||i.playbackRate===0||!ct.getBuffered(i).length)return;const u=ct.bufferInfo(i,s,0),f=u.len>0,d=u.nextStart||0;if(!f&&!d)return;if(o){const g=u.len>yT,y=!d||r&&r.start<=s||d-s>yT&&!this.fragmentTracker.getPartialFragment(s);if(g||y)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var h;const g=Math.max(d,u.start||0)-s,y=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,b=(y==null||(h=y.details)==null?void 0:h.live)?y.details.targetduration*2:yT,_=this.fragmentTracker.getPartialFragment(s);if(g>0&&(g<=b||_)){this._trySkipBufferHole(_);return}}const p=self.performance.now();if(a===null){this.stalled=p;return}const v=p-a;if(!o&&v>=BGe&&(this._reportStall(u),!this.media))return;const m=ct.bufferInfo(i,s,n.maxBufferHole);this._tryFixBufferStall(m,v)}_tryFixBufferStall(e,r){const{config:n,fragmentTracker:i,media:a}=this;if(a===null)return;const s=a.currentTime,o=i.getPartialFragment(s);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>n.maxBufferHole||e.nextStart&&e.nextStart-sn.highBufferWatchdogPeriod*1e3&&(G.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:r,media:n,stallReported:i}=this;if(!i&&n){this.stallReported=!0;const a=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${JSON.stringify(e)})`);G.warn(a.message),r.trigger($.ERROR,{type:ye.MEDIA_ERROR,details:q.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len})}}_trySkipBufferHole(e){const{config:r,hls:n,media:i}=this;if(i===null)return 0;const a=i.currentTime,s=ct.bufferInfo(i,a,0),o=a0&&s.len<1&&i.readyState<3,u=o-a;if(u>0&&(c||l)){if(u>r.maxBufferHole){const{fragmentTracker:d}=this;let h=!1;if(a===0){const p=d.getAppendedFrag(0,xe.MAIN);p&&o1?(i=0,this.bitrateTest=!0):i=n.nextAutoLevel),this.level=n.nextLoadLevel=i,this.loadedmetadata=!1}r>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=X.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=X.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case X.WAITING_LEVEL:{var e;const{levels:n,level:i}=this,a=n==null||(e=n[i])==null?void 0:e.details;if(a&&(!a.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(a))break;this.state=X.IDLE;break}break}case X.FRAG_LOADING_WAITING_RETRY:{var r;const n=self.performance.now(),i=this.retryDate;(!i||n>=i||(r=this.media)!=null&&r.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=X.IDLE)}break}this.state===X.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:r,levels:n,media:i}=this,{config:a,nextLoadLevel:s}=e;if(r===null||!i&&(this.startFragRequested||!a.startFragPrefetch)||this.altAudio&&this.audioOnly||!(n!=null&&n[s]))return;const o=n[s],c=this.getMainFwdBufferInfo();if(c===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(c,l)){const m={};this.altAudio&&(m.type="video"),this.hls.trigger($.BUFFER_EOS,m),this.state=X.ENDED;return}e.loadLevel!==s&&e.manualLevel===-1&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const u=o.details;if(!u||this.state===X.WAITING_LEVEL||u.live&&this.levelLastLoaded!==s){this.level=s,this.state=X.WAITING_LEVEL;return}const f=c.len,d=this.getMaxBufferLength(o.maxBitrate);if(f>=d)return;this.backtrackFragment&&this.backtrackFragment.start>c.end&&(this.backtrackFragment=null);const h=this.backtrackFragment?this.backtrackFragment.start:c.end;let p=this.getNextFragment(h,u);if(this.couldBacktrack&&!this.fragPrevious&&p&&p.sn!=="initSegment"&&this.fragmentTracker.getState(p)!==Tr.OK){var v;const g=((v=this.backtrackFragment)!=null?v:p).sn-u.startSN,y=u.fragments[g-1];y&&p.cc===y.cc&&(p=y,this.fragmentTracker.removeFragment(y))}else this.backtrackFragment&&c.len&&(this.backtrackFragment=null);if(p&&this.isLoopLoading(p,h)){if(!p.gap){const g=this.audioOnly&&!this.altAudio?Qe.AUDIO:Qe.VIDEO,y=(g===Qe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,g,xe.MAIN)}p=this.getNextFragmentLoopLoading(p,u,c,xe.MAIN,d)}p&&(p.initSegment&&!p.initSegment.data&&!this.bitrateTest&&(p=p.initSegment),this.loadFragment(p,o,h))}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);this.fragCurrent=e,i===Tr.NOT_LOADED?e.sn==="initSegment"?this._loadInitSegment(e,r):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,r)):(this.startFragRequested=!0,super.loadFragment(e,r,n)):this.clearTrackerIfNeeded(e)}getAppendedFrag(e){const r=this.fragmentTracker.getAppendedFrag(e,xe.MAIN);return r&&"fragment"in r?r.fragment:r}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,xe.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:r}=this;if(r!=null&&r.readyState){let n;const i=this.getAppendedFrag(r.currentTime);if(i&&i.start>1&&this.flushMainBuffer(0,i.start-1),!r.paused&&e){const s=this.hls.nextLoadLevel,o=e[s],c=this.fragLastKbps;c&&this.fragCurrent?n=this.fragCurrent.duration*o.maxBitrate/(1e3*c)+1:n=0}else n=0;const a=this.getBufferedFrag(r.currentTime+n);if(a){const s=this.followingBufferedFrag(a);if(s){this.abortCurrentFrag();const o=s.maxStartPTS?s.maxStartPTS:s.start,c=s.duration,l=Math.max(a.end,o+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*.5),c*.75));this.flushMainBuffer(l,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 X.KEY_LOADING:case X.FRAG_LOADING:case X.FRAG_LOADING_WAITING_RETRY:case X.PARSING:case X.PARSED:this.state=X.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,r){super.flushMainBuffer(e,r,this.altAudio?"video":null)}onMediaAttached(e,r){super.onMediaAttached(e,r);const n=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),n.addEventListener("playing",this.onvplaying),n.addEventListener("seeked",this.onvseeked),this.gapController=new HGe(this.config,n,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,r=e?e.currentTime:null;me(r)&&this.log(`Media seeked to ${r.toFixed(3)}`);const n=this.getMainFwdBufferInfo();if(n===null||n.len===0){this.warn(`Main forward buffer length on "seeked" event ${n?n.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger($.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null,this.backtrackFragment=null}onManifestParsed(e,r){let n=!1,i=!1,a;r.levels.forEach(s=>{a=s.audioCodec,a&&(a.indexOf("mp4a.40.2")!==-1&&(n=!0),a.indexOf("mp4a.40.5")!==-1&&(i=!0))}),this.audioCodecSwitch=n&&i&&!iGe(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=r.levels,this.startFragRequested=!1}onLevelLoading(e,r){const{levels:n}=this;if(!n||this.state!==X.IDLE)return;const i=n[r.level];(!i.details||i.details.live&&this.levelLastLoaded!==r.level||this.waitForCdnTuneIn(i.details))&&(this.state=X.WAITING_LEVEL)}onLevelLoaded(e,r){var n;const{levels:i}=this,a=r.level,s=r.details,o=s.totalduration;if(!i){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${s.startSN},${s.endSN}], cc [${s.startCC}, ${s.endCC}] duration:${o}`);const c=i[a],l=this.fragCurrent;l&&(this.state===X.FRAG_LOADING||this.state===X.FRAG_LOADING_WAITING_RETRY)&&(l.level!==r.level||l.urlId!==c.urlId)&&l.loader&&this.abortCurrentFrag();let u=0;if(s.live||(n=c.details)!=null&&n.live){if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed)return;u=this.alignPlaylists(s,c.details)}if(c.details=s,this.levelLastLoaded=a,this.hls.trigger($.LEVEL_UPDATED,{details:s,level:a}),this.state===X.WAITING_LEVEL){if(this.waitForCdnTuneIn(s))return;this.state=X.IDLE}this.startFragRequested?s.live&&this.synchronizeToLiveEdge(s):this.setStartPosition(s,u),this.tick()}_handleFragmentLoadProgress(e){var r;const{frag:n,part:i,payload:a}=e,{levels:s}=this;if(!s){this.warn(`Levels were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const o=s[n.level],c=o.details;if(!c){this.warn(`Dropping fragment ${n.sn} of level ${n.level} after level details were reset`),this.fragmentTracker.removeFragment(n);return}const l=o.videoCodec,u=c.PTSKnown||!c.live,f=(r=n.initSegment)==null?void 0:r.data,d=this._getAudioCodec(o),h=this.transmuxer=this.transmuxer||new QQ(this.hls,xe.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),p=i?i.index:-1,v=p!==-1,m=new LO(n.level,n.sn,n.stats.chunkCount,a.byteLength,p,v),g=this.initPTS[n.cc];h.push(a,f,d,l,n,i,c.totalduration,u,m,g)}onAudioTrackSwitching(e,r){const n=this.altAudio;if(!!!r.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const s=this.fragCurrent;s&&(this.log("Switching to main audio track, cancel main fragment load"),s.abortRequests(),this.fragmentTracker.removeFragment(s)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const a=this.hls;n&&(a.trigger($.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),a.trigger($.AUDIO_TRACK_SWITCHED,r)}}onAudioTrackSwitched(e,r){const n=r.id,i=!!this.hls.audioTracks[n].url;if(i){const a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=i,this.tick()}onBufferCreated(e,r){const n=r.tracks;let i,a,s=!1;for(const o in n){const c=n[o];if(c.id==="main"){if(a=o,i=c,o==="video"){const l=n[o];l&&(this.videoBuffer=l.buffer)}}else s=!0}s&&i?(this.log(`Alternate track found, use ${a}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,r){const{frag:n,part:i}=r;if(n&&n.type!==xe.MAIN)return;if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${i?" p: "+i.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===X.PARSED&&(this.state=X.IDLE);return}const a=i?i.stats:n.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),n.sn!=="initSegment"&&(this.fragPrevious=n),this.fragBufferedComplete(n,i)}onError(e,r){var n;if(r.fatal){this.state=X.ERROR;return}switch(r.details){case q.FRAG_GAP:case q.FRAG_PARSING_ERROR:case q.FRAG_DECRYPT_ERROR:case q.FRAG_LOAD_ERROR:case q.FRAG_LOAD_TIMEOUT:case q.KEY_LOAD_ERROR:case q.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(xe.MAIN,r);break;case q.LEVEL_LOAD_ERROR:case q.LEVEL_LOAD_TIMEOUT:case q.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===X.WAITING_LEVEL&&((n=r.context)==null?void 0:n.type)===He.LEVEL&&(this.state=X.IDLE);break;case q.BUFFER_FULL_ERROR:if(!r.parent||r.parent!=="main")return;this.reduceLengthAndFlushBuffer(r)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case q.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}checkBuffer(){const{media:e,gapController:r}=this;if(!(!e||!r||!e.readyState)){if(this.loadedmetadata||!ct.getBuffered(e).length){const n=this.state!==X.IDLE?this.fragCurrent:null;r.poll(this.lastCurrentTime,n)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=X.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:r}){if(r!==Qe.AUDIO||this.audioOnly&&!this.altAudio){const n=(r===Qe.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(n,r,xe.MAIN)}}onLevelsUpdated(e,r){this.levels=r.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const r=e.currentTime;let n=this.startPosition;if(n>=0&&r0&&(s{const{hls:i}=this;if(!n||this.fragContextChanged(e))return;r.fragmentError=0,this.state=X.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=e.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger($.FRAG_LOADED,n),e.bitrateTest=!1})}_handleTransmuxComplete(e){var r;const n="main",{hls:i}=this,{remuxResult:a,chunkMeta:s}=e,o=this.getCurrentContext(s);if(!o){this.resetWhenMissingContext(s);return}const{frag:c,part:l,level:u}=o,{video:f,text:d,id3:h,initSegment:p}=a,{details:v}=u,m=this.altAudio?void 0:a.audio;if(this.fragContextChanged(c)){this.fragmentTracker.removeFragment(c);return}if(this.state=X.PARSING,p){p.tracks&&(this._bufferInitSegment(u,p.tracks,c,s),i.trigger($.FRAG_PARSING_INIT_SEGMENT,{frag:c,id:n,tracks:p.tracks}));const g=p.initPTS,y=p.timescale;me(g)&&(this.initPTS[c.cc]={baseTime:g,timescale:y},i.trigger($.INIT_PTS_FOUND,{frag:c,id:n,initPTS:g,timescale:y}))}if(f&&a.independent!==!1){if(v){const{startPTS:g,endPTS:y,startDTS:x,endDTS:b}=f;if(l)l.elementaryStreams[f.type]={startPTS:g,endPTS:y,startDTS:x,endDTS:b};else if(f.firstKeyFrame&&f.independent&&s.id===1&&(this.couldBacktrack=!0),f.dropped&&f.independent){const _=this.getMainFwdBufferInfo(),S=(_?_.end:this.getLoadPosition())+this.config.maxBufferHole,w=f.firstKeyFramePTS?f.firstKeyFramePTS:g;if(S{const u=r[c].initSegment;u!=null&&u.byteLength&&this.hls.trigger($.BUFFER_APPENDING,{type:c,data:u,frag:n,part:null,chunkMeta:i,parent:n.type})}),this.tick()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,xe.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=X.IDLE}checkFragmentChanged(){const e=this.media;let r=null;if(e&&e.readyState>1&&e.seeking===!1){const n=e.currentTime;if(ct.isBuffered(e,n)?r=this.getAppendedFrag(n):ct.isBuffered(e,n+.1)&&(r=this.getAppendedFrag(n+.1)),r){this.backtrackFragment=null;const i=this.fragPlaying,a=r.level;(!i||r.sn!==i.sn||i.level!==a||r.urlId!==i.urlId)&&(this.fragPlaying=r,this.hls.trigger($.FRAG_CHANGED,{frag:r}),(!i||i.level!==a)&&this.hls.trigger($.LEVEL_SWITCHED,{level:a}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const r=e.currentTime,n=this.currentFrag;if(n&&me(r)&&me(n.programDateTime)){const i=n.programDateTime+(r-n.start)*1e3;return new Date(i)}}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 Xc{constructor(e,r=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=r,this.totalWeight_=n}sample(e,r){const n=Math.pow(this.alpha_,e);this.estimate_=r*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class VGe{constructor(e,r,n,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Xc(e),this.fast_=new Xc(r),this.defaultTTFB_=i,this.ttfb_=new Xc(e)}update(e,r){const{slow_:n,fast_:i,ttfb_:a}=this;n.halfLife!==e&&(this.slow_=new Xc(e,n.getEstimate(),n.getTotalWeight())),i.halfLife!==r&&(this.fast_=new Xc(r,i.getEstimate(),i.getTotalWeight())),a.halfLife!==e&&(this.ttfb_=new Xc(e,a.getEstimate(),a.getTotalWeight()))}sample(e,r){e=Math.max(e,this.minDelayMs_);const n=8*r,i=e/1e3,a=n/i;this.fast_.sample(i,a),this.slow_.sample(i,a)}sampleTTFB(e){const r=e/1e3,n=Math.sqrt(2)*Math.exp(-Math.pow(r,2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}class WGe{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=e;const r=e.config;this.bwEstimator=new VGe(r.abrEwmaSlowVoD,r.abrEwmaFastVoD,r.abrEwmaDefaultEstimate),this.registerListeners()}registerListeners(){const{hls:e}=this;e.on($.FRAG_LOADING,this.onFragLoading,this),e.on($.FRAG_LOADED,this.onFragLoaded,this),e.on($.FRAG_BUFFERED,this.onFragBuffered,this),e.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on($.LEVEL_LOADED,this.onLevelLoaded,this)}unregisterListeners(){const{hls:e}=this;e.off($.FRAG_LOADING,this.onFragLoading,this),e.off($.FRAG_LOADED,this.onFragLoaded,this),e.off($.FRAG_BUFFERED,this.onFragBuffered,this),e.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off($.LEVEL_LOADED,this.onLevelLoaded,this)}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null}onFragLoading(e,r){var n;const i=r.frag;this.ignoreFragment(i)||(this.fragCurrent=i,this.partCurrent=(n=r.part)!=null?n:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))}onLevelSwitching(e,r){this.clearTimer()}getTimeToLoadFrag(e,r,n,i){const a=e+n/r,s=i?this.lastLevelLoadSec:0;return a+s}onLevelLoaded(e,r){const n=this.hls.config,{total:i,bwEstimate:a}=r.stats;me(i)&&me(a)&&(this.lastLevelLoadSec=8*i/a),r.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD)}_abandonRulesCheck(){const{fragCurrent:e,partCurrent:r,hls:n}=this,{autoLevelEnabled:i,media:a}=n;if(!e||!a)return;const s=performance.now(),o=r?r.stats:e.stats,c=r?r.duration:e.duration,l=s-o.loading.start;if(o.aborted||o.loaded&&o.loaded===o.total||e.level===0){this.clearTimer(),this._nextAutoLevel=-1;return}if(!i||a.paused||!a.playbackRate||!a.readyState)return;const u=n.mainForwardBufferInfo;if(u===null)return;const f=this.bwEstimator.getEstimateTTFB(),d=Math.abs(a.playbackRate);if(l<=Math.max(f,1e3*(c/(d*2))))return;const h=u.len/d;if(h>=2*c/d)return;const p=o.loading.first?o.loading.first-o.loading.start:-1,v=o.loaded&&p>-1,m=this.bwEstimator.getEstimate(),{levels:g,minAutoLevel:y}=n,x=g[e.level],b=o.total||Math.max(o.loaded,Math.round(c*x.maxBitrate/8));let _=l-p;_<1&&v&&(_=Math.min(l,o.loaded*8/m));const S=v?o.loaded*1e3/_:0,w=S?(b-o.loaded)/S:b*8/m+f/1e3;if(w<=h)return;const R=S?S*8:m;let I=Number.POSITIVE_INFINITY,T;for(T=e.level-1;T>y;T--){const C=g[T].maxBitrate;if(I=this.getTimeToLoadFrag(f/1e3,R,c*C,!g[T].details),I=w||I>c*10||(n.nextLoadLevel=T,v?this.bwEstimator.sample(l-Math.min(f,p),o.loaded):this.bwEstimator.sampleTTFB(l),this.clearTimer(),G.warn(`[abr] Fragment ${e.sn}${r?" part "+r.index:""} of level ${e.level} is loading too slowly;
+ Time to underbuffer: ${h.toFixed(3)} s
+ Estimated load time for current fragment: ${w.toFixed(3)} s
+ Estimated load time for down switch fragment: ${I.toFixed(3)} s
+ TTFB estimate: ${p}
+ Current BW estimate: ${me(m)?(m/1024).toFixed(3):"Unknown"} Kb/s
+ New BW estimate: ${(this.bwEstimator.getEstimate()/1024).toFixed(3)} Kb/s
+ Aborting and switching to level ${T}`),e.loader&&(this.fragCurrent=this.partCurrent=null,e.abortRequests()),n.trigger($.FRAG_LOAD_EMERGENCY_ABORTED,{frag:e,part:r,stats:o}))}onFragLoaded(e,{frag:r,part:n}){const i=n?n.stats:r.stats;if(r.type===xe.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),this.lastLoadedFragLevel=r.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){const a=n?n.duration:r.duration,s=this.hls.levels[r.level],o=(s.loaded?s.loaded.bytes:0)+i.loaded,c=(s.loaded?s.loaded.duration:0)+a;s.loaded={bytes:o,duration:c},s.realBitrate=Math.round(8*o/c)}if(r.bitrateTest){const a={stats:i,frag:r,part:n,id:r.type};this.onFragBuffered($.FRAG_BUFFERED,a),r.bitrateTest=!1}}}onFragBuffered(e,r){const{frag:n,part:i}=r,a=i!=null&&i.stats.loaded?i.stats:n.stats;if(a.aborted||this.ignoreFragment(n))return;const s=a.parsing.end-a.loading.start-Math.min(a.loading.first-a.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(s,a.loaded),a.bwEstimate=this.bwEstimator.getEstimate(),n.bitrateTest?this.bitrateTestDelay=s/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==xe.MAIN||e.sn==="initSegment"}clearTimer(){self.clearInterval(this.timer)}get nextAutoLevel(){const e=this._nextAutoLevel,r=this.bwEstimator;if(e!==-1&&!r.canEstimate())return e;let n=this.getNextABRAutoLevel();if(e!==-1){const i=this.hls.levels;if(i.length>Math.max(e,n)&&i[e].loadError<=i[n].loadError)return e}return e!==-1&&(n=Math.min(e,n)),n}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:r,hls:n}=this,{maxAutoLevel:i,config:a,minAutoLevel:s,media:o}=n,c=r?r.duration:e?e.duration:0,l=o&&o.playbackRate!==0?Math.abs(o.playbackRate):1,u=this.bwEstimator?this.bwEstimator.getEstimate():a.abrEwmaDefaultEstimate,f=n.mainForwardBufferInfo,d=(f?f.len:0)/l;let h=this.findBestLevel(u,s,i,d,a.abrBandWidthFactor,a.abrBandWidthUpFactor);if(h>=0)return h;G.trace(`[abr] ${d?"rebuffering expected":"buffer is empty"}, finding optimal quality level`);let p=c?Math.min(c,a.maxStarvationDelay):a.maxStarvationDelay,v=a.abrBandWidthFactor,m=a.abrBandWidthUpFactor;if(!d){const g=this.bitrateTestDelay;g&&(p=(c?Math.min(c,a.maxLoadingDelay):a.maxLoadingDelay)-g,G.trace(`[abr] bitrate test took ${Math.round(1e3*g)}ms, set first fragment max fetchDuration to ${Math.round(1e3*p)} ms`),v=m=1)}return h=this.findBestLevel(u,s,i,d+p,v,m),Math.max(h,0)}findBestLevel(e,r,n,i,a,s){var o;const{fragCurrent:c,partCurrent:l,lastLoadedFragLevel:u}=this,{levels:f}=this.hls,d=f[u],h=!!(d!=null&&(o=d.details)!=null&&o.live),p=d==null?void 0:d.codecSet,v=l?l.duration:c?c.duration:0,m=this.bwEstimator.getEstimateTTFB()/1e3;let g=r,y=-1;for(let x=n;x>=r;x--){const b=f[x];if(!b||p&&b.codecSet!==p){b&&(g=Math.min(x,g),y=Math.max(x,y));continue}y!==-1&&G.trace(`[abr] Skipped level(s) ${g}-${y} with CODECS:"${f[y].attrs.CODECS}"; not compatible with "${d.attrs.CODECS}"`);const _=b.details,S=(l?_==null?void 0:_.partTarget:_==null?void 0:_.averagetargetduration)||v;let w;x<=u?w=a*e:w=s*e;const R=f[x].maxBitrate,I=this.getTimeToLoadFrag(m,w,R*S,_===void 0);if(G.trace(`[abr] level:${x} adjustedbw-bitrate:${Math.round(w-R)} avgDuration:${S.toFixed(1)} maxFetchDuration:${i.toFixed(1)} fetchDuration:${I.toFixed(1)}`),w>R&&(I===0||!me(I)||h&&!this.bitrateTestDelay||I0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r,this.state=X.IDLE):(this.loadedmetadata=!1,this.state=X.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case X.IDLE:this.doTickIdle();break;case X.WAITING_TRACK:{var e;const{levels:n,trackId:i}=this,a=n==null||(e=n[i])==null?void 0:e.details;if(a){if(this.waitForCdnTuneIn(a))break;this.state=X.WAITING_INIT_PTS}break}case X.FRAG_LOADING_WAITING_RETRY:{var r;const n=performance.now(),i=this.retryDate;(!i||n>=i||(r=this.media)!=null&&r.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=X.IDLE);break}case X.WAITING_INIT_PTS:{const n=this.waitingData;if(n){const{frag:i,part:a,cache:s,complete:o}=n;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=X.FRAG_LOADING;const c=s.flush(),l={frag:i,part:a,payload:c,networkDetails:null};this._handleFragmentLoadProgress(l),o&&super._handleFragmentLoadComplete(l)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const c=this.getLoadPosition(),l=ct.bufferInfo(this.mediaBuffer,c,this.config.maxBufferHole);QA(l.end,this.config.maxFragLookUpTolerance,i)<0&&(this.log(`Waiting fragment cc (${i.cc}) @ ${i.start} cancelled because another fragment at ${l.end} is needed`),this.clearWaitingFragment())}}else this.state=X.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=X.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:r,media:n,trackId:i}=this,a=e.config;if(!(r!=null&&r[i])||!n&&(this.startFragRequested||!a.startFragPrefetch))return;const s=r[i],o=s.details;if(!o||o.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(o)){this.state=X.WAITING_TRACK;return}const c=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&c&&(this.bufferFlushed=!1,this.afterBufferFlushed(c,Qe.AUDIO,xe.AUDIO));const l=this.getFwdBufferInfo(c,xe.AUDIO);if(l===null)return;const{bufferedTrack:u,switchingTrack:f}=this;if(!f&&this._streamEnded(l,o)){e.trigger($.BUFFER_EOS,{type:"audio"}),this.state=X.ENDED;return}const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,xe.MAIN),h=l.len,p=this.getMaxBufferLength(d==null?void 0:d.len);if(h>=p&&!f)return;const m=o.fragments[0].start;let g=l.end;if(f&&n){const _=this.getLoadPosition();u&&f.attrs!==u.attrs&&(g=_),o.PTSKnown&&_m||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=m+.05)}let y=this.getNextFragment(g,o),x=!1;if(y&&this.isLoopLoading(y,g)&&(x=!!y.gap,y=this.getNextFragmentLoopLoading(y,o,l,xe.MAIN,p)),!y){this.bufferFlushed=!0;return}const b=d&&y.start>d.end+o.targetduration;if(b||!(d!=null&&d.len)&&l.len){const _=this.fragmentTracker.getBufferedFrag(y.start,xe.MAIN);if(_===null||(x||(x=!!_.gap||!!b&&d.len===0),b&&!x||x&&l.nextStart&&l.nextStart<_.end))return}this.loadFragment(y,s,g)}getMaxBufferLength(e){const r=super.getMaxBufferLength();return e?Math.min(Math.max(r,e),this.config.maxMaxBufferLength):r}onMediaDetaching(){this.videoBuffer=null,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:r}){this.resetTransmuxer(),this.levels=r.map(n=>new tp(n))}onAudioTrackSwitching(e,r){const n=!!r.url;this.trackId=r.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),n?this.setInterval(uB):this.resetTransmuxer(),n?(this.switchingTrack=r,this.state=X.IDLE):(this.switchingTrack=null,this.bufferedTrack=r,this.state=X.STOPPED),this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=!1,this.bufferedTrack=null,this.switchingTrack=null}onLevelLoaded(e,r){this.mainDetails=r.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger($.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,r){var n;if(this.mainDetails==null){this.cachedTrackLoadedData=r;return}const{levels:i}=this,{details:a,id:s}=r;if(!i){this.warn(`Audio tracks were reset while loading level ${s}`);return}this.log(`Track ${s} loaded [${a.startSN},${a.endSN}],duration:${a.totalduration}`);const o=i[s];let c=0;if(a.live||(n=o.details)!=null&&n.live){const l=this.mainDetails;if(a.fragments[0]||(a.deltaUpdateFailed=!0),a.deltaUpdateFailed||!l)return;!o.details&&a.hasProgramDateTime&&l.hasProgramDateTime?(MQ(a,l),c=a.fragments[0].start):c=this.alignPlaylists(a,o.details)}o.details=a,this.levelLastLoaded=s,!this.startFragRequested&&(this.mainDetails||!a.live)&&this.setStartPosition(o.details,c),this.state===X.WAITING_TRACK&&!this.waitForCdnTuneIn(a)&&(this.state=X.IDLE),this.tick()}_handleFragmentLoadProgress(e){var r;const{frag:n,part:i,payload:a}=e,{config:s,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const u=l.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const f=s.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new QQ(this.hls,xe.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const h=this.initPTS[n.cc],p=(r=n.initSegment)==null?void 0:r.data;if(h!==void 0){const m=i?i.index:-1,g=m!==-1,y=new LO(n.level,n.sn,n.stats.chunkCount,a.byteLength,m,g);d.push(a,p,f,"",n,i,u.totalduration,!1,y,h)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:v}=this.waitingData=this.waitingData||{frag:n,part:i,cache:new ZQ,complete:!1};v.push(new Uint8Array(a)),this.waitingVideoCC=this.videoTrackCC,this.state=X.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,r){const n=r.tracks.audio;n&&(this.mediaBuffer=n.buffer||null),r.tracks.video&&(this.videoBuffer=r.tracks.video.buffer||null)}onFragBuffered(e,r){const{frag:n,part:i}=r;if(n.type!==xe.AUDIO){if(!this.loadedmetadata&&n.type===xe.MAIN){var a;(a=this.videoBuffer||this.media)!=null&&a.buffered.length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${i?" p: "+i.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(n.sn!=="initSegment"){this.fragPrevious=n;const s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger($.AUDIO_TRACK_SWITCHED,sn({},s)))}this.fragBufferedComplete(n,i)}onError(e,r){var n;if(r.fatal){this.state=X.ERROR;return}switch(r.details){case q.FRAG_GAP:case q.FRAG_PARSING_ERROR:case q.FRAG_DECRYPT_ERROR:case q.FRAG_LOAD_ERROR:case q.FRAG_LOAD_TIMEOUT:case q.KEY_LOAD_ERROR:case q.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(xe.AUDIO,r);break;case q.AUDIO_TRACK_LOAD_ERROR:case q.AUDIO_TRACK_LOAD_TIMEOUT:case q.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===X.WAITING_TRACK&&((n=r.context)==null?void 0:n.type)===He.AUDIO_TRACK&&(this.state=X.IDLE);break;case q.BUFFER_FULL_ERROR:if(!r.parent||r.parent!=="audio")return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case q.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onBufferFlushed(e,{type:r}){r===Qe.AUDIO&&(this.bufferFlushed=!0,this.state===X.ENDED&&(this.state=X.IDLE))}_handleTransmuxComplete(e){var r;const n="audio",{hls:i}=this,{remuxResult:a,chunkMeta:s}=e,o=this.getCurrentContext(s);if(!o){this.resetWhenMissingContext(s);return}const{frag:c,part:l,level:u}=o,{details:f}=u,{audio:d,text:h,id3:p,initSegment:v}=a;if(this.fragContextChanged(c)||!f){this.fragmentTracker.removeFragment(c);return}if(this.state=X.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),v!=null&&v.tracks&&(this._bufferInitSegment(v.tracks,c,s),i.trigger($.FRAG_PARSING_INIT_SEGMENT,{frag:c,id:n,tracks:v.tracks})),d){const{startPTS:m,endPTS:g,startDTS:y,endDTS:x}=d;l&&(l.elementaryStreams[Qe.AUDIO]={startPTS:m,endPTS:g,startDTS:y,endDTS:x}),c.setElementaryStreamInfo(Qe.AUDIO,m,g,y,x),this.bufferFragmentData(d,c,l,s)}if(p!=null&&(r=p.samples)!=null&&r.length){const m=Pt({id:n,frag:c,details:f},p);i.trigger($.FRAG_PARSING_METADATA,m)}if(h){const m=Pt({id:n,frag:c,details:f},h);i.trigger($.FRAG_PARSING_USERDATA,m)}}_bufferInitSegment(e,r,n){if(this.state!==X.PARSING)return;e.video&&delete e.video;const i=e.audio;if(!i)return;i.levelCodec=i.codec,i.id="audio",this.log(`Init audio buffer, container:${i.container}, codecs[parsed]=[${i.codec}]`),this.hls.trigger($.BUFFER_CODECS,e);const a=i.initSegment;if(a!=null&&a.byteLength){const s={type:"audio",frag:r,part:null,chunkMeta:n,parent:r.type,data:a};this.hls.trigger($.BUFFER_APPENDING,s)}this.tick()}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||i===Tr.NOT_LOADED||i===Tr.PARTIAL){var a;e.sn==="initSegment"?this._loadInitSegment(e,r):(a=r.details)!=null&&a.live&&!this.initPTS[e.cc]?(this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=X.WAITING_INIT_PTS):(this.startFragRequested=!0,super.loadFragment(e,r,n))}else this.clearTrackerIfNeeded(e)}completeAudioSwitch(e){const{hls:r,media:n,bufferedTrack:i}=this,a=i==null?void 0:i.attrs,s=e.attrs;n&&a&&(a.CHANNELS!==s.CHANNELS||a.NAME!==s.NAME||a.LANGUAGE!==s.LANGUAGE)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")),this.bufferedTrack=e,this.switchingTrack=null,r.trigger($.AUDIO_TRACK_SWITCHED,sn({},e))}}class qGe extends OO{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.LEVEL_LOADING,this.onLevelLoading,this),e.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.LEVEL_LOADING,this.onLevelLoading,this),e.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off($.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,r){this.tracks=r.audioTracks||[]}onAudioTrackLoaded(e,r){const{id:n,groupId:i,details:a}=r,s=this.tracksInGroup[n];if(!s||s.groupId!==i){this.warn(`Track with id:${n} and group:${i} not found in active group ${s.groupId}`);return}const o=s.details;s.details=r.details,this.log(`audio-track ${n} "${s.name}" lang:${s.lang} group:${i} loaded [${a.startSN}-${a.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(e,r){this.switchLevel(r.level)}onLevelSwitching(e,r){this.switchLevel(r.level)}switchLevel(e){const r=this.hls.levels[e];if(!(r!=null&&r.audioGroupIds))return;const n=r.audioGroupIds[r.urlId];if(this.groupId!==n){this.groupId=n||null;const i=this.tracks.filter(s=>!n||s.groupId===n);this.selectDefaultTrack&&!i.some(s=>s.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=i;const a={audioTracks:i};this.log(`Updating audio tracks, ${i.length} track(s) found in group:${n}`),this.hls.trigger($.AUDIO_TRACKS_UPDATED,a),this.selectInitialTrack()}else this.shouldReloadPlaylist(this.currentTrack)&&this.setAudioTrack(this.trackId)}onError(e,r){r.fatal||!r.context||r.context.type===He.AUDIO_TRACK&&r.context.id===this.trackId&&r.context.groupId===this.groupId&&(this.requestScheduled=-1,this.checkRetry(r))}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioTrack(e){const r=this.tracksInGroup;if(e<0||e>=r.length){this.warn("Invalid id passed to audio-track controller");return}this.clearTimer();const n=this.currentTrack;r[this.trackId];const i=r[e],{groupId:a,name:s}=i;if(this.log(`Switching to audio-track ${e} "${s}" lang:${i.lang} group:${a}`),this.trackId=e,this.currentTrack=i,this.selectDefaultTrack=!1,this.hls.trigger($.AUDIO_TRACK_SWITCHING,sn({},i)),i.details&&!i.details.live)return;const o=this.switchParams(i.url,n==null?void 0:n.details);this.loadPlaylist(o)}selectInitialTrack(){const e=this.tracksInGroup,r=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(r!==-1)this.setAudioTrack(r);else{const n=new Error(`No track found for running audio group-ID: ${this.groupId} track count: ${e.length}`);this.warn(n.message),this.hls.trigger($.ERROR,{type:ye.MEDIA_ERROR,details:q.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:n})}}findTrackId(e){const r=this.tracksInGroup;for(let n=0;nt[n]!==e[n])}const fB=500;class QGe extends DO{constructor(e,r,n){super(e,r,n,"[subtitle-stream-controller]",xe.SUBTITLE),this.levels=[],this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.LEVEL_LOADED,this.onLevelLoaded,this),e.on($.ERROR,this.onError,this),e.on($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on($.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on($.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.LEVEL_LOADED,this.onLevelLoaded,this),e.off($.ERROR,this.onError,this),e.off($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off($.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off($.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=X.IDLE,this.setInterval(fB),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,r){this.mainDetails=r.details}onSubtitleFragProcessed(e,r){const{frag:n,success:i}=r;if(this.fragPrevious=n,this.state=X.IDLE,!i)return;const a=this.tracksBuffered[this.currentTrackId];if(!a)return;let s;const o=n.start;for(let l=0;l=a[l].start&&o<=a[l].end){s=a[l];break}const c=n.start+n.duration;s?s.end=c:(s={start:o,end:c},a.push(s)),this.fragmentTracker.fragBuffered(n)}onBufferFlushing(e,r){const{startOffset:n,endOffset:i}=r;if(n===0&&i!==Number.POSITIVE_INFINITY){const{currentTrackId:a,levels:s}=this;if(!s.length||!s[a]||!s[a].details)return;const c=s[a].details.targetduration,l=i-c;if(l<=0)return;r.endOffsetSubtitles=Math.max(0,l),this.tracksBuffered.forEach(u=>{for(let f=0;fnew tp(n));return}this.tracksBuffered=[],this.levels=r.map(n=>{const i=new tp(n);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,xe.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,r){if(this.currentTrackId=r.id,!this.levels.length||this.currentTrackId===-1){this.clearInterval();return}const n=this.levels[this.currentTrackId];n!=null&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.setInterval(fB)}onSubtitleTrackLoaded(e,r){var n;const{details:i,id:a}=r,{currentTrackId:s,levels:o}=this;if(!o.length)return;const c=o[s];if(a>=o.length||a!==s||!c)return;this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(i.live||(n=c.details)!=null&&n.live){const u=this.mainDetails;if(i.deltaUpdateFailed||!u)return;const f=u.fragments[0];c.details?(l=this.alignPlaylists(i,c.details),l===0&&f&&(l=f.start,XA(i,l))):i.hasProgramDateTime&&u.hasProgramDateTime?(MQ(i,u),l=i.fragments[0].start):f&&(l=f.start,XA(i,l))}c.details=i,this.levelLastLoaded=a,!this.startFragRequested&&(this.mainDetails||!i.live)&&this.setStartPosition(c.details,l),this.tick(),i.live&&!this.fragCurrent&&this.media&&this.state===X.IDLE&&(rp(null,i.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0))}_handleFragmentLoadComplete(e){const{frag:r,payload:n}=e,i=r.decryptdata,a=this.hls;if(!this.fragContextChanged(r)&&n&&n.byteLength>0&&i&&i.key&&i.iv&&i.method==="AES-128"){const s=performance.now();this.decrypter.decrypt(new Uint8Array(n),i.key.buffer,i.iv.buffer).catch(o=>{throw a.trigger($.ERROR,{type:ye.MEDIA_ERROR,details:q.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:r}),o}).then(o=>{const c=performance.now();a.trigger($.FRAG_DECRYPTED,{frag:r,payload:o,stats:{tstart:s,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=X.IDLE})}}doTick(){if(!this.media){this.state=X.IDLE;return}if(this.state===X.IDLE){const{currentTrackId:e,levels:r}=this,n=r[e];if(!r.length||!n||!n.details)return;const i=n.details,a=i.targetduration,{config:s}=this,o=this.getLoadPosition(),c=ct.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],o-a,s.maxBufferHole),{end:l,len:u}=c,f=this.getFwdBufferInfo(this.media,xe.MAIN),d=this.getMaxBufferLength(f==null?void 0:f.len)+a;if(u>d)return;const h=i.fragments,p=h.length,v=i.edge;let m=null;const g=this.fragPrevious;if(l{if(i=i>>>0,i>a-1)throw new DOMException(`Failed to execute '${n}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${a})`);return e[i][n]};this.buffered={get length(){return e.length},end(n){return r("end",n,e.length)},start(n){return r("start",n,e.length)}}}}class JGe extends OO{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.trackChangeListener=()=>this.onTextTracksChanged(),this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes(this.trackId)}registerListeners(){const{hls:e}=this;e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.LEVEL_LOADING,this.onLevelLoading,this),e.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.LEVEL_LOADING,this.onLevelLoading,this),e.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off($.ERROR,this.onError,this)}onMediaAttached(e,r){this.media=r.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),xT(this.media.textTracks).forEach(r=>{Ru(r)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,r){this.tracks=r.subtitleTracks}onSubtitleTrackLoaded(e,r){const{id:n,details:i}=r,{trackId:a}=this,s=this.tracksInGroup[a];if(!s){this.warn(`Invalid subtitle track id ${n}`);return}const o=s.details;s.details=r.details,this.log(`subtitle track ${n} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(e,r){this.switchLevel(r.level)}onLevelSwitching(e,r){this.switchLevel(r.level)}switchLevel(e){const r=this.hls.levels[e];if(!(r!=null&&r.textGroupIds))return;const n=r.textGroupIds[r.urlId],i=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==n){const a=this.tracks.filter(c=>!n||c.groupId===n);this.tracksInGroup=a;const s=this.findTrackId(i==null?void 0:i.name)||this.findTrackId();this.groupId=n||null;const o={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${n}" group-id`),this.hls.trigger($.SUBTITLE_TRACKS_UPDATED,o),s!==-1&&this.setSubtitleTrack(s,i)}else this.shouldReloadPlaylist(i)&&this.setSubtitleTrack(this.trackId,i)}findTrackId(e){const r=this.tracksInGroup;for(let n=0;no.groupId===this.groupId);if(e===-1)[].slice.call(i).forEach(o=>{o.mode="disabled"});else{const o=a[n];o&&(o.mode="disabled")}const s=a[e];s&&(s.mode=this.subtitleDisplay?"showing":"hidden")}setSubtitleTrack(e,r){var n;const i=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(this.trackId!==e&&this.toggleTrackModes(e),this.trackId===e&&(e===-1||(n=i[e])!=null&&n.details)||e<-1||e>=i.length)return;this.clearTimer();const a=i[e];if(this.log(`Switching to subtitle-track ${e}`+(a?` "${a.name}" lang:${a.lang} group:${a.groupId}`:"")),this.trackId=e,a){const{id:s,groupId:o="",name:c,type:l,url:u}=a;this.hls.trigger($.SUBTITLE_TRACK_SWITCH,{id:s,groupId:o,name:c,type:l,url:u});const f=this.switchParams(a.url,r==null?void 0:r.details);this.loadPlaylist(f)}else this.hls.trigger($.SUBTITLE_TRACK_SWITCH,{id:e})}onTextTracksChanged(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1;const r=xT(this.media.textTracks);for(let n=0;n{r=a}),i={execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(i,e),n}executeNext(e){const{buffers:r,queues:n}=this,i=r[e],a=n[e];if(a.length){const s=a[0];try{s.execute()}catch(o){G.warn("[buffer-operation-queue]: Unhandled exception executing the current operation"),s.onError(o),i!=null&&i.updating||(a.shift(),this.executeNext(e))}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const dB=MO(),hB=/([ha]vc.)(?:\.[^.,]+)+/;class tVe{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendError=0,this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this._onMediaSourceOpen=()=>{const{media:r,mediaSource:n}=this;G.log("[buffer-controller]: Media source opened"),r&&(r.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger($.MEDIA_ATTACHED,{media:r})),n&&n.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{G.log("[buffer-controller]: Media source closed")},this._onMediaSourceEnded=()=>{G.log("[buffer-controller]: Media source ended")},this._onMediaEmptied=()=>{const{media:r,_objectUrl:n}=this;r&&r.src!==n&&G.error(`Media element src was set while attaching MediaSource (${n} > ${r.src})`)},this.hls=e,this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null}registerListeners(){const{hls:e}=this;e.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.BUFFER_RESET,this.onBufferReset,this),e.on($.BUFFER_APPENDING,this.onBufferAppending,this),e.on($.BUFFER_CODECS,this.onBufferCodecs,this),e.on($.BUFFER_EOS,this.onBufferEos,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on($.LEVEL_UPDATED,this.onLevelUpdated,this),e.on($.FRAG_PARSED,this.onFragParsed,this),e.on($.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.BUFFER_RESET,this.onBufferReset,this),e.off($.BUFFER_APPENDING,this.onBufferAppending,this),e.off($.BUFFER_CODECS,this.onBufferCodecs,this),e.off($.BUFFER_EOS,this.onBufferEos,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off($.LEVEL_UPDATED,this.onLevelUpdated,this),e.off($.FRAG_PARSED,this.onFragParsed,this),e.off($.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new eVe(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null}onManifestParsed(e,r){let n=2;(r.audio&&!r.video||!r.altAudio)&&(n=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=n,this.details=null,G.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,r){const n=this.media=r.media;if(n&&dB){const i=this.mediaSource=new dB;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),n.src=self.URL.createObjectURL(i),this._objectUrl=n.src,n.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:r,_objectUrl:n}=this;if(r){if(G.log("[buffer-controller]: media source detaching"),r.readyState==="open")try{r.endOfStream()}catch(i){G.warn(`[buffer-controller]: onMediaDetaching: ${i.message} while calling endOfStream`)}this.onBufferReset(),r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),e&&(e.removeEventListener("emptied",this._onMediaEmptied),n&&self.URL.revokeObjectURL(n),e.src===n?(e.removeAttribute("src"),e.load()):G.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger($.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{const r=this.sourceBuffer[e];try{r&&(this.removeBufferListeners(e),this.mediaSource&&this.mediaSource.removeSourceBuffer(r),this.sourceBuffer[e]=void 0)}catch(n){G.warn(`[buffer-controller]: Failed to reset the ${e} buffer`,n)}}),this._initSourceBuffer()}onBufferCodecs(e,r){const n=this.getSourceBufferTypes().length;Object.keys(r).forEach(i=>{if(n){const a=this.tracks[i];if(a&&typeof a.buffer.changeType=="function"){const{id:s,codec:o,levelCodec:c,container:l,metadata:u}=r[i],f=(a.levelCodec||a.codec).replace(hB,"$1"),d=(c||o).replace(hB,"$1");if(f!==d){const h=`${l};codecs=${c||o}`;this.appendChangeType(i,h),G.log(`[buffer-controller]: switching codec ${f} to ${d}`),this.tracks[i]={buffer:a.buffer,codec:o,container:l,levelCodec:c,metadata:u,id:s}}}}else this.pendingTracks[i]=r[i]}),!n&&(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks())}appendChangeType(e,r){const{operationQueue:n}=this,i={execute:()=>{const a=this.sourceBuffer[e];a&&(G.log(`[buffer-controller]: changing ${e} sourceBuffer type to ${r}`),a.changeType(r)),n.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{G.warn(`[buffer-controller]: Failed to change ${e} SourceBuffer type`,a)}};n.append(i,e)}onBufferAppending(e,r){const{hls:n,operationQueue:i,tracks:a}=this,{data:s,type:o,frag:c,part:l,chunkMeta:u}=r,f=u.buffering[o],d=self.performance.now();f.start=d;const h=c.stats.buffering,p=l?l.stats.buffering:null;h.start===0&&(h.start=d),p&&p.start===0&&(p.start=d);const v=a.audio;let m=!1;o==="audio"&&(v==null?void 0:v.container)==="audio/mpeg"&&(m=!this.lastMpegAudioChunk||u.id===1||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);const g=c.start,y={execute:()=>{if(f.executeStart=self.performance.now(),m){const x=this.sourceBuffer[o];if(x){const b=g-x.timestampOffset;Math.abs(b)>=.1&&(G.log(`[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${g} (delta: ${b}) sn: ${c.sn})`),x.timestampOffset=g)}}this.appendExecutor(s,o)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();f.executeEnd=f.end=x,h.first===0&&(h.first=x),p&&p.first===0&&(p.first=x);const{sourceBuffer:b}=this,_={};for(const S in b)_[S]=ct.getBuffered(b[S]);this.appendError=0,this.hls.trigger($.BUFFER_APPENDED,{type:o,frag:c,part:l,chunkMeta:u,parent:c.type,timeRanges:_})},onError:x=>{G.error(`[buffer-controller]: Error encountered while trying to append to the ${o} SourceBuffer`,x);const b={type:ye.MEDIA_ERROR,parent:c.type,details:q.BUFFER_APPEND_ERROR,frag:c,part:l,chunkMeta:u,error:x,err:x,fatal:!1};x.code===DOMException.QUOTA_EXCEEDED_ERR?b.details=q.BUFFER_FULL_ERROR:(this.appendError++,b.details=q.BUFFER_APPEND_ERROR,this.appendError>n.config.appendErrorMaxRetry&&(G.error(`[buffer-controller]: Failed ${n.config.appendErrorMaxRetry} times to append segment in sourceBuffer`),b.fatal=!0)),n.trigger($.ERROR,b)}};i.append(y,o)}onBufferFlushing(e,r){const{operationQueue:n}=this,i=a=>({execute:this.removeExecutor.bind(this,a,r.startOffset,r.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger($.BUFFER_FLUSHED,{type:a})},onError:s=>{G.warn(`[buffer-controller]: Failed to remove from ${a} SourceBuffer`,s)}});r.type?n.append(i(r.type),r.type):this.getSourceBufferTypes().forEach(a=>{n.append(i(a),a)})}onFragParsed(e,r){const{frag:n,part:i}=r,a=[],s=i?i.elementaryStreams:n.elementaryStreams;s[Qe.AUDIOVIDEO]?a.push("audiovideo"):(s[Qe.AUDIO]&&a.push("audio"),s[Qe.VIDEO]&&a.push("video"));const o=()=>{const c=self.performance.now();n.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const l=i?i.stats:n.stats;this.hls.trigger($.FRAG_BUFFERED,{frag:n,part:i,stats:l,id:n.type})};a.length===0&&G.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(o,a)}onFragChanged(e,r){this.flushBackBuffer()}onBufferEos(e,r){this.getSourceBufferTypes().reduce((i,a)=>{const s=this.sourceBuffer[a];return s&&(!r.type||r.type===a)&&(s.ending=!0,s.ended||(s.ended=!0,G.log(`[buffer-controller]: ${a} sourceBuffer now EOS`))),i&&!!(!s||s.ended)},!0)&&(G.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(a=>{const s=this.sourceBuffer[a];s&&(s.ending=!1)});const{mediaSource:i}=this;if(!i||i.readyState!=="open"){i&&G.info(`[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${i.readyState}`);return}G.log("[buffer-controller]: Calling mediaSource.endOfStream()"),i.endOfStream()}))}onLevelUpdated(e,{details:r}){r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}flushBackBuffer(){const{hls:e,details:r,media:n,sourceBuffer:i}=this;if(!n||r===null)return;const a=this.getSourceBufferTypes();if(!a.length)return;const s=r.live&&e.config.liveBackBufferLength!==null?e.config.liveBackBufferLength:e.config.backBufferLength;if(!me(s)||s<0)return;const o=n.currentTime,c=r.levelTargetDuration,l=Math.max(s,c),u=Math.floor(o/c)*c-l;a.forEach(f=>{const d=i[f];if(d){const h=ct.getBuffered(d);if(h.length>0&&u>h.start(0)){if(e.trigger($.BACK_BUFFER_REACHED,{bufferEnd:u}),r.live)e.trigger($.LIVE_BACK_BUFFER_REACHED,{bufferEnd:u});else if(d.ended&&h.end(h.length-1)-oo&&a>s||!me(s))&&(G.log(`[buffer-controller]: Updating Media Source duration to ${a.toFixed(3)}`),i.duration=a)}updateSeekableRange(e){const r=this.mediaSource,n=e.fragments;if(n.length&&e.live&&r!=null&&r.setLiveSeekableRange){const a=Math.max(0,n[0].start),s=Math.max(a,a+e.totalduration);r.setLiveSeekableRange(a,s)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:r,pendingTracks:n}=this,i=Object.keys(n).length;if(i&&!e||i===2){this.createSourceBuffers(n),this.pendingTracks={};const a=this.getSourceBufferTypes();if(a.length)this.hls.trigger($.BUFFER_CREATED,{tracks:this.tracks}),a.forEach(s=>{r.executeNext(s)});else{const s=new Error("could not create source buffer for media codec(s)");this.hls.trigger($.ERROR,{type:ye.MEDIA_ERROR,details:q.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:s,reason:s.message})}}}createSourceBuffers(e){const{sourceBuffer:r,mediaSource:n}=this;if(!n)throw Error("createSourceBuffers called when mediaSource was null");for(const i in e)if(!r[i]){const a=e[i];if(!a)throw Error(`source buffer exists for track ${i}, however track does not`);const s=a.levelCodec||a.codec,o=`${a.container};codecs=${s}`;G.log(`[buffer-controller]: creating sourceBuffer(${o})`);try{const c=r[i]=n.addSourceBuffer(o),l=i;this.addBufferListener(l,"updatestart",this._onSBUpdateStart),this.addBufferListener(l,"updateend",this._onSBUpdateEnd),this.addBufferListener(l,"error",this._onSBUpdateError),this.tracks[i]={buffer:c,codec:s,container:a.container,levelCodec:a.levelCodec,metadata:a.metadata,id:a.id}}catch(c){G.error(`[buffer-controller]: error while trying to add sourceBuffer: ${c.message}`),this.hls.trigger($.ERROR,{type:ye.MEDIA_ERROR,details:q.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,mimeType:o})}}}_onSBUpdateStart(e){const{operationQueue:r}=this;r.current(e).onStart()}_onSBUpdateEnd(e){const{operationQueue:r}=this;r.current(e).onComplete(),r.shiftAndExecuteNext(e)}_onSBUpdateError(e,r){const n=new Error(`${e} SourceBuffer error`);G.error(`[buffer-controller]: ${n}`,r),this.hls.trigger($.ERROR,{type:ye.MEDIA_ERROR,details:q.BUFFER_APPENDING_ERROR,error:n,fatal:!1});const i=this.operationQueue.current(e);i&&i.onError(r)}removeExecutor(e,r,n){const{media:i,mediaSource:a,operationQueue:s,sourceBuffer:o}=this,c=o[e];if(!i||!a||!c){G.warn(`[buffer-controller]: Attempting to remove from the ${e} SourceBuffer, but it does not exist`),s.shiftAndExecuteNext(e);return}const l=me(i.duration)?i.duration:1/0,u=me(a.duration)?a.duration:1/0,f=Math.max(0,r),d=Math.min(n,l,u);d>f&&!c.ending?(c.ended=!1,G.log(`[buffer-controller]: Removing [${f},${d}] from the ${e} SourceBuffer`),c.remove(f,d)):s.shiftAndExecuteNext(e)}appendExecutor(e,r){const{operationQueue:n,sourceBuffer:i}=this,a=i[r];if(!a){G.warn(`[buffer-controller]: Attempting to append to the ${r} SourceBuffer, but it does not exist`),n.shiftAndExecuteNext(r);return}a.ended=!1,a.appendBuffer(e)}blockBuffers(e,r=this.getSourceBufferTypes()){if(!r.length){G.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:n}=this,i=r.map(a=>n.appendBlocker(a));Promise.all(i).then(()=>{e(),r.forEach(a=>{const s=this.sourceBuffer[a];s!=null&&s.updating||n.shiftAndExecuteNext(a)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,r,n){const i=this.sourceBuffer[e];if(!i)return;const a=n.bind(this,e);this.listeners[e].push({event:r,listener:a}),i.addEventListener(r,a)}removeBufferListeners(e){const r=this.sourceBuffer[e];r&&this.listeners[e].forEach(n=>{r.removeEventListener(n.event,n.listener)})}}const pB={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},eZ=function(e){let r=e;return pB.hasOwnProperty(e)&&(r=pB[e]),String.fromCharCode(r)},yi=15,Oa=100,rVe={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},nVe={17:2,18:4,21:6,22:8,23:10,19:13,20:15},iVe={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},aVe={25:2,26:4,29:6,30:8,31:10,27:13,28:15},sVe=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class oVe{constructor(){this.time=null,this.verboseLevel=0}log(e,r){if(this.verboseLevel>=e){const n=typeof r=="function"?r():r;G.log(`${this.time} [${e}] ${n}`)}}}const pl=function(e){const r=[];for(let n=0;nOa&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Oa)}moveCursor(e){const r=this.pos+e;if(e>1)for(let n=this.pos+1;n=144&&this.backSpace();const r=eZ(e);if(this.pos>=Oa){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+r+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1)}clearFromPos(e){let r;for(r=e;r"pacData = "+JSON.stringify(e));let r=e.row-1;if(this.nrRollUpRows&&r"bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,r=this.rows.splice(e,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const r=[];let n="",i=-1;for(let a=0;a0&&(e?n="["+r.join(" | ")+"]":n=r.join(`
+`)),n}getTextAndFormat(){return this.rows}}class mB{constructor(e,r,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new bT(n),this.nonDisplayedMemory=new bT(n),this.lastOutputScreen=new bT(n),this.currRollUpRow=this.displayedMemory.rows[yi-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[yi-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let n=0;nr+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const r={flash:!1};if(r.underline=e%2===1,r.italics=e>=46,r.italics)r.foreground="white";else{const n=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];r.foreground=i[n]}this.logger.log(2,"MIDROW: "+JSON.stringify(r)),this.writeScreen.setPen(r)}outputDataUpdate(e=!1){const r=this.logger.time;r!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=r:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,r,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:r),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class gB{constructor(e,r,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;const i=new oVe;this.channels=[null,new mB(e,r,i),new mB(e+1,n,i)],this.cmdHistory=yB(),this.logger=i}getHandler(e){return this.channels[e].getHandler()}setHandler(e,r){this.channels[e].setHandler(r)}addData(e,r){let n,i,a,s=!1;this.logger.time=e;for(let o=0;o ("+pl([i,a])+")"),n=this.parseCmd(i,a),n||(n=this.parseMidrow(i,a)),n||(n=this.parsePAC(i,a)),n||(n=this.parseBackgroundAttributes(i,a)),!n&&(s=this.parseChars(i,a),s)){const c=this.currentChannel;c&&c>0?this.channels[c].insertChars(s):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!s&&this.logger.log(2,"Couldn't parse cleaned data "+pl([i,a])+" orig: "+pl([r[o],r[o+1]]))}}parseCmd(e,r){const{cmdHistory:n}=this,i=(e===20||e===28||e===21||e===29)&&r>=32&&r<=47,a=(e===23||e===31)&&r>=33&&r<=35;if(!(i||a))return!1;if(vB(e,r,n))return Qc(null,null,n),this.logger.log(3,"Repeated command ("+pl([e,r])+") is dropped"),!0;const s=e===20||e===21||e===23?1:2,o=this.channels[s];return e===20||e===21||e===28||e===29?r===32?o.ccRCL():r===33?o.ccBS():r===34?o.ccAOF():r===35?o.ccAON():r===36?o.ccDER():r===37?o.ccRU(2):r===38?o.ccRU(3):r===39?o.ccRU(4):r===40?o.ccFON():r===41?o.ccRDC():r===42?o.ccTR():r===43?o.ccRTD():r===44?o.ccEDM():r===45?o.ccCR():r===46?o.ccENM():r===47&&o.ccEOC():o.ccTO(r-32),Qc(e,r,n),this.currentChannel=s,!0}parseMidrow(e,r){let n=0;if((e===17||e===25)&&r>=32&&r<=47){if(e===17?n=1:n=2,n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[n];return i?(i.ccMIDROW(r),this.logger.log(3,"MIDROW ("+pl([e,r])+")"),!0):!1}return!1}parsePAC(e,r){let n;const i=this.cmdHistory,a=(e>=17&&e<=23||e>=25&&e<=31)&&r>=64&&r<=127,s=(e===16||e===24)&&r>=64&&r<=95;if(!(a||s))return!1;if(vB(e,r,i))return Qc(null,null,i),!0;const o=e<=23?1:2;r>=64&&r<=95?n=o===1?rVe[e]:iVe[e]:n=o===1?nVe[e]:aVe[e];const c=this.channels[o];return c?(c.setPAC(this.interpretPAC(n,r)),Qc(e,r,i),this.currentChannel=o,!0):!1}interpretPAC(e,r){let n;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return r>95?n=r-96:n=r-64,i.underline=(n&1)===1,n<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((n-16)/2)*4,i}parseChars(e,r){let n,i=null,a=null;if(e>=25?(n=2,a=e-8):(n=1,a=e),a>=17&&a<=19){let s;a===17?s=r+80:a===18?s=r+112:s=r+144,this.logger.log(2,"Special char '"+eZ(s)+"' in channel "+n),i=[s]}else e>=32&&e<=127&&(i=r===0?[e]:[e,r]);if(i){const s=pl(i);this.logger.log(3,"Char codes = "+s.join(",")),Qc(e,r,this.cmdHistory)}return i}parseBackgroundAttributes(e,r){const n=(e===16||e===24)&&r>=32&&r<=47,i=(e===23||e===31)&&r>=45&&r<=47;if(!(n||i))return!1;let a;const s={};e===16||e===24?(a=Math.floor((r-32)/2),s.background=sVe[a],r%2===1&&(s.background=s.background+"_semi")):r===45?s.background="transparent":(s.foreground="black",r===47&&(s.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(s),Qc(e,r,this.cmdHistory),!0}reset(){for(let e=0;ee)&&(this.startTime=e),this.endTime=r,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var jO=function(){if(typeof self<"u"&&self.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function r(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;const l=c.toLowerCase();return~o.indexOf(l)?l:!1}function n(o){return r(t,o)}function i(o){return r(e,o)}function a(o,...c){let l=1;for(;l100)throw new Error("Position must be between 0 and 100.");S=T,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",a({},f,{get:function(){return w},set:function(T){const C=i(T);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");w=C,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",a({},f,{get:function(){return R},set:function(T){if(T<0||T>100)throw new Error("Size must be between 0 and 100.");R=T,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",a({},f,{get:function(){return I},set:function(T){const C=i(T);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");I=C,this.hasBeenReset=!0}})),u.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}();class uVe{decode(e,r){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function rZ(t){function e(n,i,a,s){return(n|0)*3600+(i|0)*60+(a|0)+parseFloat(s||0)}const r=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?e(r[2],r[3],0,r[4]):e(r[1],r[2],r[3],r[4]):null}class fVe{constructor(){this.values=Object.create(null)}set(e,r){!this.get(e)&&r!==""&&(this.values[e]=r)}get(e,r,n){return n?this.has(e)?this.values[e]:r[n]:this.has(e)?this.values[e]:r}has(e){return e in this.values}alt(e,r,n){for(let i=0;i=0&&n<=100)return this.set(e,n),!0}return!1}}function nZ(t,e,r,n){const i=n?t.split(n):[t];for(const a in i){if(typeof i[a]!="string")continue;const s=i[a].split(r);if(s.length!==2)continue;const o=s[0],c=s[1];e(o,c)}}const JA=new jO(0,0,""),Qg=JA.align==="middle"?"middle":"center";function dVe(t,e,r){const n=t;function i(){const o=rZ(t);if(o===null)throw new Error("Malformed timestamp: "+n);return t=t.replace(/^[^\sa-zA-Z-]+/,""),o}function a(o,c){const l=new fVe;nZ(o,function(d,h){let p;switch(d){case"region":for(let v=r.length-1;v>=0;v--)if(r[v].id===h){l.set(d,r[v].region);break}break;case"vertical":l.alt(d,h,["rl","lr"]);break;case"line":p=h.split(","),l.integer(d,p[0]),l.percent(d,p[0])&&l.set("snapToLines",!1),l.alt(d,p[0],["auto"]),p.length===2&&l.alt("lineAlign",p[1],["start",Qg,"end"]);break;case"position":p=h.split(","),l.percent(d,p[0]),p.length===2&&l.alt("positionAlign",p[1],["start",Qg,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,h);break;case"align":l.alt(d,h,["start",Qg,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let u=l.get("line","auto");u==="auto"&&JA.line===-1&&(u=-1),c.line=u,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",Qg);let f=l.get("position","auto");f==="auto"&&JA.position===50&&(f=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=f}function s(){t=t.replace(/^\s+/,"")}if(s(),e.startTime=i(),s(),t.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+n);t=t.slice(3),s(),e.endTime=i(),s(),a(t,e)}function iZ(t){return t.replace(/
/gi,`
+`)}class hVe{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new uVe,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const r=this;e&&(r.buffer+=r.decoder.decode(e,{stream:!0}));function n(){let a=r.buffer,s=0;for(a=iZ(a);s")===-1){r.cue.id=a;continue}case"CUE":if(!r.cue){r.state="BADCUE";continue}try{dVe(a,r.cue,r.regionList)}catch{r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":{const o=a.indexOf("-->")!==-1;if(!a||o&&(s=!0)){r.oncue&&r.cue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}if(r.cue===null)continue;r.cue.text&&(r.cue.text+=`
+`),r.cue.text+=a}continue;case"BADCUE":a||(r.state="ID")}}}catch{r.state==="CUETEXT"&&r.cue&&r.oncue&&r.oncue(r.cue),r.cue=null,r.state=r.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
+
+`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(r){e.onparsingerror&&e.onparsingerror(r)}return e.onflush&&e.onflush(),this}}const pVe=/\r\n|\n\r|\n|\r/g,ET=function(e,r,n=0){return e.slice(n,n+r.length)===r},mVe=function(e){let r=parseInt(e.slice(-3));const n=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),a=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!me(r)||!me(n)||!me(i)||!me(a))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return r+=1e3*n,r+=60*1e3*i,r+=60*60*1e3*a,r},ST=function(e){let r=5381,n=e.length;for(;n;)r=r*33^e.charCodeAt(--n);return(r>>>0).toString()};function HO(t,e,r){return ST(t.toString())+ST(e.toString())+ST(r)}const gVe=function(e,r,n){let i=e[r],a=e[i.prevCC];if(!a||!a.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(s=a)!=null&&s.new;){var s;e.ccOffset+=i.start-a.start,i.new=!1,i=a,a=e[i.prevCC]}e.presentationOffset=n};function vVe(t,e,r,n,i,a,s){const o=new hVe,c=fa(new Uint8Array(t)).trim().replace(pVe,`
+`).split(`
+`),l=[],u=IGe(e.baseTime,e.timescale);let f="00:00.000",d=0,h=0,p,v=!0;o.oncue=function(m){const g=r[n];let y=r.ccOffset;const x=(d-u)/9e4;g!=null&&g.new&&(h!==void 0?y=r.ccOffset=g.start:gVe(r,n,x)),x&&(y=x-r.presentationOffset);const b=m.endTime-m.startTime,_=jn((m.startTime+y-h)*9e4,i*9e4)/9e4;m.startTime=Math.max(_,0),m.endTime=Math.max(_+b,0);const S=m.text.trim();m.text=decodeURIComponent(encodeURIComponent(S)),m.id||(m.id=HO(m.startTime,m.endTime,S)),m.endTime>0&&l.push(m)},o.onparsingerror=function(m){p=m},o.onflush=function(){if(p){s(p);return}a(l)},c.forEach(m=>{if(v)if(ET(m,"X-TIMESTAMP-MAP=")){v=!1,m.slice(16).split(",").forEach(g=>{ET(g,"LOCAL:")?f=g.slice(6):ET(g,"MPEGTS:")&&(d=parseInt(g.slice(7)))});try{h=mVe(f)/1e3}catch(g){p=g}return}else m===""&&(v=!1);o.parse(m+`
+`)}),o.flush()}const _T="stpp.ttml.im1t",aZ=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,sZ=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,yVe={left:"start",center:"center",right:"end",start:"start",end:"end"};function xB(t,e,r,n){const i=Be(new Uint8Array(t),["mdat"]);if(i.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const a=i.map(o=>fa(o)),s=AGe(e.baseTime,1,e.timescale);try{a.forEach(o=>r(xVe(o,s)))}catch(o){n(o)}}function xVe(t,e){const i=new DOMParser().parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const a={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(a).reduce((f,d)=>(f[d]=i.getAttribute(`ttp:${d}`)||a[d],f),{}),o=i.getAttribute("xml:space")!=="preserve",c=bB(wT(i,"styling","style")),l=bB(wT(i,"layout","region")),u=wT(i,"body","[begin]");return[].map.call(u,f=>{const d=oZ(f,o);if(!d||!f.hasAttribute("begin"))return null;const h=RT(f.getAttribute("begin"),s),p=RT(f.getAttribute("dur"),s);let v=RT(f.getAttribute("end"),s);if(h===null)throw EB(f);if(v===null){if(p===null)throw EB(f);v=h+p}const m=new jO(h-e,v-e,d);m.id=HO(m.startTime,m.endTime,m.text);const g=l[f.getAttribute("region")],y=c[f.getAttribute("style")],x=bVe(g,y,c),{textAlign:b}=x;if(b){const _=yVe[b];_&&(m.lineAlign=_),m.align=b}return Pt(m,x),m}).filter(f=>f!==null)}function wT(t,e,r){const n=t.getElementsByTagName(e)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function bB(t){return t.reduce((e,r)=>{const n=r.getAttribute("xml:id");return n&&(e[n]=r),e},{})}function oZ(t,e){return[].slice.call(t.childNodes).reduce((r,n,i)=>{var a;return n.nodeName==="br"&&i?r+`
+`:(a=n.childNodes)!=null&&a.length?oZ(n,e):e?r+n.textContent.trim().replace(/\s+/g," "):r+n.textContent},"")}function bVe(t,e,r){const n="http://www.w3.org/ns/ttml#styling";let i=null;const a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],s=t!=null&&t.hasAttribute("style")?t.getAttribute("style"):null;return s&&r.hasOwnProperty(s)&&(i=r[s]),a.reduce((o,c)=>{const l=TT(e,n,c)||TT(t,n,c)||TT(i,n,c);return l&&(o[c]=l),o},{})}function TT(t,e,r){return t&&t.hasAttributeNS(e,r)?t.getAttributeNS(e,r):null}function EB(t){return new Error(`Could not parse ttml timestamp ${t}`)}function RT(t,e){if(!t)return null;let r=rZ(t);return r===null&&(aZ.test(t)?r=EVe(t,e):sZ.test(t)&&(r=SVe(t,e))),r}function EVe(t,e){const r=aZ.exec(t),n=(r[4]|0)+(r[5]|0)/e.subFrameRate;return(r[1]|0)*3600+(r[2]|0)*60+(r[3]|0)+n/e.frameRate}function SVe(t,e){const r=sZ.exec(t),n=Number(r[1]);switch(r[2]){case"h":return n*3600;case"m":return n*60;case"ms":return n*1e3;case"f":return n/e.frameRate;case"t":return n/e.tickRate}return n}class _Ve{constructor(e){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=SB(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},this.config.enableCEA708Captions){const r=new Xg(this,"textTrack1"),n=new Xg(this,"textTrack2"),i=new Xg(this,"textTrack3"),a=new Xg(this,"textTrack4");this.cea608Parser1=new gB(1,r,n),this.cea608Parser2=new gB(3,i,a)}e.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_LOADED,this.onManifestLoaded,this),e.on($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on($.FRAG_LOADING,this.onFragLoading,this),e.on($.FRAG_LOADED,this.onFragLoaded,this),e.on($.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on($.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on($.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on($.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_LOADED,this.onManifestLoaded,this),e.off($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off($.FRAG_LOADING,this.onFragLoading,this),e.off($.FRAG_LOADED,this.onFragLoaded,this),e.off($.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off($.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off($.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off($.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null}addCues(e,r,n,i,a){let s=!1;for(let o=a.length;o--;){const c=a[o],l=TVe(c[0],c[1],r,n);if(l>=0&&(c[0]=Math.min(c[0],r),c[1]=Math.max(c[1],n),s=!0,l/(n-r)>.5))return}if(s||a.push([r,n]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,r,n,i)}else{const o=this.Cues.newCue(null,r,n,i);this.hls.trigger($.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:r,id:n,initPTS:i,timescale:a}){const{unparsedVttFrags:s}=this;n==="main"&&(this.initPTS[r.cc]={baseTime:i,timescale:a}),s.length&&(this.unparsedVttFrags=[],s.forEach(o=>{this.onFragLoaded($.FRAG_LOADED,o)}))}getExistingTrack(e){const{media:r}=this;if(r)for(let n=0;n{Ru(e[r]),delete e[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=SB(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=this.unparsedVttFrags||[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const r=e.textTracks;if(r)for(let n=0;na.textCodec===_T);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(JQ(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const s=this.media?this.media.textTracks:null;this.tracks.forEach((o,c)=>{let l;if(s&&c({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger($.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:s})}}}_captionsOrSubtitlesFromCharacteristics(e){if(e.attrs.CHARACTERISTICS){const r=/transcribes-spoken-dialog/gi.test(e.attrs.CHARACTERISTICS),n=/describes-music-and-sound/gi.test(e.attrs.CHARACTERISTICS);if(r&&n)return"captions"}return"subtitles"}onManifestLoaded(e,r){this.config.enableCEA708Captions&&r.captions&&r.captions.forEach(n=>{const i=/(?:CC|SERVICE)([1-4])/.exec(n.instreamId);if(!i)return;const a=`textTrack${i[1]}`,s=this.captionsProperties[a];s&&(s.label=n.name,n.lang&&(s.languageCode=n.lang),s.media=n)})}closedCaptionsForLevel(e){const r=this.hls.levels[e.level];return r==null?void 0:r.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,r){const{cea608Parser1:n,cea608Parser2:i,lastSn:a,lastPartIndex:s}=this;if(!(!this.enabled||!(n&&i))&&r.frag.type===xe.MAIN){var o,c;const l=r.frag.sn,u=(o=r==null||(c=r.part)==null?void 0:c.index)!=null?o:-1;l===a+1||l===a&&u===s+1||(n.reset(),i.reset()),this.lastSn=l,this.lastPartIndex=u}}onFragLoaded(e,r){const{frag:n,payload:i}=r,{initPTS:a,unparsedVttFrags:s}=this;if(n.type===xe.SUBTITLE)if(i.byteLength){if(!a[n.cc]){s.push(r),a.length&&this.hls.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Missing initial subtitle PTS")});return}const o=n.decryptdata,c="stats"in r;if(o==null||!o.encrypted||c){const l=this.tracks[n.level],u=this.vttCCs;u[n.cc]||(u[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),l&&l.textCodec===_T?this._parseIMSC1(n,i):this._parseVTTs(n,i,u)}}else this.hls.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,r){const n=this.hls;xB(r,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),n.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{G.log(`Failed to parse IMSC1: ${i}`),n.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e,r,n){var i;const a=this.hls,s=(i=e.initSegment)!=null&&i.data?rc(e.initSegment.data,new Uint8Array(r)):r;vVe(s,this.initPTS[e.cc],n,e.cc,e.start,o=>{this._appendCues(o,e.level),a.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},o=>{this._fallbackToIMSC1(e,r),G.log(`Failed to parse VTT cue: ${o}`),a.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:o})})}_fallbackToIMSC1(e,r){const n=this.tracks[e.level];n.textCodec||xB(r,this.initPTS[e.cc],()=>{n.textCodec=_T,this._parseIMSC1(e,r)},()=>{n.textCodec="wvtt"})}_appendCues(e,r){const n=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[r];if(!i||i.mode==="disabled")return;e.forEach(a=>kQ(i,a))}else{const i=this.tracks[r];if(!i)return;const a=i.default?"default":"subtitles"+r;n.trigger($.CUES_PARSED,{type:"subtitles",cues:e,track:a})}}onFragDecrypted(e,r){const{frag:n}=r;if(n.type===xe.SUBTITLE){if(!this.initPTS[n.cc]){this.unparsedVttFrags.push(r);return}this.onFragLoaded($.FRAG_LOADED,r)}}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,r){const{cea608Parser1:n,cea608Parser2:i}=this;if(!this.enabled||!(n&&i))return;const{frag:a,samples:s}=r;if(!(a.type===xe.MAIN&&this.closedCaptionsForLevel(a)==="NONE"))for(let o=0;oKA(o[c],r,n))}if(this.config.renderTextTracksNatively&&r===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>KA(o[c],r,i))}}}extractCea608Data(e){const r=[[],[]],n=e[0]&31;let i=2;for(let a=0;a0&&this.mediaWidth>0){const e=this.hls.levels;if(e.length){const r=this.hls;r.autoLevelCapping=this.getMaxLevel(e.length-1),r.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=r.autoLevelCapping}}}getMaxLevel(e){const r=this.hls.levels;if(!r.length)return-1;const n=r.filter((i,a)=>this.isLevelAllowed(i)&&a<=e);return this.clientRect=null,zO.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,r={width:0,height:0};if(e){const n=e.getBoundingClientRect();r.width=n.width,r.height=n.height,!r.width&&!r.height&&(r.width=n.right-n.left||e.width||0,r.height=n.bottom-n.top||e.height||0)}return this.clientRect=r,r}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(n=>e.bitrate===n.bitrate&&e.width===n.width&&e.height===n.height)}static getMaxLevelByMediaSize(e,r,n){if(!(e!=null&&e.length))return-1;const i=(s,o)=>o?s.width!==o.width||s.height!==o.height:!0;let a=e.length-1;for(let s=0;s=r||o.height>=n)&&i(o,e[s+1])){a=s;break}}return a}}class RVe{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on($.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off($.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,r){const n=this.hls.config;if(n.capLevelOnFPSDrop){const i=r.media instanceof self.HTMLVideoElement?r.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}checkFPS(e,r,n){const i=performance.now();if(r){if(this.lastTime){const a=i-this.lastTime,s=n-this.lastDroppedFrames,o=r-this.lastDecodedFrames,c=1e3*s/a,l=this.hls;if(l.trigger($.FPS_DROP,{currentDropped:s,currentDecoded:o,totalDroppedFrames:n}),c>0&&s>l.config.fpsDroppedMonitoringThreshold*o){let u=l.currentLevel;G.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=u)&&(u=u-1,l.trigger($.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=n,this.lastDecodedFrames=r}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const r=e.getVideoPlaybackQuality();this.checkFPS(e,r.totalVideoFrames,r.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const Zg="[eme]";class Qu{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=Qu.CDMCleanupPromise?[Qu.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=G.debug.bind(G,Zg),this.log=G.log.bind(G,Zg),this.warn=G.warn.bind(G,Zg),this.error=G.error.bind(G,Zg),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on($.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on($.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on($.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off($.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off($.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off($.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:r,widevineLicenseUrl:n}=this.config,i=r[e];if(i)return i.licenseUrl;if(e===vt.WIDEVINE&&n)return n;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:r}=this.config,n=r[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const r=this.hls.levels,n=(s,o,c)=>!!s&&c.indexOf(s)===o,i=r.map(s=>s.audioCodec).filter(n),a=r.map(s=>s.videoCodec).filter(n);return i.length+a.length===0&&a.push("avc1.42e01e"),new Promise((s,o)=>{const c=l=>{const u=l.shift();this.getMediaKeysPromise(u,i,a).then(f=>s({keySystem:u,mediaKeys:f})).catch(f=>{l.length?c(l):f instanceof Mn?o(f):o(new Mn({type:ye.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_NO_ACCESS,error:f,fatal:!0},f.message))})};c(e)})}requestMediaKeySystemAccess(e,r){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${n}`;return yQ===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return n(e,r)}getMediaKeysPromise(e,r,n){const i=UHe(e,r,n,this.config.drmSystemOptions),a=this.keySystemAccessPromises[e];let s=a==null?void 0:a.keySystemAccess;if(!s){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(i)}`),s=this.requestMediaKeySystemAccess(e,i);const o=this.keySystemAccessPromises[e]={keySystemAccess:s};return s.catch(c=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),s.then(c=>{this.log(`Access for key-system "${c.keySystem}" obtained`);const l=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=c.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),l.then(f=>f?this.setMediaKeysServerCertificate(u,e,f):u))),o.mediaKeys.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),o.mediaKeys})}return s.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:r,mediaKeys:n}){this.log(`Creating key-system session "${r}" keyId: ${Ji.hexDump(e.keyId||[])}`);const i=n.createSession(),a={decryptdata:e,keySystem:r,mediaKeys:n,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a}renewKeySession(e){const r=e.decryptdata;if(r.pssh){const n=this.createMediaKeySessionContext(e),i=this.getKeyIdString(r),a="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(n,a,r.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return Ji.hexDump(e.keyId)}updateKeySession(e,r){var n;const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${Ji.hexDump(((n=e.decryptdata)==null?void 0:n.keyId)||[])}
+ } (data length: ${r&&r.byteLength})`),i.update(r)}selectKeySystemFormat(e){const r=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((r,n)=>{const i=nT(this.config),a=e.map(P5).filter(s=>!!s&&i.indexOf(s)!==-1);return this.getKeySystemSelectionPromise(a).then(({keySystem:s})=>{const o=N5(s);o?r(o):n(new Error(`Unable to find format for key-system "${s}"`))}).catch(n)})}loadKey(e){const r=e.keyInfo.decryptdata,n=this.getKeyIdString(r),i=`(keyId: ${n} format: "${r.keyFormat}" method: ${r.method} uri: ${r.uri})`;this.log(`Starting session for key ${i}`);let a=this.keyIdToKeySessionPromise[n];return a||(a=this.keyIdToKeySessionPromise[n]=this.getKeySystemForKeyPromise(r).then(({keySystem:s,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(s,o).then(()=>{this.throwIfDestroyed();const c=this.createMediaKeySessionContext({keySystem:s,mediaKeys:o,decryptdata:r}),l="cenc";return this.generateRequestWithPreferredKeySession(c,l,r.pssh,"playlist-key")}))),a.catch(s=>this.handleError(s))),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Mn?this.hls.trigger($.ERROR,e.data):this.hls.trigger($.ERROR,{type:ye.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const r=this.getKeyIdString(e),n=this.keyIdToKeySessionPromise[r];if(!n){const i=P5(e.keyFormat),a=i?[i]:nT(this.config);return this.attemptKeySystemAccess(a)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=nT(this.config)),e.length===0)throw new Mn({type:ye.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:r,initData:n}=e;if(this.debug(`"${e.type}" event: init data type: "${r}"`),n===null)return;let i,a;if(r==="sinf"&&this.config.drmSystems[vt.FAIRPLAY]){const u=Qt(new Uint8Array(n));try{const f=$O(JSON.parse(u).sinf),d=RQ(new Uint8Array(f));if(!d)return;i=d.subarray(8,24),a=vt.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const u=uze(n);if(u===null)return;u.version===0&&u.systemId===vQ.WIDEVINE&&u.data&&(i=u.data.subarray(8,24)),a=BHe(u.systemId)}if(!a||!i)return;const s=Ji.hexDump(i),{keyIdToKeySessionPromise:o,mediaKeySessions:c}=this;let l=o[s];for(let u=0;uthis.generateRequestWithPreferredKeySession(f,r,n,"encrypted-event-key-match"));break}}l||(l=o[s]=this.getKeySystemSelectionPromise([a]).then(({keySystem:u,mediaKeys:f})=>{var d;this.throwIfDestroyed();const h=new ep("ISO-23001-7",s,(d=N5(u))!=null?d:"");return h.pssh=new Uint8Array(n),h.keyId=i,this.attemptSetMediaKeys(u,f).then(()=>{this.throwIfDestroyed();const p=this.createMediaKeySessionContext({decryptdata:h,keySystem:u,mediaKeys:f});return this.generateRequestWithPreferredKeySession(p,r,n,"encrypted-event-no-match")})})),l.catch(u=>this.handleError(u))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,r){const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(n).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(r)});return this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),n.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(a=>n.indexOf(a)===-1)})}generateRequestWithPreferredKeySession(e,r,n,i){var a,s;const o=(a=this.config.drmSystems)==null||(s=a[e.keySystem])==null?void 0:s.generateRequest;if(o)try{const d=o.call(this.hls,r,n,e);if(!d)throw new Error("Invalid response from configured generateRequest filter");r=d.initDataType,n=e.decryptdata.pssh=d.initData?new Uint8Array(d.initData):null}catch(d){var c;if(this.warn(d.message),(c=this.hls)!=null&&c.config.debug)throw d}if(n===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const l=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${i}": ${l} (init data type: ${r} length: ${n?n.byteLength:null})`);const u=new np;e.mediaKeysSession.onmessage=d=>{const h=e.mediaKeysSession;if(!h){u.emit("error",new Error("invalid state"));return}const{messageType:p,message:v}=d;this.log(`"${p}" message event for session "${h.sessionId}" message size: ${v.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(e,v).catch(m=>{this.handleError(m),u.emit("error",m)}):p==="license-release"?e.keySystem===vt.FAIRPLAY&&(this.updateKeySession(e,gQ("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${p}"`)},e.mediaKeysSession.onkeystatuseschange=d=>{if(!e.mediaKeysSession){u.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const p=e.keyStatus;u.emit("keyStatus",p),p==="expired"&&(this.warn(`${e.keySystem} expired for key ${l}`),this.renewKeySession(e))};const f=new Promise((d,h)=>{u.on("error",h),u.on("keyStatus",p=>{p.startsWith("usable")?d():p==="output-restricted"?h(new Mn({type:ye.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):p==="internal-error"?h(new Mn({type:ye.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${p}"`)):p==="expired"?h(new Error("key expired while generating request")):this.warn(`unhandled key status change "${p}"`)})});return e.mediaKeysSession.generateRequest(r,n).then(()=>{var d;this.log(`Request generated for key-session "${(d=e.mediaKeysSession)==null?void 0:d.sessionId}" keyId: ${l}`)}).catch(d=>{throw new Mn({type:ye.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_NO_SESSION,error:d,fatal:!1},`Error generating key-session request: ${d}`)}).then(()=>f).catch(d=>{throw u.removeAllListeners(),this.removeSession(e),d}).then(()=>(u.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((r,n)=>{this.log(`key status change "${r}" for keyStatuses keyId: ${Ji.hexDump("buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n))} session keyId: ${Ji.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=r})}fetchServerCertificate(e){const r=this.config,n=r.loader,i=new n(r),a=this.getServerCertificateUrl(e);return a?(this.log(`Fetching serverCertificate for "${e}"`),new Promise((s,o)=>{const c={responseType:"arraybuffer",url:a},l=r.certLoadPolicy.default,u={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},f={onSuccess:(d,h,p,v)=>{s(d.data)},onError:(d,h,p,v)=>{o(new Mn({type:ye.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:sn({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${a}). Status: ${d.code} (${d.text})`))},onTimeout:(d,h,p)=>{o(new Mn({type:ye.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${a})`))},onAbort:(d,h,p)=>{o(new Error("aborted"))}};i.load(c,u,f)})):Promise.resolve()}setMediaKeysServerCertificate(e,r,n){return new Promise((i,a)=>{e.setServerCertificate(n).then(s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${n==null?void 0:n.byteLength}) on "${r}"`),i(e)}).catch(s=>{a(new Mn({type:ye.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:s,fatal:!0},s.message))})})}renewLicense(e,r){return this.requestLicense(e,new Uint8Array(r)).then(n=>this.updateKeySession(e,new Uint8Array(n)).catch(i=>{throw new Mn({type:ye.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:i,fatal:!0},i.message)}))}setupLicenseXHR(e,r,n,i){const a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return a.call(this.hls,e,r,n,i)}).catch(s=>{if(!n.decryptdata)throw s;return e.open("POST",r,!0),a.call(this.hls,e,r,n,i)}).then(s=>(e.readyState||e.open("POST",r,!0),{xhr:e,licenseChallenge:s||i})):(e.open("POST",r,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,r){const n=this.config.keyLoadPolicy.default;return new Promise((i,a)=>{const s=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${s}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,s,e)}catch(u){this.error(u)}i(c)}else{const c=n.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)a(new Mn({type:ye.KEY_SYSTEM_ERROR,details:q.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:s,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${s}). Status: ${o.status} (${o.statusText})`));else{const u=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(e,r).then(i,a)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,s,e,r).then(({xhr:c,licenseChallenge:l})=>{c.send(l)})})}onMediaAttached(e,r){if(!this.config.emeEnabled)return;const n=r.media;this.media=n,n.addEventListener("encrypted",this.onMediaEncrypted),n.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,r=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},ep.clearKeyUriToKeyIdMap();const n=r.length;Qu.CDMCleanupPromise=Promise.all(r.map(i=>this.removeSession(i)).concat(e==null?void 0:e.setMediaKeys(null).catch(i=>{this.log(`Could not clear media keys: ${i}. media.src: ${e==null?void 0:e.src}`)}))).then(()=>{n&&(this.log("finished closing key sessions and clearing media keys"),r.length=0)}).catch(i=>{this.log(`Could not close sessions and clear media keys: ${i}. media.src: ${e==null?void 0:e.src}`)})}onManifestLoaded(e,{sessionKeys:r}){if(!(!r||!this.config.emeEnabled)&&!this.keyFormatPromise){const n=r.reduce((i,a)=>(i.indexOf(a.keyFormat)===-1&&i.push(a.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)}}removeSession(e){const{mediaKeysSession:r,licenseXhr:n}=e;if(r){this.log(`Remove licenses and keys and close session ${r.sessionId}`),r.onmessage=null,r.onkeystatuseschange=null,n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);return i>-1&&this.mediaKeySessions.splice(i,1),r.remove().catch(a=>{this.log(`Could not remove session: ${a}`)}).then(()=>r.close()).catch(a=>{this.log(`Could not close session: ${a}`)})}}}Qu.CDMCleanupPromise=void 0;class Mn extends Error{constructor(e,r){super(r),this.data=void 0,e.error||(e.error=new Error(r)),this.data=e,e.err=e.error}}const AVe=1;var Ur={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"};const IVe="h";class Hs{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:Ur.MANIFEST,su:!this.initialized})}catch(a){G.warn("Could not generate manifest CMCD data.",a)}},this.applyFragmentData=i=>{try{const a=i.frag,s=this.hls.levels[a.level],o=this.getObjectType(a),c={d:a.duration*1e3,ot:o};(o===Ur.VIDEO||o===Ur.AUDIO||o==Ur.MUXED)&&(c.br=s.bitrate/1e3,c.tb=this.getTopBandwidth(o)/1e3,c.bl=this.getBufferLength(o)),this.apply(i,c)}catch(a){G.warn("Could not generate segment CMCD data.",a)}},this.hls=e;const r=this.config=e.config,{cmcd:n}=r;n!=null&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||Hs.uuid(),this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.registerListeners())}registerListeners(){const e=this.hls;e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHED,this.onMediaDetached,this),e.on($.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHED,this.onMediaDetached,this),e.off($.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null}onMediaAttached(e,r){this.media=r.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,r){var n,i;this.audioBuffer=(n=r.tracks.audio)==null?void 0:n.buffer,this.videoBuffer=(i=r.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:AVe,sf:IVe,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,r={}){Pt(r,this.createData());const n=r.ot===Ur.INIT||r.ot===Ur.VIDEO||r.ot===Ur.MUXED;if(this.starved&&n&&(r.bs=!0,r.su=!0,this.starved=!1),r.su==null&&(r.su=this.buffering),this.useHeaders){const i=Hs.toHeaders(r);if(!Object.keys(i).length)return;e.headers||(e.headers={}),Pt(e.headers,i)}else{const i=Hs.toQuery(r);if(!i)return;e.url=Hs.appendQueryToUri(e.url,i)}}getObjectType(e){const{type:r}=e;if(r==="subtitle")return Ur.TIMED_TEXT;if(e.sn==="initSegment")return Ur.INIT;if(r==="audio")return Ur.AUDIO;if(r==="main")return this.hls.audioTracks.length?Ur.VIDEO:Ur.MUXED}getTopBandwidth(e){let r=0,n;const i=this.hls;if(e===Ur.AUDIO)n=i.audioTracks;else{const a=i.maxAutoLevel,s=a>-1?a+1:i.levels.length;n=i.levels.slice(0,s)}for(const a of n)a.bitrate>r&&(r=a.bitrate);return r>0?r:NaN}getBufferLength(e){const r=this.hls.media,n=e===Ur.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!r?NaN:ct.bufferInfo(n,r.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,r=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new n(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,s,o){r(a),this.loader.load(a,s,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,r=this.applyFragmentData,n=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new n(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,s,o){r(a),this.loader.load(a,s,o)}}}static uuid(){const e=URL.createObjectURL(new Blob),r=e.toString();return URL.revokeObjectURL(e),r.slice(r.lastIndexOf("/")+1)}static serialize(e){const r=[],n=l=>!Number.isNaN(l)&&l!=null&&l!==""&&l!==!1,i=l=>Math.round(l),a=l=>i(l/100)*100,o={br:i,d:i,bl:a,dl:a,mtp:a,nor:l=>encodeURIComponent(l),rtp:a,tb:i},c=Object.keys(e||{}).sort();for(const l of c){let u=e[l];if(!n(u)||l==="v"&&u===1||l=="pr"&&u===1)continue;const f=o[l];f&&(u=f(u));const d=typeof u;let h;l==="ot"||l==="sf"||l==="st"?h=`${l}=${u}`:d==="boolean"?h=l:d==="number"?h=`${l}=${u}`:h=`${l}=${JSON.stringify(u)}`,r.push(h)}return r.join(",")}static toHeaders(e){const r=Object.keys(e),n={},i=["Object","Request","Session","Status"],a=[{},{},{},{}],s={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3};for(const o of r){const c=s[o]!=null?s[o]:1;a[c][o]=e[o]}for(let o=0;on!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,r){const{contentSteering:n}=r;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,r){this.audioTracks=r.audioTracks,this.subtitleTracks=r.subtitleTracks}onError(e,r){const{errorAction:n}=r;if((n==null?void 0:n.action)===zr.SendAlternateToPenaltyBox&&n.flags===Bn.MoveAllAlternatesMatchingHost){let i=this.pathwayPriority;const a=this.pathwayId;this.penalizedPathways[a]||(this.penalizedPathways[a]=performance.now()),!i&&this.levels&&(i=this.levels.reduce((s,o)=>(s.indexOf(o.pathwayId)===-1&&s.push(o.pathwayId),s),[])),i&&i.length>1&&(this.updatePathwayPriority(i),n.resolved=this.pathwayId!==a)}}filterParsedLevels(e){this.levels=e;let r=this.getLevelsForPathway(this.pathwayId);if(r.length===0){const n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),r=this.getLevelsForPathway(n),this.pathwayId=n}return r.length!==e.length?(this.log(`Found ${r.length}/${e.length} levels in Pathway "${this.pathwayId}"`),r):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(r=>e===r.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let r;const n=this.penalizedPathways,i=performance.now();Object.keys(n).forEach(a=>{i-n[a]>$Ve&&delete n[a]});for(let a=0;a0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,this.hls.trigger($.LEVELS_UPDATED,{levels:r});const l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}clonePathways(e){const r=this.levels;if(!r)return;const n={},i={};e.forEach(a=>{const{ID:s,"BASE-ID":o,"URI-REPLACEMENT":c}=a;if(r.some(u=>u.pathwayId===s))return;const l=this.getLevelsForPathway(o).map(u=>{const f=Pt({},u);f.details=void 0,f.url=lZ(u.uri,u.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c);const d=new gt(u.attrs);d["PATHWAY-ID"]=s;const h=d.AUDIO&&`${d.AUDIO}_clone_${s}`,p=d.SUBTITLES&&`${d.SUBTITLES}_clone_${s}`;h&&(n[d.AUDIO]=h,d.AUDIO=h),p&&(i[d.SUBTITLES]=p,d.SUBTITLES=p),f.attrs=d;const v=new tp(f);return D1(v,"audio",h),D1(v,"text",p),v});r.push(...l),_B(this.audioTracks,n,c,s),_B(this.subtitleTracks,i,c,s)})}loadSteeringManifest(e){const r=this.hls.config,n=r.loader;this.loader&&this.loader.destroy(),this.loader=new n(r);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const u=(this.hls.bandwidthEstimate||r.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+u)}const a={responseType:"json",url:i.href},s=r.steeringManifestLoadPolicy.default,o=s.errorRetry||s.timeoutRetry||{},c={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(u,f,d,h)=>{this.log(`Loaded steering manifest: "${i}"`);const p=u.data;if(p.VERSION!==1){this.log(`Steering VERSION ${p.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=p.TTL;const{"RELOAD-URI":v,"PATHWAY-CLONES":m,"PATHWAY-PRIORITY":g}=p;if(v)try{this.uri=new self.URL(v,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${v}`);return}this.scheduleRefresh(this.uri||d.url),m&&this.clonePathways(m),g&&this.updatePathwayPriority(g)},onError:(u,f,d,h)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${f.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${f.url} no longer available`);return}let p=this.timeToLoad*1e3;if(u.code===429){const v=this.loader;if(typeof(v==null?void 0:v.getResponseHeader)=="function"){const m=v.getResponseHeader("Retry-After");m&&(p=parseFloat(m)*1e3)}this.log(`Steering manifest ${f.url} rate limited`);return}this.scheduleRefresh(this.uri||f.url,p)},onTimeout:(u,f,d)=>{this.log(`Timeout loading steering manifest (${f.url})`),this.scheduleRefresh(this.uri||f.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(a,c,l)}scheduleRefresh(e,r=this.timeToLoad*1e3){self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout(()=>{this.loadSteeringManifest(e)},r)}}function _B(t,e,r,n){t&&Object.keys(e).forEach(i=>{const a=t.filter(s=>s.groupId===i).map(s=>{const o=Pt({},s);return o.details=void 0,o.attrs=new gt(o.attrs),o.url=o.attrs.URI=lZ(s.url,s.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=n,o});t.push(...a)})}function lZ(t,e,r,n){const{HOST:i,PARAMS:a,[r]:s}=n;let o;e&&(o=s==null?void 0:s[e],o&&(t=o));const c=new self.URL(t);return i&&!o&&(c.host=i),a&&Object.keys(a).sort().forEach(l=>{l&&c.searchParams.set(l,a[l])}),c.href}const kVe=/^age:\s*[\d.]+\s*$/im;class cZ{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new TE,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=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,r,n){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=r,this.callbacks=n,this.loadInternal()}loadInternal(){const{config:e,context:r}=this;if(!e)return;const n=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0;const a=this.xhrSetup;a?Promise.resolve().then(()=>{if(!this.stats.aborted)return a(n,r.url)}).catch(s=>(n.open("GET",r.url,!0),a(n,r.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(n,r,e)}).catch(s=>{this.callbacks.onError({code:n.status,text:s.message},r,n,i)}):this.openAndSendXhr(n,r,e)}openAndSendXhr(e,r,n){e.readyState||e.open("GET",r.url,!0);const i=this.context.headers,{maxTimeToFirstByteMs:a,maxLoadTimeMs:s}=n.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);r.rangeEnd&&e.setRequestHeader("Range","bytes="+r.rangeStart+"-"+(r.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=r.responseType,self.clearTimeout(this.requestTimeout),n.timeout=a&&me(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){const{context:e,loader:r,stats:n}=this;if(!e||!r)return;const i=r.readyState,a=this.config;if(!n.aborted&&i>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),a.timeout!==a.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),a.timeout=a.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),r.onreadystatechange=null,r.onprogress=null;const s=r.status,o=r.responseType!=="text";if(s>=200&&s<300&&(o&&r.response||r.responseText!==null)){n.loading.end=Math.max(self.performance.now(),n.loading.first);const c=o?r.response:r.responseText,l=r.responseType==="arraybuffer"?c.byteLength:c.length;if(n.loaded=n.total=l,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first),!this.callbacks)return;const u=this.callbacks.onProgress;if(u&&u(n,e,c,r),!this.callbacks)return;const f={url:r.responseURL,data:c,code:s};this.callbacks.onSuccess(f,n,e,r)}else{const c=a.loadPolicy.errorRetry,l=n.retry;N1(c,l,!1,s)?this.retry(c):(G.error(`${s} while loading ${e.url}`),this.callbacks.onError({code:s,text:r.statusText},e,r,n))}}}loadtimeout(){var e;const r=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,n=this.stats.retry;if(N1(r,n,!0))this.retry(r);else{G.warn(`timeout while loading ${this.context.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:r,stats:n}=this;this.retryDelay=kO(e,n.retry),n.retry++,G.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${r.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const r=this.stats;r.loaded=e.loaded,e.lengthComputable&&(r.total=e.total)}getCacheAge(){let e=null;if(this.loader&&kVe.test(this.loader.getAllResponseHeaders())){const r=this.loader.getResponseHeader("age");e=r?parseFloat(r):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function OVe(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const LVe=/(\d+)-(\d+)\/(\d+)/;class wB{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||MVe,this.controller=new self.AbortController,this.stats=new TE}destroy(){this.loader=this.callbacks=null,this.abortInternal()}abortInternal(){const e=this.response;e!=null&&e.ok||(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,r,n){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const a=PVe(e,this.controller.signal),s=n.onProgress,o=e.responseType==="arraybuffer",c=o?"byteLength":"length",{maxTimeToFirstByteMs:l,maxLoadTimeMs:u}=r.loadPolicy;this.context=e,this.config=r,this.callbacks=n,this.request=this.fetchSetup(e,a),self.clearTimeout(this.requestTimeout),r.timeout=l&&me(l)?l:u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),n.onTimeout(i,e,this.response)},r.timeout),self.fetch(this.request).then(f=>{this.response=this.loader=f;const d=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),r.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),n.onTimeout(i,e,this.response)},u-(d-i.loading.start)),!f.ok){const{status:h,statusText:p}=f;throw new FVe(p||"fetch, bad network response",h,f)}return i.loading.first=d,i.total=DVe(f.headers)||i.total,s&&me(r.highWaterMark)?this.loadProgressively(f,i,e,r.highWaterMark,s):o?f.arrayBuffer():e.responseType==="json"?f.json():f.text()}).then(f=>{const{response:d}=this;self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const h=f[c];h&&(i.loaded=i.total=h);const p={url:d.url,data:f,code:d.status};s&&!me(r.highWaterMark)&&s(i,e,f,d),n.onSuccess(p,i,e,d)}).catch(f=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const d=f&&f.code||0,h=f?f.message:null;n.onError({code:d,text:h},e,f?f.details:null,i)})}getCacheAge(){let e=null;if(this.response){const r=this.response.headers.get("age");e=r?parseFloat(r):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,r,n,i=0,a){const s=new ZQ,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return s.dataLength&&a(r,n,s.flush(),e),Promise.resolve(new ArrayBuffer(0));const u=l.value,f=u.length;return r.loaded+=f,f=i&&a(r,n,s.flush(),e)):a(r,n,u,e),c()}).catch(()=>Promise.reject());return c()}}function PVe(t,e){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(Pt({},t.headers))};return t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),r}function NVe(t){const e=LVe.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function DVe(t){const e=t.get("Content-Range");if(e){const n=NVe(e);if(me(n))return n}const r=t.get("Content-Length");if(r)return parseInt(r)}function MVe(t,e){return new self.Request(t.url,e)}class FVe extends Error{constructor(e,r,n){super(e),this.code=void 0,this.details=void 0,this.code=r,this.details=n}}const BVe=/\s/,UVe={newCue(t,e,r,n){const i=[];let a,s,o,c,l;const u=self.VTTCue||self.TextTrackCue;for(let d=0;d=16?c--:c++;const h=iZ(l.trim()),p=HO(e,r,h);t!=null&&(f=t.cues)!=null&&f.getCueById(p)||(s=new u(e,r,h),s.id=p,s.line=d+1,s.align="left",s.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(s))}return t&&i.length&&(i.sort((d,h)=>d.line==="auto"||h.line==="auto"?0:d.line>8&&h.line>8?h.line-d.line:d.line-h.line),i.forEach(d=>kQ(t,d))),i}},jVe={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},HVe=sn(sn({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:cZ,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:WGe,bufferController:tVe,capLevelController:zO,errorController:Fze,fpsController:RVe,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:yQ,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:jVe},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},zVe()),{},{subtitleStreamController:QGe,subtitleTrackController:JGe,timelineController:_Ve,audioStreamController:YGe,audioTrackController:qGe,emeController:Qu,cmcdController:Hs,contentSteeringController:CVe});function zVe(){return{cueHandler:UVe,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 GVe(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=eI(t),n=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(a=>{const s=`${a==="level"?"playlist":a}LoadPolicy`,o=e[s]===void 0,c=[];i.forEach(l=>{const u=`${a}Loading${l}`,f=e[u];if(f!==void 0&&o){c.push(u);const d=r[s].default;switch(e[s]={default:d},l){case"TimeOut":d.maxLoadTimeMs=f,d.maxTimeToFirstByteMs=f;break;case"MaxRetry":d.errorRetry.maxNumRetry=f,d.timeoutRetry.maxNumRetry=f;break;case"RetryDelay":d.errorRetry.retryDelayMs=f,d.timeoutRetry.retryDelayMs=f;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=f,d.timeoutRetry.maxRetryDelayMs=f;break}}}),c.length&&G.warn(`hls.js config: "${c.join('", "')}" setting(s) are deprecated, use "${s}": ${JSON.stringify(e[s])}`)}),sn(sn({},r),e)}function eI(t){return t&&typeof t=="object"?Array.isArray(t)?t.map(eI):Object.keys(t).reduce((e,r)=>(e[r]=eI(t[r]),e),{}):t}function VVe(t){const e=t.loader;e!==wB&&e!==cZ?(G.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):OVe()&&(t.loader=wB,t.progressive=!0,t.enableSoftwareAES=!0,G.log("[config]: Progressive streaming enabled, using FetchLoader"))}class Za{static get version(){return"1.4.0"}static isSupported(){return nGe()}static get Events(){return $}static get ErrorTypes(){return ye}static get ErrorDetails(){return q}static get DefaultConfig(){return Za.defaultConfig?Za.defaultConfig:HVe}static set DefaultConfig(e){Za.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new np,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,$He(e.debug||!1,"Hls instance");const r=this.config=GVe(Za.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,r.progressive&&VVe(r);const{abrController:n,bufferController:i,capLevelController:a,errorController:s,fpsController:o}=r,c=new s(this),l=this.abrController=new n(this),u=this.bufferController=new i(this),f=this.capLevelController=new a(this),d=new o(this),h=new xze(this),p=new wze(this),v=r.contentSteeringController,m=v?new v(this):null,g=this.levelController=new Uze(this,m),y=new jze(this),x=new zze(this.config),b=this.streamController=new GGe(this,y,x);f.setStreamController(b),d.setStreamController(b);const _=[h,g,b];m&&_.splice(1,0,m),this.networkControllers=_;const S=[l,u,f,d,p,y];this.audioTrackController=this.createController(r.audioTrackController,_);const w=r.audioStreamController;w&&_.push(new w(this,y,x)),this.subtitleTrackController=this.createController(r.subtitleTrackController,_);const R=r.subtitleStreamController;R&&_.push(new R(this,y,x)),this.createController(r.timelineController,S),x.emeController=this.emeController=this.createController(r.emeController,S),this.cmcdController=this.createController(r.cmcdController,S),this.latencyController=this.createController(Tze,S),this.coreComponents=S,_.push(c);const I=c.onErrorOut;typeof I=="function"&&this.on($.ERROR,I,c)}createController(e,r){if(e){const n=new e(this);return r&&r.push(n),n}return null}on(e,r,n=this){this._emitter.on(e,r,n)}once(e,r,n=this){this._emitter.once(e,r,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,r,n=this,i){this._emitter.off(e,r,n,i)}listeners(e){return this._emitter.listeners(e)}emit(e,r,n){return this._emitter.emit(e,r,n)}trigger(e,r){if(this.config.debug)return this.emit(e,e,r);try{return this.emit(e,e,r)}catch(n){G.error("An internal error happened while handling event "+e+'. Error message: "'+n.message+'". Here is a stacktrace:',n),this.trigger($.ERROR,{type:ye.OTHER_ERROR,details:q.INTERNAL_EXCEPTION,fatal:!1,event:e,error:n})}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){G.log("destroy"),this.trigger($.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(r=>r.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(r=>r.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){G.log("attachMedia"),this._media=e,this.trigger($.MEDIA_ATTACHING,{media:e})}detachMedia(){G.log("detachMedia"),this.trigger($.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const r=this.media,n=this.url,i=this.url=J0.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});G.log(`loadSource:${i}`),r&&n&&n!==i&&this.bufferController.hasSourceTypes()&&(this.detachMedia(),this.attachMedia(r)),this.trigger($.MANIFEST_LOADING,{url:e})}startLoad(e=-1){G.log(`startLoad(${e})`),this.networkControllers.forEach(r=>{r.startLoad(e)})}stopLoad(){G.log("stopLoad"),this.networkControllers.forEach(e=>{e.stopLoad()})}swapAudioCodec(){G.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){G.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e,r=0){this.levelController.removeLevel(e,r)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){G.log(`set currentLevel:${e}`),this.loadLevel=e,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){G.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){G.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){G.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){return this.levelController.startLevel}set startLevel(e){G.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 r=!!e;r!==this.config.capLevelToPlayerSize&&(r?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(G.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e)}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){qA.indexOf(e)>-1&&(this._maxHdcpLevel=e)}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:r}}=this;if(!e)return 0;const n=e.length;for(let i=0;i=r)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:r,maxHdcpLevel:n}=this;let i;if(r===-1&&e&&e.length?i=e.length-1:i=r,n)for(let a=i;a--;){const s=e[a].attrs["HDCP-LEVEL"];if(s&&s<=n)return a}return i}get nextAutoLevel(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)}set nextAutoLevel(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const r=this.audioTrackController;r&&(r.audioTrack=e)}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 r=this.subtitleTrackController;r&&(r.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const r=this.subtitleTrackController;r&&(r.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Za.defaultConfig=void 0;function WVe(t){switch(t.code){case MediaError.MEDIA_ERR_ABORTED:return{code:"ABORTED",description:"Video was aborted"};case MediaError.MEDIA_ERR_NETWORK:return{code:"NETWORK_ERROR",description:"A network error occured, the video failed to stream"};case MediaError.MEDIA_ERR_DECODE:return{code:"DECODE_ERROR",description:"Video stream could not be decoded"};case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:return{code:"SRC_NOT_SUPPORTED",description:"The video type is not supported by your browser"};default:return{code:"UNKNOWN_ERROR",description:"Unknown media error occured"}}}function KVe(t,e){const r=e,n=Sr(t);return{getId(){return"video"},play(){r.play()},pause(){r.pause()},exitFullscreen(){xn.fullscreenElement&&xn.exitFullscreen()},enterFullscreen(){if(!(!hO()||xn.fullscreenElement)){if(pE()){n.wrapperElement&&xn.requestFullscreen(n.wrapperElement);return}dO()&&r.webkitEnterFullscreen()}},startAirplay(){const i=r;i.webkitShowPlaybackTargetPicker&&i.webkitShowPlaybackTargetPicker()},setTime(i){let a=Math.min(i,r.duration);a=Math.max(0,a),!Number.isNaN(a)&&(r.currentTime=a,n.progress.time=a,Xa(t,n))},setSeeking(i){if(n.mediaPlaying.isSeeking=i,n.mediaPlaying.isDragSeeking=i,Jt(t,n),!i){n.pausedWhenSeeking||this.play();return}n.pausedWhenSeeking=n.mediaPlaying.isPaused,this.pause()},async setVolume(i){let a=Math.min(i,1);a=Math.max(0,a),await G0()&&(r.volume=a),n.mediaPlaying.volume=a,Jt(t,n),fQ(a)},setSource(i){if(!i){k1(t,n),r.removeAttribute("src"),r.load(),n.source=null,no(t,n);return}if(k1(t,n),(i==null?void 0:i.type)===Yt.HLS)if(r.canPlayType("application/vnd.apple.mpegurl"))r.src=i.source;else{if(!Za.isSupported()){n.error={name:"Not supported",description:"Your browser does not support HLS video"},Yw(t,n);return}const a=new Za({enableWorker:!1});n.hlsInstance=a,a.on(Za.Events.ERROR,(s,o)=>{var c;o.fatal&&(n.error={name:`error ${o.details}`,description:((c=o.error)==null?void 0:c.message)??"Something went wrong"},Yw(t,n)),console.error("HLS error",o)}),a.attachMedia(r),a.loadSource(i.source)}else i.type===Yt.MP4&&(r.src=i.source);n.source={quality:i.quality,type:i.type,url:i.source,caption:null,embedId:i.embedId,providerId:i.providerId},no(t,n)},setCaption(i,a){var s;n.source&&(S1((s=n.source.caption)==null?void 0:s.url),n.source.caption={id:i,url:a},no(t,n))},clearCaption(){var i;n.source&&(S1((i=n.source.caption)==null?void 0:i.url),n.source.caption=null,no(t,n))},togglePictureInPicture(){if(aX()){const i=r;i.webkitSetPresentationMode(i.webkitPresentationMode==="picture-in-picture"?"inline":"picture-in-picture")}iX()&&(r!==document.pictureInPictureElement?r.requestPictureInPicture():document.exitPictureInPicture())},setPlaybackSpeed(i){r.playbackRate=i,n.mediaPlaying.playbackSpeed=i,Jt(t,n)},providerStart(){var x,b,_;this.setVolume(uQ());const i=()=>{n.mediaPlaying.isPaused=!0,n.mediaPlaying.isPlaying=!1,Jt(t,n)},a=()=>{n.mediaPlaying.isPaused=!1,n.mediaPlaying.isPlaying=!0,n.mediaPlaying.isLoading=!1,n.mediaPlaying.hasPlayedOnce=!0,Jt(t,n)},s=()=>{n.mediaPlaying.isLoading=!0,Jt(t,n)},o=()=>{n.mediaPlaying.isSeeking=!0,Jt(t,n)},c=()=>{n.mediaPlaying.isSeeking=!1,Jt(t,n)},l=()=>{n.progress.duration=r.duration,Xa(t,n)},u=()=>{n.progress.duration=r.duration,n.progress.time=r.currentTime,Xa(t,n)},f=()=>{n.progress.buffered=yHe(r.currentTime,r.buffered),Xa(t,n)},d=()=>{n.mediaPlaying.isFirstLoading=!1,n.mediaPlaying.isLoading=!1,Jt(t,n)},h=()=>{n.mediaPlaying.playbackSpeed=r.playbackRate,Jt(t,n)},p=()=>{n.interface.isFullscreen=!!document.fullscreenElement||!!document.webkitFullscreenElement,gn(t,n)},v=async()=>{await G0()&&(n.mediaPlaying.volume=r.volume,Jt(t,n))},m=S=>{n.interface.isFocused=S.type!=="mouseleave",gn(t,n)},g=S=>{S.availability==="available"&&(n.canAirplay=!0,ld(t,n))},y=()=>{if(r.error){const S=WVe(r.error);console.error("Native video player threw error",r.error),n.error={description:S.description,name:`Error ${S.code}`},this.pause()}else n.error=null;Yw(t,n)};return(x=n.wrapperElement)==null||x.addEventListener("click",m),(b=n.wrapperElement)==null||b.addEventListener("mouseenter",m),(_=n.wrapperElement)==null||_.addEventListener("mouseleave",m),r.addEventListener("volumechange",v),r.addEventListener("pause",i),r.addEventListener("playing",a),r.addEventListener("seeking",o),r.addEventListener("seeked",c),r.addEventListener("progress",f),r.addEventListener("waiting",s),r.addEventListener("timeupdate",u),r.addEventListener("loadedmetadata",l),r.addEventListener("canplay",d),r.addEventListener("ratechange",h),xn.addEventListener("fullscreenchange",p),r.addEventListener("error",y),r.addEventListener("webkitplaybacktargetavailabilitychanged",g),n.source&&this.setSource({quality:n.source.quality,source:n.source.url,type:n.source.type,embedId:n.source.embedId,providerId:n.source.providerId}),{destroy:()=>{var S,w,R;r.removeEventListener("pause",i),r.removeEventListener("playing",a),r.removeEventListener("seeking",o),r.removeEventListener("volumechange",v),r.removeEventListener("seeked",c),r.removeEventListener("timeupdate",u),r.removeEventListener("loadedmetadata",l),r.removeEventListener("progress",f),r.removeEventListener("waiting",s),r.removeEventListener("error",y),r.removeEventListener("canplay",d),xn.removeEventListener("fullscreenchange",p),(S=n.wrapperElement)==null||S.removeEventListener("click",m),(w=n.wrapperElement)==null||w.removeEventListener("mouseenter",m),(R=n.wrapperElement)==null||R.removeEventListener("mouseleave",m),r.removeEventListener("webkitplaybacktargetavailabilitychanged",g)}}}}}function YVe(t){const e=Re(),r=Cn(e),n=Es(e),i=A.useRef(null),a=A.useMemo(()=>!!n.wrapperInitialized,[n]),s=A.useMemo(()=>n.stateProviderId,[n]);return A.useEffect(()=>{if(!a||!i.current)return;const o=KVe(e,i.current);dQ(e,o);const{destroy:c}=o.providerStart();return()=>{try{hQ(e,o.getId())}catch{}c()}},[e,a,s]),E("video",{ref:i,autoPlay:t.autoPlay,muted:r.volume===0,playsInline:!0,className:"z-0 h-full w-full"})}function qVe(t){const e=Re();return Es(e).stateProviderId!=="video"?null:E(YVe,{...t})}function XVe(t){const e=A.useRef(null),r=Re(),n=Bi(r),i=ui(r),a=typeof t.children=="function"?t.children({isFullscreen:n.isFullscreen}):t.children;return E(EHe,{onGoBack:t.onGoBack,media:i==null?void 0:i.meta.meta,children:Y("div",{ref:e,className:["is-video-player popout-location relative h-full w-full select-none overflow-hidden bg-black",t.includeSafeArea||n.isFullscreen?"[border-left:env(safe-area-inset-left)_solid_transparent] [border-right:env(safe-area-inset-right)_solid_transparent]":""].join(" "),children:[E(SHe,{}),E(qVe,{autoPlay:t.autoPlay}),E(xHe,{}),E(bHe,{wrapper:e.current}),E("div",{className:"absolute inset-0",children:a})]})})}function QVe(t){return E(p5e,{children:E(XVe,{...t})})}function uZ({text:t,scale:e}){const{captionSettings:r}=sd(),n=(t||"").replaceAll(/\r?\n/g,"
"),i=JBe(n,{ALLOWED_TAGS:["c","b","i","u","span","ruby","rt","br"],ADD_TAGS:["v","lang"],ALLOWED_ATTR:["title","lang"]});return E("p",{className:"pointer-events-none mb-1 select-none rounded px-4 py-1 text-center [text-shadow:0_2px_4px_rgba(0,0,0,0.5)]",style:{...r.style,fontSize:r.style.fontSize*(e??1)},children:E("span",{dangerouslySetInnerHTML:{__html:i},dir:"auto"})})}function ZVe({isControlsShown:t}){var u,f;const e=Re(),r=ym(e).source,n=Xo(e).time,{captionSettings:i,setCaptionDelay:a}=sd(),s=A.useRef([]),o=A.useRef(a);A.useEffect(()=>{o.current=a},[a]),HFe(async()=>{var h;const d=(h=r==null?void 0:r.caption)==null?void 0:h.url;if(d){const v=await(await fetch(d)).text();try{s.current=Hq(v)}catch{s.current=[]}a(0)}else s.current=[]},[(u=r==null?void 0:r.caption)==null?void 0:u.url]),A.useEffect(()=>{o.current(0)},[(f=r==null?void 0:r.caption)==null?void 0:f.url]);const c=A.useCallback((d,h,p,v)=>{const m=d/1e3+p,g=h/1e3+p;return Math.max(0,m)<=v&&Math.max(0,g)>=v},[]);if(!s.current.length)return null;const l=s.current.filter(({start:d,end:h})=>c(d,h,i.delay,n));return E($i,{className:["pointer-events-none absolute flex w-full flex-col items-center transition-[bottom]",t?"bottom-24":"bottom-12"].join(" "),animation:"slide-up",show:!0,children:l.map(({start:d,end:h,content:p})=>E(uZ,{text:p},`${d}-${h}`))})}function JVe(){const t=Re(),e=ui(t);return(e==null?void 0:e.meta.meta.type)!==ie.SERIES?null:E("div",{className:"mx-2 h-6 w-px bg-white opacity-50"})}function TB(t){const{t:e}=ke(),r=Re(),n=st(r),i=Bi(r),{isMobile:a}=Aa(!1);return E("div",{className:t.className,children:E("div",{className:"relative",children:E(hX,{id:"settings",children:E(_s,{active:i.popout==="settings",className:t.className,onClick:()=>n.openPopout("settings"),text:a?e("videoPlayer.buttons.settings"):void 0,icon:ue.GEAR})})})})}function eWe(){const t=Re(),e=Bi(t),r=Cn(t);return Y("div",{className:[e.volumeChangedWithKeybind?"mt-10 scale-100 opacity-100":"mt-5 scale-75 opacity-0","absolute left-1/2 z-[100] flex -translate-x-1/2 items-center space-x-4 rounded-full bg-bink-300 bg-opacity-50 px-5 py-2 transition-all duration-100"].join(" "),children:[E(Ve,{icon:r.volume>0?ue.VOLUME:ue.VOLUME_X,className:"text-xl text-white"}),E("div",{className:"h-2 w-44 overflow-hidden rounded-full bg-denim-100",children:E("div",{className:"h-full rounded-r-full bg-bink-500 transition-[width] duration-100",style:{width:`${r.volume*100}%`}})})]})}function AT(t){return E("div",{className:"absolute inset-0 flex items-center justify-center",children:t.children})}function tWe(){const t=Re(),e=st(t),r=A.useCallback(()=>{e.setLeftControlsHover(!0)},[e]),n=A.useCallback(()=>{e.setLeftControlsHover(!1)},[e]);return Y(xr,{children:[Y("div",{className:"flex items-center px-2",onMouseLeave:n,onMouseEnter:r,children:[E(lX,{}),E(y7e,{}),E(T7e,{className:"mr-2"}),E(pX,{})]}),E(_7e,{})]})}function rWe(t){const[e,r]=A.useState(!1),{isMobile:n}=Aa(),i=A.useCallback(a=>{r(a)},[r]);return E(QVe,{autoPlay:t.autoPlay,includeSafeArea:t.includeSafeArea,onGoBack:t.onGoBack,children:({isFullscreen:a})=>Y(xr,{children:[E(m7e,{}),E(b7e,{}),E(eWe,{}),Y(A7e,{onGoBack:t.onGoBack,children:[Y(u7e,{onBackdropChange:i,children:[E(AT,{children:E(g7e,{})}),E(AT,{children:E(f7e,{})}),E(AT,{children:E(v7e,{})}),n?E($i,{animation:"fade",show:e,className:"absolute inset-0 flex items-center justify-center",children:E(x7e,{})}):"",E($i,{animation:"slide-down",show:e,className:"pointer-events-auto absolute inset-x-0 top-0 flex flex-col px-8 py-6 pb-2",children:E(p7e,{showControls:n,onClick:t.onGoBack,isFullScreen:!0})}),Y($i,{animation:"slide-up",show:e,className:["pointer-events-auto absolute inset-x-0 bottom-0 flex flex-col px-4 pb-2",t.includeSafeArea||a?"[margin-bottom:env(safe-area-inset-bottom)]":""].join(" "),children:[Y("div",{className:"flex w-full items-center space-x-3",children:[n&&E(pX,{noDuration:!0}),E(S7e,{})]}),E("div",{className:"flex items-center",children:n?Y("div",{className:"grid w-full grid-cols-[56px,1fr,56px] items-center",children:[E("div",{}),Y("div",{className:"flex items-center justify-center",children:[E(Y6,{}),E(K6,{}),E(TB,{})]}),E(W6,{})]}):Y(xr,{children:[E(tWe,{}),E("div",{className:"flex-1"}),E(Y6,{}),E(JVe,{}),E(TB,{}),E(Vq,{}),E(Gq,{}),E(K6,{}),E(W6,{})]})})]}),e?E(fHe,{}):null]}),E(ZVe,{isControlsShown:e}),t.children]})]})})}function nWe(){const{t}=ke(),e=lE();return Y("div",{className:"flex-1",children:[E(va,{children:E("title",{children:t("media.errors.failedMeta")})}),E("div",{className:"fixed inset-x-0 top-0 px-8 py-6",children:E(_c,{onClick:e})}),E(Kk,{children:E("p",{className:"my-6 max-w-lg",children:t("media.errors.mediaFailed")})})]})}function RB(){return E("div",{className:"h-9 w-[220px] rounded-full bg-slate-800 opacity-50"})}function iWe({event:t}){return Y("div",{className:"flex h-9 w-[220px] items-center rounded-full bg-slate-800 p-3 text-denim-700",children:[E("div",{className:"mr-2 flex w-[18px] items-center justify-center",children:t.errored?E(Ve,{icon:ue.X,className:"text-[0.85em] text-rose-400"}):E(tQ,{className:"h-[18px] w-[18px] text-bink-700",percentage:t.percentage,radius:40})}),E("div",{className:"flex-1 overflow-hidden",children:E("p",{className:`overflow-hidden text-ellipsis whitespace-nowrap ${t.errored?"text-rose-400":""}`,children:t.id})})]})}function aWe(t){return Y("div",{className:"relative h-16 w-[400px] overflow-hidden",children:[E("div",{className:"absolute inset-0 flex items-center justify-center",children:E("div",{className:"relative flex h-full w-[220px] items-center",children:Y("div",{className:"absolute inset-y-0 left-0 flex items-center gap-[16px] transition-transform duration-200",style:{transform:`translateX(${-1*(220+16)*t.events.length}px)`},children:[E(RB,{}),t.events.map(e=>E(iWe,{event:e},e.eventId)),E(RB,{})]})})}),E("div",{className:"absolute inset-y-0 left-0 w-40 bg-gradient-to-r from-denim-100 to-transparent"}),E("div",{className:"absolute inset-y-0 right-0 w-40 bg-gradient-to-l from-denim-100 to-transparent"})]})}function AB(t){return E("div",{className:"relative my-4 max-w-[18rem]",children:E(Ug,{value:t.selectedItem,onChange:t.setSelectedItem,children:({open:e})=>Y(xr,{children:[Y(Ug.Button,{className:"relative w-full cursor-default rounded-lg bg-denim-500 py-2 pl-3 pr-10 text-left text-white shadow-md focus:outline-none focus-visible:border-indigo-500 focus-visible:ring-2 focus-visible:ring-bink-500 focus-visible:ring-opacity-75 focus-visible:ring-offset-2 focus-visible:ring-offset-bink-300 sm:text-sm",children:[E("span",{className:"block truncate",children:t.selectedItem.name}),E("span",{className:"pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2",children:E(Ve,{icon:ue.CHEVRON_DOWN,className:`transform transition-transform ${e?"rotate-180":""}`})})]}),E($A,{as:A.Fragment,leave:"transition ease-in duration-100",leaveFrom:"opacity-100",leaveTo:"opacity-0",children:E(Ug.Options,{className:"absolute left-0 right-0 top-10 z-10 mt-1 max-h-60 overflow-auto rounded-md bg-denim-500 py-1 text-white shadow-lg ring-1 ring-black ring-opacity-5 scrollbar-thin scrollbar-track-denim-400 scrollbar-thumb-denim-200 focus:outline-none sm:top-10 sm:text-sm",children:t.options.map(r=>E(Ug.Option,{className:({active:n})=>`relative cursor-default select-none py-2 pl-10 pr-4 ${n?"bg-denim-400 text-bink-700":"text-white"}`,value:r,children:r.name},r.id))})})]})})})}function sWe(t){return Y(xr,{children:[E(va,{children:E("body",{"data-no-scroll":!0})}),Y("div",{className:"fixed inset-0 z-[99999]",children:[E($i,{animation:"fade",className:"absolute inset-0 bg-[rgba(8,6,18,0.85)]",isChild:!0}),t.children]})]})}function oWe(t){return E($i,{className:"fixed inset-0 z-[9999]",animation:"none",show:t.show,children:E(sWe,{children:E($i,{isChild:!0,className:"flex h-full w-full items-center justify-center",animation:"slide-up",children:t.children})})})}function fZ(t){return ql.createPortal(E(oWe,{show:t.show,children:t.children}),document.body)}function dZ(t){return E("div",{className:["relative mx-2 w-[500px] overflow-hidden rounded-lg bg-denim-300 px-10 py-10 sm:w-[500px] md:w-[500px] lg:w-[1000px]",t.className??""].join(" "),children:t.children})}function vo(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function AE(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&u1(t,e)}function xm(t,e){if(e&&(Gt(e)==="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return vo(t)}function xa(t){return xa=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},xa(t)}function lWe(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function cWe(t){return GY(t)||lWe(t)||VY(t)||WY()}function IB(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function $B(t){for(var e=1;e1&&arguments[1]!==void 0?arguments[1]:{};Di(this,t),this.init(e,r)}return Mi(t,[{key:"init",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.prefix=n.prefix||"i18next:",this.logger=r||uWe,this.options=n,this.debug=n.debug}},{key:"setDebug",value:function(r){this.debug=r}},{key:"log",value:function(){for(var r=arguments.length,n=new Array(r),i=0;i