From 7255ce8bcae218cfd08835296e6c9ae21cc88c0e Mon Sep 17 00:00:00 2001 From: colobas Date: Thu, 15 Feb 2024 19:40:45 +0000 Subject: [PATCH] deploy: 222a4f51680260c3be58c1ba7473c8ce0a4a6092 --- assets/{index-VXrCd0hU.js => index-L-Wh-Sy9.js} | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename assets/{index-VXrCd0hU.js => index-L-Wh-Sy9.js} (99%) diff --git a/assets/index-VXrCd0hU.js b/assets/index-L-Wh-Sy9.js similarity index 99% rename from assets/index-VXrCd0hU.js rename to assets/index-L-Wh-Sy9.js index 145c414..bb0ec7f 100644 --- a/assets/index-VXrCd0hU.js +++ b/assets/index-L-Wh-Sy9.js @@ -32,4 +32,4 @@ Clique num vídeo para ver o debate completo. `),c=[],h=e?Zl(e.baseTime,e.timescale):0;let u="00:00.000",d=0,g=0,f,m=!0;o.oncue=function(T){const E=t[s];let S=t.ccOffset;const y=(d-h)/9e4;if(E!=null&&E.new&&(g!==void 0?S=t.ccOffset=E.start:kc(t,s,y)),y){if(!e){f=new Error("Missing initPTS for VTT MPEGTS");return}S=y-t.presentationOffset}const v=T.endTime-T.startTime,x=Se((T.startTime+S-g)*9e4,i*9e4)/9e4;T.startTime=Math.max(x,0),T.endTime=Math.max(x+v,0);const b=T.text.trim();T.text=decodeURIComponent(encodeURIComponent(b)),T.id||(T.id=Si(T.startTime,T.endTime,b)),T.endTime>0&&c.push(T)},o.onparsingerror=function(T){f=T},o.onflush=function(){if(f){a(f);return}r(c)},l.forEach(T=>{if(m)if(ws(T,"X-TIMESTAMP-MAP=")){m=!1,T.slice(16).split(",").forEach(E=>{ws(E,"LOCAL:")?u=E.slice(6):ws(E,"MPEGTS:")&&(d=parseInt(E.slice(7)))});try{g=wc(u)/1e3}catch(E){f=E}return}else T===""&&(m=!1);o.parse(T+` `)}),o.flush()}const Ps="stpp.ttml.im1t",Vn=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Hn=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Fc={left:"start",center:"center",right:"end",start:"start",end:"end"};function Rr(n,e,t,s){const i=H(new Uint8Array(n),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>Pe(o)),a=Jl(e.baseTime,1,e.timescale);try{r.forEach(o=>t(Oc(o,a)))}catch(o){s(o)}}function Oc(n,e){const i=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(r).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||r[d],u),{}),o=i.getAttribute("xml:space")!=="preserve",l=br(Fs(i,"styling","style")),c=br(Fs(i,"layout","region")),h=Fs(i,"body","[begin]");return[].map.call(h,u=>{const d=Wn(u,o);if(!d||!u.hasAttribute("begin"))return null;const g=Ms(u.getAttribute("begin"),a),f=Ms(u.getAttribute("dur"),a);let m=Ms(u.getAttribute("end"),a);if(g===null)throw Ir(u);if(m===null){if(f===null)throw Ir(u);m=g+f}const T=new xi(g-e,m-e,d);T.id=Si(T.startTime,T.endTime,T.text);const E=c[u.getAttribute("region")],S=l[u.getAttribute("style")],y=Mc(E,S,l),{textAlign:v}=y;if(v){const x=Fc[v];x&&(T.lineAlign=x),T.align=v}return ne(T,y),T}).filter(u=>u!==null)}function Fs(n,e,t){const s=n.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function br(n){return n.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Wn(n,e){return[].slice.call(n.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+` `:(r=s.childNodes)!=null&&r.length?Wn(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Mc(n,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(i=t[a]),r.reduce((o,l)=>{const c=Os(e,s,l)||Os(n,s,l)||Os(i,s,l);return c&&(o[l]=c),o},{})}function Os(n,e,t){return n&&n.hasAttributeNS(e,t)?n.getAttributeNS(e,t):null}function Ir(n){return new Error(`Could not parse ttml timestamp ${n}`)}function Ms(n,e){if(!n)return null;let t=$n(n);return t===null&&(Vn.test(n)?t=Nc(n,e):Hn.test(n)&&(t=Uc(n,e))),t}function Nc(n,e){const t=Vn.exec(n),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function Uc(n,e){const t=Hn.exec(n),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class Bc{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Cr(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new Mt(this,"textTrack1"),t=new Mt(this,"textTrack2"),s=new Mt(this,"textTrack3"),i=new Mt(this,"textTrack4");this.cea608Parser1=new vr(1,e,t),this.cea608Parser2=new vr(3,s,i)}}addCues(e,t,s,i,r){let a=!1;for(let o=r.length;o--;){const l=r[o],c=$c(l[0],l[1],t,s);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],s),a=!0,c/(s-t)>.5))return}if(a||r.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r}){const{unparsedVttFrags:a}=this;s==="main"&&(this.initPTS[t.cc]={baseTime:i,timescale:r}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(p.FRAG_LOADED,o)}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i{at(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Cr(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;sr.textCodec===Ps);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Nn(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const a=this.media,o=a?Gt(a.textTracks):null;if(this.tracks.forEach((l,c)=>{let h;if(o){let u=null;for(let d=0;dc!==null).map(c=>c.label);l.length&&A.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,a=this.captionsProperties[r];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:i,lastCc:r,lastSn:a,lastPartIndex:o}=this;if(!(!this.enabled||!s||!i)&&t.frag.type===N.MAIN){var l,c;const{cc:h,sn:u}=t.frag,d=(l=t==null||(c=t.part)==null?void 0:c.index)!=null?l:-1;u===a+1||u===a&&d===o+1||h===r||(s.reset(),i.reset()),this.lastCc=h,this.lastSn=u,this.lastPartIndex=d}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===N.SUBTITLE)if(i.byteLength){const r=s.decryptdata,a="stats"in t;if(r==null||!r.encrypted||a){const o=this.tracks[s.level],l=this.vttCCs;l[s.cc]||(l[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Ps?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;Rr(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{A.log(`Failed to parse IMSC1: ${i}`),s.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:a}=this,o=r.length-1;if(!r[s.cc]&&o===-1){a.push(e);return}const l=this.hls,c=(t=s.initSegment)!=null&&t.data?ve(s.initSegment.data,new Uint8Array(i)):i;Pc(c,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),l.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},h=>{const u=h.message==="Missing initPTS for VTT MPEGTS";u?a.push(e):this._fallbackToIMSC1(s,i),A.log(`Failed to parse VTT cue: ${h}`),!(u&&o>s.cc)&&l.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:h})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||Rr(t,this.initPTS[e.cc],()=>{s.textCodec=Ps,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>dn(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===N.SUBTITLE&&this.onFragLoaded(p.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){this.initCea608Parsers();const{cea608Parser1:s,cea608Parser2:i}=this;if(!this.enabled||!s||!i)return;const{frag:r,samples:a}=t;if(!(r.type===N.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let o=0;oHs(o[l],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>Hs(o[l],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;rthis.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,vi.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let r=e.length-1;const a=Math.max(t,s);for(let o=0;o=a||l.height>=a)&&i(l,e[o+1])){r=o;break}}return r}}class Gc{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/r,c=this.hls;if(c.trigger(p.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let h=c.currentLevel;A.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=h)&&(h=h-1,c.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:c.currentLevel}),c.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const Ut="[eme]";class ct{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=ct.CDMCleanupPromise?[ct.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=A.debug.bind(A,Ut),this.log=A.log.bind(A,Ut),this.warn=A.warn.bind(A,Ut),this.error=A.error.bind(A,Ut),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(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t[e];if(i)return i.licenseUrl;if(e===te.WIDEVINE&&s)return s;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(a,o,l)=>!!a&&l.indexOf(a)===o,i=t.map(a=>a.audioCodec).filter(s),r=t.map(a=>a.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const l=c=>{const h=c.shift();this.getMediaKeysPromise(h,i,r).then(u=>a({keySystem:h,mediaKeys:u})).catch(u=>{c.length?l(c):u instanceof xe?o(u):o(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};l(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Qr===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){const i=Qa(e,t,s,this.config.drmSystemOptions),r=this.keySystemAccessPromises[e];let a=r==null?void 0:r.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(i)}`),a=this.requestMediaKeySystemAccess(e,i);const o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const c=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(h=>(this.log(`Media-keys created for "${e}"`),c.then(u=>u?this.setMediaKeysServerCertificate(h,e,u):h))),o.mediaKeys.catch(h=>{this.error(`Failed to create media-keys for "${e}"}: ${h}`)}),o.mediaKeys})}return a.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Ie.hexDump(e.keyId||[])}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=this.getKeyIdString(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.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 Ie.hexDump(e.keyId)}updateKeySession(e,t){var s;const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${Ie.hexDump(((s=e.decryptdata)==null?void 0:s.keyId)||[])} - } (data length: ${t&&t.byteLength})`),i.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,s)=>{const i=Es(this.config),r=e.map(Oi).filter(a=>!!a&&i.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:a})=>{const o=Mi(a);o?t(o):s(new Error(`Unable to find format for key-system "${a}"`))}).catch(s)})}loadKey(e){const t=e.keyInfo.decryptdata,s=this.getKeyIdString(t),i=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);let r=this.keyIdToKeySessionPromise[s];return r||(r=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t});return this.generateRequestWithPreferredKeySession(l,"cenc",t.pssh,"playlist-key")}))),r.catch(a=>this.handleError(a))),r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof xe?this.hls.trigger(p.ERROR,e.data):this.hls.trigger(p.ERROR,{type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=Oi(e.keyFormat),r=i?[i]:Es(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Es(this.config)),e.length===0)throw new xe({type:B.KEY_SYSTEM_ERROR,details:I.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:t,initData:s}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),s===null)return;let i,r;if(t==="sinf"&&this.config.drmSystems[te.FAIRPLAY]){const h=ae(new Uint8Array(s));try{const u=oi(JSON.parse(h).sinf),d=an(new Uint8Array(u));if(!d)return;i=d.subarray(8,24),r=te.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const h=Ao(s);if(h===null)return;h.version===0&&h.systemId===Xr.WIDEVINE&&h.data&&(i=h.data.subarray(8,24)),r=Xa(h.systemId)}if(!r||!i)return;const a=Ie.hexDump(i),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let c=o[a];for(let h=0;hthis.generateRequestWithPreferredKeySession(u,t,s,"encrypted-event-key-match"));break}}c||(c=o[a]=this.getKeySystemSelectionPromise([r]).then(({keySystem:h,mediaKeys:u})=>{var d;this.throwIfDestroyed();const g=new Rt("ISO-23001-7",a,(d=Mi(h))!=null?d:"");return g.pssh=new Uint8Array(s),g.keyId=i,this.attemptSetMediaKeys(h,u).then(()=>{this.throwIfDestroyed();const f=this.createMediaKeySessionContext({decryptdata:g,keySystem:h,mediaKeys:u});return this.generateRequestWithPreferredKeySession(f,t,s,"encrypted-event-no-match")})})),c.catch(h=>this.handleError(h))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r,a;const o=(r=this.config.drmSystems)==null||(a=r[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const f=o.call(this.hls,t,s,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,s=e.decryptdata.pssh=f.initData?new Uint8Array(f.initData):null}catch(f){var l;if(this.warn(f.message),(l=this.hls)!=null&&l.config.debug)throw f}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${i}": ${c} (init data type: ${t} length: ${s?s.byteLength:null})`);const h=new yi,u=e._onmessage=f=>{const m=e.mediaKeysSession;if(!m){h.emit("error",new Error("invalid state"));return}const{messageType:T,message:E}=f;this.log(`"${T}" message event for session "${m.sessionId}" message size: ${E.byteLength}`),T==="license-request"||T==="license-renewal"?this.renewLicense(e,E).catch(S=>{this.handleError(S),h.emit("error",S)}):T==="license-release"?e.keySystem===te.FAIRPLAY&&(this.updateKeySession(e,Ks("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${T}"`)},d=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){h.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const T=e.keyStatus;h.emit("keyStatus",T),T==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",u),e.mediaKeysSession.addEventListener("keystatuseschange",d);const g=new Promise((f,m)=>{h.on("error",m),h.on("keyStatus",T=>{T.startsWith("usable")?f():T==="output-restricted"?m(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):T==="internal-error"?m(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${T}"`)):T==="expired"?m(new Error("key expired while generating request")):this.warn(`unhandled key status change "${T}"`)})});return e.mediaKeysSession.generateRequest(t,s).then(()=>{var f;this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${c}`)}).catch(f=>{throw new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_SESSION,error:f,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>g).catch(f=>{throw h.removeAllListeners(),this.removeSession(e),f}).then(()=>(h.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,s)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Ie.hexDump("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${Ie.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:r},c=t.certLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,m)=>{a(d.data)},onError:(d,g,f,m)=>{o(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:ue({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,g,f)=>{o(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,g,f)=>{o(new Error("aborted"))}};i.load(l,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s==null?void 0:s.byteLength}) on "${t}"`),i(e)}).catch(a=>{r(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:i,fatal:!0},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u in key message");return Ks(atob(c))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(h){this.error(h)}i(l)}else{const l=s.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)r(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const h=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==te.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=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={},Rt.clearKeyUriToKeyIdMap();const s=t.length;ct.CDMCleanupPromise=Promise.all(t.map(i=>this.removeSession(i)).concat(e==null?void 0:e.setMediaKeys(null).catch(i=>{this.log(`Could not clear media keys: ${i}`)}))).then(()=>{s&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(i=>{this.log(`Could not close sessions and clear media keys: ${i}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);return i>-1&&this.mediaKeySessions.splice(i,1),t.remove().catch(r=>{this.log(`Could not remove session: ${r}`)}).then(()=>t.close()).catch(r=>{this.log(`Could not close session: ${r}`)})}}}ct.CDMCleanupPromise=void 0;class xe extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var ge;(function(n){n.MANIFEST="m",n.AUDIO="a",n.VIDEO="v",n.MUXED="av",n.INIT="i",n.CAPTION="c",n.TIMED_TEXT="tt",n.KEY="k",n.OTHER="o"})(ge||(ge={}));var Js;(function(n){n.DASH="d",n.HLS="h",n.SMOOTH="s",n.OTHER="o"})(Js||(Js={}));var qe;(function(n){n.OBJECT="CMCD-Object",n.REQUEST="CMCD-Request",n.SESSION="CMCD-Session",n.STATUS="CMCD-Status"})(qe||(qe={}));const Kc={[qe.OBJECT]:["br","d","ot","tb"],[qe.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[qe.SESSION]:["cid","pr","sf","sid","st","v"],[qe.STATUS]:["bs","rtp"]};class mt{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(s=>s instanceof mt?s:new mt(s))),this.value=e,this.params=t}}class jn{constructor(e){this.description=void 0,this.description=e}}const Vc="Dict";function Hc(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":typeof n=="object"?JSON.stringify(n):String(n)}function Wc(n,e,t,s){return new Error(`failed to ${n} "${Hc(e)}" as ${t}`,{cause:s})}const _r="Bare Item",Yc="Boolean",jc="Byte Sequence",qc="Decimal",zc="Integer";function Xc(n){return n<-999999999999999||99999999999999912)throw Fe(n,qc);const t=e.toString();return t.includes(".")?t:`${t}.0`}const nh="String";function ah(n){if(Qc.test(n))throw Fe(n,nh);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function oh(n){return n.description||n.toString().slice(7,-1)}function wr(n){const e=oh(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Fe(e,Jc);return e}function Zs(n){switch(typeof n){case"number":if(!O(n))throw Fe(n,_r);return Number.isInteger(n)?qn(n):rh(n);case"string":return ah(n);case"symbol":return wr(n);case"boolean":return eh(n);case"object":if(n instanceof Date)return ih(n);if(n instanceof Uint8Array)return sh(n);if(n instanceof jn)return wr(n);default:throw Fe(n,_r)}}function ei(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw Fe(n,Zc);return n}function Ai(n){return n==null?"":Object.entries(n).map(([e,t])=>t===!0?`;${ei(e)}`:`;${ei(e)}=${Zs(t)}`).join("")}function Xn(n){return n instanceof mt?`${Zs(n.value)}${Ai(n.params)}`:Zs(n)}function lh(n){return`(${n.value.map(Xn).join(" ")})${Ai(n.params)}`}function ch(n,e={whitespace:!0}){if(typeof n!="object")throw Fe(n,Vc);const t=n instanceof Map?n.entries():Object.entries(n),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof mt||(r=new mt(r));let a=ei(i);return r.value===!0?a+=Ai(r.params):(a+="=",Array.isArray(r.value)?a+=lh(r):a+=Xn(r)),a}).join(`,${s}`)}function hh(n,e){return ch(n,e)}const uh=n=>n==="ot"||n==="sf"||n==="st",dh=n=>typeof n=="number"?O(n):n!=null&&n!==""&&n!==!1;function fh(n,e){const t=new URL(n),s=new URL(e);if(t.origin!==s.origin)return n;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")}function gh(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}const Yt=n=>Math.round(n),mh=(n,e)=>(e!=null&&e.baseUrl&&(n=fh(n,e.baseUrl)),encodeURIComponent(n)),Bt=n=>Yt(n/100)*100,ph={br:Yt,d:Yt,bl:Bt,dl:Bt,mtp:Bt,nor:mh,rtp:Bt,tb:Yt};function Th(n,e){const t={};if(n==null||typeof n!="object")return t;const s=Object.keys(n).sort(),i=ne({},ph,e==null?void 0:e.formatters),r=e==null?void 0:e.filter;return s.forEach(a=>{if(r!=null&&r(a))return;let o=n[a];const l=i[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||dh(o)&&(uh(a)&&typeof o=="string"&&(o=new jn(o)),t[a]=o))}),t}function Qn(n,e={}){return n?hh(Th(n,e),ne({whitespace:!1},e)):""}function Eh(n,e={}){if(!n)return{};const t=Object.entries(n),s=Object.entries(Kc).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),i=t.reduce((r,a)=>{var o,l;const[c,h]=a,u=((o=s.find(d=>d[1].includes(c)))==null?void 0:o[0])||qe.REQUEST;return(l=r[u])!=null||(r[u]={}),r[u][c]=h,r},{});return Object.entries(i).reduce((r,[a,o])=>(r[a]=Qn(o,e),r),{})}function yh(n,e,t){return ne(n,Eh(e,t))}const xh="CMCD";function Sh(n,e={}){if(!n)return"";const t=Qn(n,e);return`${xh}=${encodeURIComponent(t)}`}const kr=/CMCD=[^&#]+/;function vh(n,e,t){const s=Sh(e,t);if(!s)return n;if(kr.test(n))return n.replace(kr,s);const i=n.includes("?")?"&":"?";return`${n}${i}${s}`}class Ah{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:ge.MANIFEST,su:!this.initialized})}catch(r){A.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const r=i.frag,a=this.hls.levels[r.level],o=this.getObjectType(r),l={d:r.duration*1e3,ot:o};(o===ge.VIDEO||o===ge.AUDIO||o==ge.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(i,l)}catch(r){A.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||gh(),this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Js.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ne(t,this.createData());const s=t.ot===ge.INIT||t.ot===ge.VIDEO||t.ot===ge.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((r,a)=>(i.includes(a)&&(r[a]=t[a]),r),{})),this.useHeaders?(e.headers||(e.headers={}),yh(e.headers,t)):e.url=vh(e.url,t)}getObjectType(e){const{type:t}=e;if(t==="subtitle")return ge.TIMED_TEXT;if(e.sn==="initSegment")return ge.INIT;if(t==="audio")return ge.AUDIO;if(t==="main")return this.hls.audioTracks.length?ge.VIDEO:ge.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===ge.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,a=r>-1?r+1:i.levels.length;s=i.levels.slice(0,a)}for(const r of s)r.bitrate>t&&(t=r.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,s=e===ge.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:J.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}}const Lh=3e5;class Rh{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=A.log.bind(A,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((s==null?void 0:s.action)===fe.SendAlternateToPenaltyBox&&s.flags===Ae.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this.pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&i?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&i&&(r=i.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==a),s.resolved||A.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>Lh&&delete s[r]});for(let r=0;r0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,pn(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(h=>h.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(h=>{const u=new se(h.attrs);u["PATHWAY-ID"]=a;const d=u.AUDIO&&`${u.AUDIO}_clone_${a}`,g=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),g&&(i[u.SUBTITLES]=g,u.SUBTITLES=g);const f=Jn(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new ft({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:f,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let T=1;T{this.log(`Loaded steering manifest: "${i}"`);const f=h.data;if(f.VERSION!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":T,"PATHWAY-PRIORITY":E}=f;if(m)try{this.uri=new self.URL(m,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||d.url),T&&this.clonePathways(T);const S={steeringManifest:f,url:i.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,S),E&&this.updatePathwayPriority(E)},onError:(h,u,d,g)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let f=this.timeToLoad*1e3;if(h.code===429){const m=this.loader;if(typeof(m==null?void 0:m.getResponseHeader)=="function"){const T=m.getResponseHeader("Retry-After");T&&(f=parseFloat(T)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,f)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Pr(n,e,t,s){n&&Object.keys(e).forEach(i=>{const r=n.filter(a=>a.groupId===i).map(a=>{const o=ne({},a);return o.details=void 0,o.attrs=new se(o.attrs),o.url=o.attrs.URI=Jn(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});n.push(...r)})}function Jn(n,e,t,s){const{HOST:i,PARAMS:r,[t]:a}=s;let o;e&&(o=a==null?void 0:a[e],o&&(n=o));const l=new self.URL(n);return i&&!o&&(l.host=i),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}const bh=/^age:\s*[\d.]+\s*$/im;class Zn{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new ds,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null,this.stats=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!this.stats.aborted)return r(s,t.url)}).catch(a=>(s.open("GET",t.url,!0),r(s,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{this.callbacks.onError({code:s.status,text:a.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&O(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=o?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(s.loaded=s.total=c,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first),!this.callbacks)return;const h=this.callbacks.onProgress;if(h&&h(s,e,l,t),!this.callbacks)return;const u={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(u,s,e,t)}else{const l=r.loadPolicy.errorRetry,c=s.retry,h={url:e.url,data:void 0,code:a};rs(l,c,!1,h)?this.retry(l):(A.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,s))}}}loadtimeout(){var e;const t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,s=this.stats.retry;if(rs(t,s,!0))this.retry(t);else{var i;A.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=hi(e,s.retry),s.retry++,A.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&bh.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function Ih(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Dh=/(\d+)-(\d+)\/(\d+)/;class Fr{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||kh,this.controller=new self.AbortController,this.stats=new ds}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=Ch(e,this.controller.signal),a=s.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&O(c)?c:h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(i,e,this.response)},t.timeout),self.fetch(this.request).then(u=>{this.response=this.loader=u;const d=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(i,e,this.response)},h-(d-i.loading.start)),!u.ok){const{status:g,statusText:f}=u;throw new Ph(f||"fetch, bad network response",g,u)}return i.loading.first=d,i.total=wh(u.headers)||i.total,a&&O(t.highWaterMark)?this.loadProgressively(u,i,e,t.highWaterMark,a):o?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{const d=this.response;if(!d)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const g=u[l];g&&(i.loaded=i.total=g);const f={url:d.url,data:u,code:d.status};a&&!O(t.highWaterMark)&&a(i,e,u,d),s.onSuccess(f,i,e,d)}).catch(u=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const d=u&&u.code||0,g=u?u.message:null;s.onError({code:d,text:g},e,u?u.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const a=new xn,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&r(t,s,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const h=c.value,u=h.length;return t.loaded+=u,u=i&&r(t,s,a.flush(),e)):r(t,s,h,e),l()}).catch(()=>Promise.reject());return l()}}function Ch(n,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ne({},n.headers))};return n.rangeEnd&&t.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),t}function _h(n){const e=Dh.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}function wh(n){const e=n.get("Content-Range");if(e){const s=_h(e);if(O(s))return s}const t=n.get("Content-Length");if(t)return parseInt(t)}function kh(n,e){return new self.Request(n.url,e)}class Ph extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const Fh=/\s/,Oh={newCue(n,e,t,s){const i=[];let r,a,o,l,c;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d=16?l--:l++;const g=Kn(c.trim()),f=Si(e,t,g);n!=null&&(u=n.cues)!=null&&u.getCueById(f)||(a=new h(e,t,g),a.id=f,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(a))}return n&&i.length&&(i.sort((d,g)=>d.line==="auto"||g.line==="auto"?0:d.line>8&&g.line>8?g.line-d.line:d.line-g.line),i.forEach(d=>dn(n,d))),i}},Mh={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},ea=ue(ue({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Zn,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:dl,bufferController:pc,capLevelController:vi,errorController:el,fpsController:Gc,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Qr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:Mh},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},Nh()),{},{subtitleStreamController:dc,subtitleTrackController:gc,timelineController:Bc,audioStreamController:hc,audioTrackController:uc,emeController:ct,cmcdController:Ah,contentSteeringController:Rh});function Nh(){return{cueHandler:Oh,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 Uh(n,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const t=ti(n),s=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(r=>{const a=`${r==="level"?"playlist":r}LoadPolicy`,o=e[a]===void 0,l=[];i.forEach(c=>{const h=`${r}Loading${c}`,u=e[h];if(u!==void 0&&o){l.push(h);const d=t[a].default;switch(e[a]={default:d},c){case"TimeOut":d.maxLoadTimeMs=u,d.maxTimeToFirstByteMs=u;break;case"MaxRetry":d.errorRetry.maxNumRetry=u,d.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":d.errorRetry.retryDelayMs=u,d.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=u,d.timeoutRetry.maxRetryDelayMs=u;break}}}),l.length&&A.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),ue(ue({},t),e)}function ti(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(ti):Object.keys(n).reduce((e,t)=>(e[t]=ti(n[t]),e),{}):n}function Bh(n){const e=n.loader;e!==Fr&&e!==Zn?(A.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):Ih()&&(n.loader=Fr,n.progressive=!0,n.enableSoftwareAES=!0,A.log("[config]: Progressive streaming enabled, using FetchLoader"))}let Ns;class $h extends ui{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},a={};let o=!1,l=!1,c=!1;t.levels.forEach(h=>{var u,d;const g=h.attrs;let{audioCodec:f,videoCodec:m}=h;((u=f)==null?void 0:u.indexOf("mp4a.40.34"))!==-1&&(Ns||(Ns=/chrome|firefox/i.test(navigator.userAgent)),Ns&&(h.audioCodec=f=void 0)),f&&(h.audioCodec=f=ts(f,s)),((d=m)==null?void 0:d.indexOf("avc1"))===0&&(m=h.videoCodec=Co(m));const{width:T,height:E,unknownCodecs:S}=h;if(o||(o=!!(T&&E)),l||(l=!!m),c||(c=!!f),S!=null&&S.length||f&&!vs(f,"audio",s)||m&&!vs(m,"video",s))return;const{CODECS:y,"FRAME-RATE":v,"HDCP-LEVEL":x,"PATHWAY-ID":b,RESOLUTION:R,"VIDEO-RANGE":C}=g,D=`${`${b||"."}-`}${h.bitrate}-${R}-${v}-${y}-${C}-${x}`;if(r[D])if(r[D].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const w=a[D]+=1;h.attrs["PATHWAY-ID"]=new Array(w+1).join(".");const V=new ft(h);r[D]=V,i.push(V)}else r[D].addGroupId("audio",g.AUDIO),r[D].addGroupId("text",g.SUBTITLES);else{const w=new ft(h);r[D]=w,a[D]=1,i.push(w)}}),this.filterAndSortMediaOptions(i,t,o,l,c)}filterAndSortMediaOptions(e,t,s,i,r){let a=[],o=[],l=e;if((s||i)&&r&&(l=l.filter(({videoCodec:f,videoRange:m,width:T,height:E})=>(!!f||!!(T&&E))&&Ko(m))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const f=new Error("no level with compatible codecs found in manifest");this.hls.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:I.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:f,reason:f.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:f}=this.hls.config;a=t.audioTracks.filter(m=>!m.audioCodec||vs(m.audioCodec,"audio",f)),Or(a)}t.subtitles&&(o=t.subtitles,Or(o));const c=l.slice(0);l.sort((f,m)=>{if(f.attrs["HDCP-LEVEL"]!==m.attrs["HDCP-LEVEL"])return(f.attrs["HDCP-LEVEL"]||"")>(m.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&f.height!==m.height)return f.height-m.height;if(f.frameRate!==m.frameRate)return f.frameRate-m.frameRate;if(f.videoRange!==m.videoRange)return ss.indexOf(f.videoRange)-ss.indexOf(m.videoRange);if(f.videoCodec!==m.videoCodec){const T=$i(f.videoCodec),E=$i(m.videoCodec);if(T!==E)return E-T}if(f.uri===m.uri&&f.codecSet!==m.codecSet){const T=es(f.codecSet),E=es(m.codecSet);if(T!==E)return E-T}return f.averageBitrate!==m.averageBitrate?f.averageBitrate-m.averageBitrate:0});let h=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let f=0;fT&&T===ea.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=E)}break}const d=r&&!i,g={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:!d&&a.some(f=>!!f.url)};this.hls.trigger(p.MANIFEST_PARSED,g),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(p.ERROR,{type:B.OTHER_ERROR,details:I.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&a.details&&i&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const h=this.switchParams(a.uri,i==null?void 0:i.details);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===Y.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===N.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,a=this._levels[i];if(!a){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}i===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(i,t,a.details)):(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){let i=s.uri;if(e)try{i=e.addDirectives(i)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const r=s.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${r?" Pathway "+r:""} ${i}`),this.clearTimer(),this.hls.trigger(p.LEVEL_LOADING,{url:i,level:t,pathwayId:s.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const s=this._levels.filter((i,r)=>r!==e?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(a=>a.level=-1)),!1));pn(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(p.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Or(n){const e={};n.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}class Gh{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=I.KEY_LOAD_ERROR,s,i,r){return new Ne({type:B.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:i}=e;for(let r=0;r{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,c))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((s=o)!=null&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((i=o)!=null&&i.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(r.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const i=this.emeController.loadKey(s);if(i)return(e.keyLoadPromise=i.then(r=>(e.mediaKeySessionContext=r,s))).catch(r=>{throw e.keyLoadPromise=null,r})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=s.keyLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,m)=>{const{frag:T,keyInfo:E,url:S}=f;if(!T.decryptdata||E!==this.keyUriToKeyInfo[S])return o(this.createKeyLoadError(T,I.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),m));E.decryptdata.key=T.decryptdata.key=new Uint8Array(d.data),T.keyLoader=null,E.loader=null,a({frag:T,keyInfo:E})},onError:(d,g,f,m)=>{this.resetLoader(g),o(this.createKeyLoadError(t,I.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),f,ue({url:l.url,data:void 0},d)))},onTimeout:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,I.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,I.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(l,h,u)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}function ta(){return self.SourceBuffer||self.WebKitSourceBuffer}function sa(){if(!Tt())return!1;const e=ta();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Kh(){if(!sa())return!1;const n=Tt();return typeof(n==null?void 0:n.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>n.isTypeSupported(bt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(bt(e,"audio"))))}function Vh(){var n;const e=ta();return typeof(e==null||(n=e.prototype)==null?void 0:n.changeType)=="function"}const Hh=250,jt=2,Wh=.1,Yh=.05;class jh{constructor(e,t,s,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=s,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:s,media:i,stalled:r}=this;if(i===null)return;const{currentTime:a,seeking:o}=i,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),r!==null){if(this.stallReported){const T=self.performance.now()-r;A.warn(`playback not stuck anymore @${a}, after ${Math.round(T)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l){this.stalled=null;return}if(i.paused&&!o||i.ended||i.playbackRate===0||!J.getBuffered(i).length){this.nudgeRetry=0;return}const h=J.bufferInfo(i,a,0),u=h.nextStart||0;if(o){const T=h.len>jt,E=!u||t&&t.start<=a||u-a>jt&&!this.fragmentTracker.getPartialFragment(a);if(T||E)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var d;if(!(h.len>0)&&!u)return;const E=Math.max(u,h.start||0)-a,S=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,v=(S==null||(d=S.details)==null?void 0:d.live)?S.details.targetduration*2:jt,x=this.fragmentTracker.getPartialFragment(a);if(E>0&&(E<=v||x)){i.paused||this._trySkipBufferHole(x);return}}const g=self.performance.now();if(r===null){this.stalled=g;return}const f=g-r;if(!o&&f>=Hh&&(this._reportStall(h),!this.media))return;const m=J.bufferInfo(i,a,s.maxBufferHole);this._tryFixBufferStall(m,f)}_tryFixBufferStall(e,t){const{config:s,fragmentTracker:i,media:r}=this;if(r===null)return;const a=r.currentTime,o=i.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>s.maxBufferHole||e.nextStart&&e.nextStart-as.highBufferWatchdogPeriod*1e3&&(A.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:s,stallReported:i}=this;if(!i&&s){this.stallReported=!0;const r=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(e)})`);A.warn(r.message),t.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:s,media:i}=this;if(i===null)return 0;const r=i.currentTime,a=J.bufferInfo(i,r,0),o=r0&&a.len<1&&i.readyState<3,h=o-r;if(h>0&&(l||c)){if(h>t.maxBufferHole){const{fragmentTracker:d}=this;let g=!1;if(r===0){const f=d.getAppendedFrag(0,N.MAIN);f&&o1?(i=0,this.bitrateTest=!0):i=s.firstAutoLevel),this.level=s.nextLoadLevel=i,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=_.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=_.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case _.WAITING_LEVEL:{const{levels:t,level:s}=this,i=t==null?void 0:t[s],r=i==null?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(r))break;this.state=_.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=_.IDLE;break}break}case _.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),s=this.retryDate;if(!s||t>=s||(e=this.media)!=null&&e.seeking){const{levels:i,level:r}=this,a=i==null?void 0:i[r];this.resetStartWhenNotLoaded(a||null),this.state=_.IDLE}}break}this.state===_.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this,{config:r,nextLoadLevel:a}=e;if(t===null||!i&&(this.startFragRequested||!r.startFragPrefetch)||this.altAudio&&this.audioOnly||!(s!=null&&s[a]))return;const o=s[a],l=this.getMainFwdBufferInfo();if(l===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(l,c)){const T={};this.altAudio&&(T.type="video"),this.hls.trigger(p.BUFFER_EOS,T),this.state=_.ENDED;return}e.loadLevel!==a&&e.manualLevel===-1&&this.log(`Adapting to level ${a} from level ${this.level}`),this.level=e.nextLoadLevel=a;const h=o.details;if(!h||this.state===_.WAITING_LEVEL||h.live&&this.levelLastLoaded!==o){this.level=a,this.state=_.WAITING_LEVEL;return}const u=l.len,d=this.getMaxBufferLength(o.maxBitrate);if(u>=d)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const g=this.backtrackFragment?this.backtrackFragment.start:l.end;let f=this.getNextFragment(g,h);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==he.OK){var m;const E=((m=this.backtrackFragment)!=null?m:f).sn-h.startSN,S=h.fragments[E-1];S&&f.cc===S.cc&&(f=S,this.fragmentTracker.removeFragment(S))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,g)){if(!f.gap){const E=this.audioOnly&&!this.altAudio?X.AUDIO:X.VIDEO,S=(E===X.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;S&&this.afterBufferFlushed(S,E,N.MAIN)}f=this.getNextFragmentLoopLoading(f,h,l,N.MAIN,d)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,o,g))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);this.fragCurrent=e,i===he.NOT_LOADED||i===he.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,s)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,N.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len{const a=r.audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=s&&i&&!Vh(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==_.IDLE)return;const i=s[t.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state=_.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i}=this,r=t.level,a=t.details,o=a.totalduration;if(!i){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=i[r],c=this.fragCurrent;c&&(this.state===_.FRAG_LOADING||this.state===_.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let h=0;if(a.live||(s=l.details)!=null&&s.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(p.LEVEL_UPDATED,{details:a,level:r}),this.state===_.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=_.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,h),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:s,part:i,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=a[s.level],l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const c=o.videoCodec,h=l.PTSKnown||!l.live,u=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),g=this.transmuxer=this.transmuxer||new Mn(this.hls,N.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,m=f!==-1,T=new di(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,m),E=this.initPTS[s.cc];g.push(r,u,d,c,s,i,l.totalduration,h,T,E)}onAudioTrackSwitching(e,t){const s=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;s&&(r.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),r.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=t.id,i=!!this.hls.audioTracks[s].url;if(i){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,a=!1;for(const o in s){const l=s[o];if(l.id==="main"){if(r=o,i=l,o==="video"){const c=s[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s&&s.type!==N.MAIN)return;if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===_.PARSED&&(this.state=_.IDLE);return}const r=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),s.sn!=="initSegment"&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}onError(e,t){var s;if(t.fatal){this.state=_.ERROR;return}switch(t.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(N.MAIN,t);break;case I.LEVEL_LOAD_ERROR:case I.LEVEL_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===_.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Y.LEVEL&&(this.state=_.IDLE);break;case I.BUFFER_APPEND_ERROR:case I.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===I.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case I.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!J.getBuffered(e).length){const s=this.state!==_.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,s)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=_.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==X.AUDIO||this.audioOnly&&!this.altAudio){const s=(t===X.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(s,t,N.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t0&&(a{const{hls:i}=this;if(!s||this.fragContextChanged(e))return;t.fragmentError=0,this.state=_.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=e.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(p.FRAG_LOADED,s),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const s="main",{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:h}=o,{video:u,text:d,id3:g,initSegment:f}=r,{details:m}=h,T=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=_.PARSING,f){if(f!=null&&f.tracks){const y=l.initSegment||l;this._bufferInitSegment(h,f.tracks,y,a),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:f.tracks})}const E=f.initPTS,S=f.timescale;O(E)&&(this.initPTS[l.cc]={baseTime:E,timescale:S},i.trigger(p.INIT_PTS_FOUND,{frag:l,id:s,initPTS:E,timescale:S}))}if(u&&m&&l.sn!=="initSegment"){const E=m.fragments[l.sn-1-m.startSN],S=l.sn===m.startSN,y=!E||l.cc>E.cc;if(r.independent!==!1){const{startPTS:v,endPTS:x,startDTS:b,endDTS:R}=u;if(c)c.elementaryStreams[u.type]={startPTS:v,endPTS:x,startDTS:b,endDTS:R};else if(u.firstKeyFrame&&u.independent&&a.id===1&&!y&&(this.couldBacktrack=!0),u.dropped&&u.independent){const C=this.getMainFwdBufferInfo(),k=(C?C.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:v;if(!S&&kjt&&(l.gap=!0);l.setElementaryStreamInfo(u.type,v,x,b,R),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(u,l,c,a,S||y)}else if(S||y)l.gap=!0;else{this.backtrack(l);return}}if(T){const{startPTS:E,endPTS:S,startDTS:y,endDTS:v}=T;c&&(c.elementaryStreams[X.AUDIO]={startPTS:E,endPTS:S,startDTS:y,endDTS:v}),l.setElementaryStreamInfo(X.AUDIO,E,S,y,v),this.bufferFragmentData(T,l,c,a)}if(m&&g!=null&&(t=g.samples)!=null&&t.length){const E={id:s,frag:l,details:m,samples:g.samples};i.trigger(p.FRAG_PARSING_METADATA,E)}if(m&&d){const E={id:s,frag:l,details:m,samples:d.samples};i.trigger(p.FRAG_PARSING_USERDATA,E)}}_bufferInitSegment(e,t,s,i){if(this.state!==_.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:r,video:a,audiovideo:o}=t;if(r){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),r.metadata.channelCount!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")),l&&l.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),r.levelCodec=l,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${r.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(p.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const h=t[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:h,frag:s,part:null,chunkMeta:i,parent:s.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,N.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=_.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(J.isBuffered(e,s)?t=this.getAppendedFrag(s):J.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!i||i.level!==r)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,s=this.currentFrag;if(s&&O(t)&&O(s.programDateTime)){const i=s.programDateTime+(t-s.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 Ve{static get version(){return"1.5.3"}static isMSESupported(){return sa()}static isSupported(){return Kh()}static getMediaSource(){return Tt()}static get Events(){return p}static get ErrorTypes(){return B}static get ErrorDetails(){return I}static get DefaultConfig(){return Ve.defaultConfig?Ve.defaultConfig:ea}static set DefaultConfig(e){Ve.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new yi,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,$a(e.debug||!1,"Hls instance");const t=this.config=Uh(Ve.DefaultConfig,e);this.userConfig=e,t.progressive&&Bh(t);const{abrController:s,bufferController:i,capLevelController:r,errorController:a,fpsController:o}=t,l=new a(this),c=this.abrController=new s(this),h=this.bufferController=new i(this),u=this.capLevelController=new r(this),d=new o(this),g=new Fo(this),f=new Bo(this),m=t.contentSteeringController,T=m?new m(this):null,E=this.levelController=new $h(this,T),S=new gl(this),y=new Gh(this.config),v=this.streamController=new zh(this,S,y);u.setStreamController(v),d.setStreamController(v);const x=[g,E,v];T&&x.splice(1,0,T),this.networkControllers=x;const b=[c,h,u,d,f,S];this.audioTrackController=this.createController(t.audioTrackController,x);const R=t.audioStreamController;R&&x.push(new R(this,S,y)),this.subtitleTrackController=this.createController(t.subtitleTrackController,x);const C=t.subtitleStreamController;C&&x.push(new C(this,S,y)),this.createController(t.timelineController,b),y.emeController=this.emeController=this.createController(t.emeController,b),this.cmcdController=this.createController(t.cmcdController,b),this.latencyController=this.createController($o,b),this.coreComponents=b,x.push(l);const k=l.onErrorOut;typeof k=="function"&&this.on(p.ERROR,k,l)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(A.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===p.ERROR;this.trigger(p.ERROR,{type:B.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){A.log("destroy"),this.trigger(p.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){A.log("attachMedia"),this._media=e,this.trigger(p.MEDIA_ATTACHING,{media:e})}detachMedia(){A.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,s=this.url,i=this.url=ai.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,A.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(p.MANIFEST_LOADING,{url:e})}startLoad(e=-1){A.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){A.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){A.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){A.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){A.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){A.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){A.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){A.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){A.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(A.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Go(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Ve.defaultConfig=void 0;function Mr(n,e,t){const s=n.slice();return s[13]=e[t].speaker,s[14]=e[t].text,s[15]=e[t].time,s[17]=t,s}function Xh(n){let e;return{c(){e=me("p"),e.textContent="Erro ao carregar transcrições"},m(t,s){ee(t,e,s)},p:oe,d(t){t&&Z(e)}}}function Qh(n){let e,t=zt(n[1]),s=[];for(let i=0;io.parentNode,S.anchor=o,ee(y,o,v),ee(y,l,v),ee(y,c,v),ee(y,h,v),Ee(h,u),ee(y,g,v),ee(y,f,v),Ee(f,m)},p(y,[v]){n=y,v&1&&t!==(t=n[0].title+"")&&Us(s,t),ya(S,n,v),v&1&&d!==(d=n[0].original_url)&&ie(h,"href",d),v&1&&T!==(T=n[0].audio_url)&&ie(f,"href",T),v&1&&E!==(E=n[0].title)&&ie(f,"download",E)},i:oe,o:oe,d(y){y&&(Z(e),Z(i),Z(r),Z(a),Z(o),Z(l),Z(c),Z(h),Z(g),Z(f)),S.block.d(y),S.token=null,S=null}}}function eu(n,e,t){let{params:s={}}=e,i={},r=[],a={},o=null;async function l(){const T=await fetch(`/debates/${s.slug}.json`);t(0,i=await T.json())}function c(){r.forEach(T=>{a[T.speaker]||t(2,a[T.speaker]=`hsl(${Math.floor(Math.random()*360)}, 70%, 60%)`,a)})}async function h(){const T=await fetch(`/debates/transcriptions/${s.slug}.json`);t(1,r=await T.json()),c()}async function u(){const T=document.getElementById("video"),E=`/debates/media/${s.slug}.m3u8`;if(console.log(E),Ve.isSupported()){const y=new Ve;y.loadSource(E),y.attachMedia(T)}else T.src=E;const S=document.querySelector(".chat-container");T.addEventListener("timeupdate",()=>{if(!S)return;const y=T.currentTime;t(3,o=r.findIndex((b,R)=>Ry)),o===-1&&t(3,o=r.length-1);const v=S.querySelectorAll(".message");v.forEach((b,R)=>{b.style.borderColor=R===o?"black":"",b.style.borderWidth=R===o?"2px":""});const x=v[o];x&&!T.paused&&(S.scrollTop=x.offsetTop-S.offsetTop-20)})}const d=T=>(T===0||r[T].speaker!==r[T-1].speaker&&(g=g==="right"?"left":"right"),g);let g="right";const f=T=>{document.getElementById("video").currentTime=parseFloat(T)};ua(async()=>{await l(),await u()});const m=T=>f(T);return n.$$set=T=>{"params"in T&&t(7,s=T.params)},[i,r,a,o,h,d,f,s,m]}class tu extends us{constructor(e){super(),hs(this,e,eu,Zh,It,{params:7})}}const su={"/debate/:slug":tu,"/":wa};function iu(n){let e,t,s,i;return e=new Da({props:{routes:su}}),{c(){At(e.$$.fragment),t=Ce(),s=me("small"),s.innerHTML='Contribui no GitHub'},m(r,a){ht(e,r,a),ee(r,t,a),ee(r,s,a),i=!0},p:oe,i(r){i||($e(e.$$.fragment,r),i=!0)},o(r){He(e.$$.fragment,r),i=!1},d(r){r&&(Z(t),Z(s)),ut(e,r)}}}class ru extends us{constructor(e){super(),hs(this,e,null,iu,It,{})}}new ru({target:document.body}); + } (data length: ${t&&t.byteLength})`),i.update(t)}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((t,s)=>{const i=Es(this.config),r=e.map(Oi).filter(a=>!!a&&i.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:a})=>{const o=Mi(a);o?t(o):s(new Error(`Unable to find format for key-system "${a}"`))}).catch(s)})}loadKey(e){const t=e.keyInfo.decryptdata,s=this.getKeyIdString(t),i=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);let r=this.keyIdToKeySessionPromise[s];return r||(r=this.keyIdToKeySessionPromise[s]=this.getKeySystemForKeyPromise(t).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:t});return this.generateRequestWithPreferredKeySession(l,"cenc",t.pssh,"playlist-key")}))),r.catch(a=>this.handleError(a))),r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof xe?this.hls.trigger(p.ERROR,e.data):this.hls.trigger(p.ERROR,{type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=Oi(e.keyFormat),r=i?[i]:Es(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Es(this.config)),e.length===0)throw new xe({type:B.KEY_SYSTEM_ERROR,details:I.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:t,initData:s}=e;if(this.debug(`"${e.type}" event: init data type: "${t}"`),s===null)return;let i,r;if(t==="sinf"&&this.config.drmSystems[te.FAIRPLAY]){const h=ae(new Uint8Array(s));try{const u=oi(JSON.parse(h).sinf),d=an(new Uint8Array(u));if(!d)return;i=d.subarray(8,24),r=te.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const h=Ao(s);if(h===null)return;h.version===0&&h.systemId===Xr.WIDEVINE&&h.data&&(i=h.data.subarray(8,24)),r=Xa(h.systemId)}if(!r||!i)return;const a=Ie.hexDump(i),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let c=o[a];for(let h=0;hthis.generateRequestWithPreferredKeySession(u,t,s,"encrypted-event-key-match"));break}}c||(c=o[a]=this.getKeySystemSelectionPromise([r]).then(({keySystem:h,mediaKeys:u})=>{var d;this.throwIfDestroyed();const g=new Rt("ISO-23001-7",a,(d=Mi(h))!=null?d:"");return g.pssh=new Uint8Array(s),g.keyId=i,this.attemptSetMediaKeys(h,u).then(()=>{this.throwIfDestroyed();const f=this.createMediaKeySessionContext({decryptdata:g,keySystem:h,mediaKeys:u});return this.generateRequestWithPreferredKeySession(f,t,s,"encrypted-event-no-match")})})),c.catch(h=>this.handleError(h))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,t){const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(t)});return this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r,a;const o=(r=this.config.drmSystems)==null||(a=r[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const f=o.call(this.hls,t,s,e);if(!f)throw new Error("Invalid response from configured generateRequest filter");t=f.initDataType,s=e.decryptdata.pssh=f.initData?new Uint8Array(f.initData):null}catch(f){var l;if(this.warn(f.message),(l=this.hls)!=null&&l.config.debug)throw f}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const c=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${i}": ${c} (init data type: ${t} length: ${s?s.byteLength:null})`);const h=new yi,u=e._onmessage=f=>{const m=e.mediaKeysSession;if(!m){h.emit("error",new Error("invalid state"));return}const{messageType:T,message:E}=f;this.log(`"${T}" message event for session "${m.sessionId}" message size: ${E.byteLength}`),T==="license-request"||T==="license-renewal"?this.renewLicense(e,E).catch(S=>{this.handleError(S),h.emit("error",S)}):T==="license-release"?e.keySystem===te.FAIRPLAY&&(this.updateKeySession(e,Ks("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${T}"`)},d=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){h.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const T=e.keyStatus;h.emit("keyStatus",T),T==="expired"&&(this.warn(`${e.keySystem} expired for key ${c}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",u),e.mediaKeysSession.addEventListener("keystatuseschange",d);const g=new Promise((f,m)=>{h.on("error",m),h.on("keyStatus",T=>{T.startsWith("usable")?f():T==="output-restricted"?m(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):T==="internal-error"?m(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${T}"`)):T==="expired"?m(new Error("key expired while generating request")):this.warn(`unhandled key status change "${T}"`)})});return e.mediaKeysSession.generateRequest(t,s).then(()=>{var f;this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${c}`)}).catch(f=>{throw new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_SESSION,error:f,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>g).catch(f=>{throw h.removeAllListeners(),this.removeSession(e),f}).then(()=>(h.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((t,s)=>{this.log(`key status change "${t}" for keyStatuses keyId: ${Ie.hexDump("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${Ie.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=t})}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:r},c=t.certLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,m)=>{a(d.data)},onError:(d,g,f,m)=>{o(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:ue({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,g,f)=>{o(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,g,f)=>{o(new Error("aborted"))}};i.load(l,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s==null?void 0:s.byteLength}) on "${t}"`),i(e)}).catch(a=>{r(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:i,fatal:!0},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u in key message");return Ks(atob(c))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const c=this.config.licenseResponseCallback;if(c)try{l=c.call(this.hls,o,a,e)}catch(h){this.error(h)}i(l)}else{const l=s.errorRetry,c=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)r(new xe({type:B.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const h=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==te.PLAYREADY&&(c=this.unpackPlayReadyKeyMessage(l,c)),l.send(c)})})}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,s.addEventListener("encrypted",this.onMediaEncrypted),s.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,t=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={},Rt.clearKeyUriToKeyIdMap();const s=t.length;ct.CDMCleanupPromise=Promise.all(t.map(i=>this.removeSession(i)).concat(e==null?void 0:e.setMediaKeys(null).catch(i=>{this.log(`Could not clear media keys: ${i}`)}))).then(()=>{s&&(this.log("finished closing key sessions and clearing media keys"),t.length=0)}).catch(i=>{this.log(`Could not close sessions and clear media keys: ${i}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s}=e;if(t){this.log(`Remove licenses and keys and close session ${t.sessionId}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);return i>-1&&this.mediaKeySessions.splice(i,1),t.remove().catch(r=>{this.log(`Could not remove session: ${r}`)}).then(()=>t.close()).catch(r=>{this.log(`Could not close session: ${r}`)})}}}ct.CDMCleanupPromise=void 0;class xe extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}var ge;(function(n){n.MANIFEST="m",n.AUDIO="a",n.VIDEO="v",n.MUXED="av",n.INIT="i",n.CAPTION="c",n.TIMED_TEXT="tt",n.KEY="k",n.OTHER="o"})(ge||(ge={}));var Js;(function(n){n.DASH="d",n.HLS="h",n.SMOOTH="s",n.OTHER="o"})(Js||(Js={}));var qe;(function(n){n.OBJECT="CMCD-Object",n.REQUEST="CMCD-Request",n.SESSION="CMCD-Session",n.STATUS="CMCD-Status"})(qe||(qe={}));const Kc={[qe.OBJECT]:["br","d","ot","tb"],[qe.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[qe.SESSION]:["cid","pr","sf","sid","st","v"],[qe.STATUS]:["bs","rtp"]};class mt{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(s=>s instanceof mt?s:new mt(s))),this.value=e,this.params=t}}class jn{constructor(e){this.description=void 0,this.description=e}}const Vc="Dict";function Hc(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":typeof n=="object"?JSON.stringify(n):String(n)}function Wc(n,e,t,s){return new Error(`failed to ${n} "${Hc(e)}" as ${t}`,{cause:s})}const _r="Bare Item",Yc="Boolean",jc="Byte Sequence",qc="Decimal",zc="Integer";function Xc(n){return n<-999999999999999||99999999999999912)throw Fe(n,qc);const t=e.toString();return t.includes(".")?t:`${t}.0`}const nh="String";function ah(n){if(Qc.test(n))throw Fe(n,nh);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function oh(n){return n.description||n.toString().slice(7,-1)}function wr(n){const e=oh(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Fe(e,Jc);return e}function Zs(n){switch(typeof n){case"number":if(!O(n))throw Fe(n,_r);return Number.isInteger(n)?qn(n):rh(n);case"string":return ah(n);case"symbol":return wr(n);case"boolean":return eh(n);case"object":if(n instanceof Date)return ih(n);if(n instanceof Uint8Array)return sh(n);if(n instanceof jn)return wr(n);default:throw Fe(n,_r)}}function ei(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw Fe(n,Zc);return n}function Ai(n){return n==null?"":Object.entries(n).map(([e,t])=>t===!0?`;${ei(e)}`:`;${ei(e)}=${Zs(t)}`).join("")}function Xn(n){return n instanceof mt?`${Zs(n.value)}${Ai(n.params)}`:Zs(n)}function lh(n){return`(${n.value.map(Xn).join(" ")})${Ai(n.params)}`}function ch(n,e={whitespace:!0}){if(typeof n!="object")throw Fe(n,Vc);const t=n instanceof Map?n.entries():Object.entries(n),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof mt||(r=new mt(r));let a=ei(i);return r.value===!0?a+=Ai(r.params):(a+="=",Array.isArray(r.value)?a+=lh(r):a+=Xn(r)),a}).join(`,${s}`)}function hh(n,e){return ch(n,e)}const uh=n=>n==="ot"||n==="sf"||n==="st",dh=n=>typeof n=="number"?O(n):n!=null&&n!==""&&n!==!1;function fh(n,e){const t=new URL(n),s=new URL(e);if(t.origin!==s.origin)return n;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")}function gh(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}const Yt=n=>Math.round(n),mh=(n,e)=>(e!=null&&e.baseUrl&&(n=fh(n,e.baseUrl)),encodeURIComponent(n)),Bt=n=>Yt(n/100)*100,ph={br:Yt,d:Yt,bl:Bt,dl:Bt,mtp:Bt,nor:mh,rtp:Bt,tb:Yt};function Th(n,e){const t={};if(n==null||typeof n!="object")return t;const s=Object.keys(n).sort(),i=ne({},ph,e==null?void 0:e.formatters),r=e==null?void 0:e.filter;return s.forEach(a=>{if(r!=null&&r(a))return;let o=n[a];const l=i[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||dh(o)&&(uh(a)&&typeof o=="string"&&(o=new jn(o)),t[a]=o))}),t}function Qn(n,e={}){return n?hh(Th(n,e),ne({whitespace:!1},e)):""}function Eh(n,e={}){if(!n)return{};const t=Object.entries(n),s=Object.entries(Kc).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),i=t.reduce((r,a)=>{var o,l;const[c,h]=a,u=((o=s.find(d=>d[1].includes(c)))==null?void 0:o[0])||qe.REQUEST;return(l=r[u])!=null||(r[u]={}),r[u][c]=h,r},{});return Object.entries(i).reduce((r,[a,o])=>(r[a]=Qn(o,e),r),{})}function yh(n,e,t){return ne(n,Eh(e,t))}const xh="CMCD";function Sh(n,e={}){if(!n)return"";const t=Qn(n,e);return`${xh}=${encodeURIComponent(t)}`}const kr=/CMCD=[^&#]+/;function vh(n,e,t){const s=Sh(e,t);if(!s)return n;if(kr.test(n))return n.replace(kr,s);const i=n.includes("?")?"&":"?";return`${n}${i}${s}`}class Ah{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:ge.MANIFEST,su:!this.initialized})}catch(r){A.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const r=i.frag,a=this.hls.levels[r.level],o=this.getObjectType(r),l={d:r.duration*1e3,ot:o};(o===ge.VIDEO||o===ge.AUDIO||o==ge.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(i,l)}catch(r){A.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||gh(),this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Js.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ne(t,this.createData());const s=t.ot===ge.INIT||t.ot===ge.VIDEO||t.ot===ge.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((r,a)=>(i.includes(a)&&(r[a]=t[a]),r),{})),this.useHeaders?(e.headers||(e.headers={}),yh(e.headers,t)):e.url=vh(e.url,t)}getObjectType(e){const{type:t}=e;if(t==="subtitle")return ge.TIMED_TEXT;if(e.sn==="initSegment")return ge.INIT;if(t==="audio")return ge.AUDIO;if(t==="main")return this.hls.audioTracks.length?ge.VIDEO:ge.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===ge.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,a=r>-1?r+1:i.levels.length;s=i.levels.slice(0,a)}for(const r of s)r.bitrate>t&&(t=r.bitrate);return t>0?t:NaN}getBufferLength(e){const t=this.hls.media,s=e===ge.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:J.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}}const Lh=3e5;class Rh{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=A.log.bind(A,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((s==null?void 0:s.action)===fe.SendAlternateToPenaltyBox&&s.flags===Ae.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this.pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&i?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&i&&(r=i.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==a),s.resolved||A.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${JSON.stringify(r)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length?(this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>Lh&&delete s[r]});for(let r=0;r0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,pn(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(h=>h.pathwayId===a))return;const c=this.getLevelsForPathway(o).map(h=>{const u=new se(h.attrs);u["PATHWAY-ID"]=a;const d=u.AUDIO&&`${u.AUDIO}_clone_${a}`,g=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),g&&(i[u.SUBTITLES]=g,u.SUBTITLES=g);const f=Jn(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new ft({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:f,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let T=1;T{this.log(`Loaded steering manifest: "${i}"`);const f=h.data;if(f.VERSION!==1){this.log(`Steering VERSION ${f.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=f.TTL;const{"RELOAD-URI":m,"PATHWAY-CLONES":T,"PATHWAY-PRIORITY":E}=f;if(m)try{this.uri=new self.URL(m,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||d.url),T&&this.clonePathways(T);const S={steeringManifest:f,url:i.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,S),E&&this.updatePathwayPriority(E)},onError:(h,u,d,g)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let f=this.timeToLoad*1e3;if(h.code===429){const m=this.loader;if(typeof(m==null?void 0:m.getResponseHeader)=="function"){const T=m.getResponseHeader("Retry-After");T&&(f=parseFloat(T)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,f)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Pr(n,e,t,s){n&&Object.keys(e).forEach(i=>{const r=n.filter(a=>a.groupId===i).map(a=>{const o=ne({},a);return o.details=void 0,o.attrs=new se(o.attrs),o.url=o.attrs.URI=Jn(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});n.push(...r)})}function Jn(n,e,t,s){const{HOST:i,PARAMS:r,[t]:a}=s;let o;e&&(o=a==null?void 0:a[e],o&&(n=o));const l=new self.URL(n);return i&&!o&&(l.host=i),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}const bh=/^age:\s*[\d.]+\s*$/im;class Zn{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new ds,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null,this.stats=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!this.stats.aborted)return r(s,t.url)}).catch(a=>(s.open("GET",t.url,!0),r(s,t.url))).then(()=>{this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{this.callbacks.onError({code:s.status,text:a.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&O(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const a=t.status,o=t.responseType!=="text";if(a>=200&&a<300&&(o&&t.response||t.responseText!==null)){s.loading.end=Math.max(self.performance.now(),s.loading.first);const l=o?t.response:t.responseText,c=t.responseType==="arraybuffer"?l.byteLength:l.length;if(s.loaded=s.total=c,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first),!this.callbacks)return;const h=this.callbacks.onProgress;if(h&&h(s,e,l,t),!this.callbacks)return;const u={url:t.responseURL,data:l,code:a};this.callbacks.onSuccess(u,s,e,t)}else{const l=r.loadPolicy.errorRetry,c=s.retry,h={url:e.url,data:void 0,code:a};rs(l,c,!1,h)?this.retry(l):(A.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:t.statusText},e,t,s))}}}loadtimeout(){var e;const t=(e=this.config)==null?void 0:e.loadPolicy.timeoutRetry,s=this.stats.retry;if(rs(t,s,!0))this.retry(t);else{var i;A.warn(`timeout while loading ${(i=this.context)==null?void 0:i.url}`);const r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=hi(e,s.retry),s.retry++,A.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&bh.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function Ih(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Dh=/(\d+)-(\d+)\/(\d+)/;class Fr{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||kh,this.controller=new self.AbortController,this.stats=new ds}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=Ch(e,this.controller.signal),a=s.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:h}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&O(c)?c:h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(i,e,this.response)},t.timeout),self.fetch(this.request).then(u=>{this.response=this.loader=u;const d=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=h,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),s.onTimeout(i,e,this.response)},h-(d-i.loading.start)),!u.ok){const{status:g,statusText:f}=u;throw new Ph(f||"fetch, bad network response",g,u)}return i.loading.first=d,i.total=wh(u.headers)||i.total,a&&O(t.highWaterMark)?this.loadProgressively(u,i,e,t.highWaterMark,a):o?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{const d=this.response;if(!d)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const g=u[l];g&&(i.loaded=i.total=g);const f={url:d.url,data:u,code:d.status};a&&!O(t.highWaterMark)&&a(i,e,u,d),s.onSuccess(f,i,e,d)}).catch(u=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const d=u&&u.code||0,g=u?u.message:null;s.onError({code:d,text:g},e,u?u.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const a=new xn,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&r(t,s,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const h=c.value,u=h.length;return t.loaded+=u,u=i&&r(t,s,a.flush(),e)):r(t,s,h,e),l()}).catch(()=>Promise.reject());return l()}}function Ch(n,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ne({},n.headers))};return n.rangeEnd&&t.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),t}function _h(n){const e=Dh.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}function wh(n){const e=n.get("Content-Range");if(e){const s=_h(e);if(O(s))return s}const t=n.get("Content-Length");if(t)return parseInt(t)}function kh(n,e){return new self.Request(n.url,e)}class Ph extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const Fh=/\s/,Oh={newCue(n,e,t,s){const i=[];let r,a,o,l,c;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d=16?l--:l++;const g=Kn(c.trim()),f=Si(e,t,g);n!=null&&(u=n.cues)!=null&&u.getCueById(f)||(a=new h(e,t,g),a.id=f,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(a))}return n&&i.length&&(i.sort((d,g)=>d.line==="auto"||g.line==="auto"?0:d.line>8&&g.line>8?g.line-d.line:d.line-g.line),i.forEach(d=>dn(n,d))),i}},Mh={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},ea=ue(ue({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Zn,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:dl,bufferController:pc,capLevelController:vi,errorController:el,fpsController:Gc,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Qr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:Mh},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},Nh()),{},{subtitleStreamController:dc,subtitleTrackController:gc,timelineController:Bc,audioStreamController:hc,audioTrackController:uc,emeController:ct,cmcdController:Ah,contentSteeringController:Rh});function Nh(){return{cueHandler:Oh,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 Uh(n,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const t=ti(n),s=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(r=>{const a=`${r==="level"?"playlist":r}LoadPolicy`,o=e[a]===void 0,l=[];i.forEach(c=>{const h=`${r}Loading${c}`,u=e[h];if(u!==void 0&&o){l.push(h);const d=t[a].default;switch(e[a]={default:d},c){case"TimeOut":d.maxLoadTimeMs=u,d.maxTimeToFirstByteMs=u;break;case"MaxRetry":d.errorRetry.maxNumRetry=u,d.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":d.errorRetry.retryDelayMs=u,d.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":d.errorRetry.maxRetryDelayMs=u,d.timeoutRetry.maxRetryDelayMs=u;break}}}),l.length&&A.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),ue(ue({},t),e)}function ti(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(ti):Object.keys(n).reduce((e,t)=>(e[t]=ti(n[t]),e),{}):n}function Bh(n){const e=n.loader;e!==Fr&&e!==Zn?(A.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):Ih()&&(n.loader=Fr,n.progressive=!0,n.enableSoftwareAES=!0,A.log("[config]: Progressive streaming enabled, using FetchLoader"))}let Ns;class $h extends ui{constructor(e,t){super(e,"[level-controller]"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},a={};let o=!1,l=!1,c=!1;t.levels.forEach(h=>{var u,d;const g=h.attrs;let{audioCodec:f,videoCodec:m}=h;((u=f)==null?void 0:u.indexOf("mp4a.40.34"))!==-1&&(Ns||(Ns=/chrome|firefox/i.test(navigator.userAgent)),Ns&&(h.audioCodec=f=void 0)),f&&(h.audioCodec=f=ts(f,s)),((d=m)==null?void 0:d.indexOf("avc1"))===0&&(m=h.videoCodec=Co(m));const{width:T,height:E,unknownCodecs:S}=h;if(o||(o=!!(T&&E)),l||(l=!!m),c||(c=!!f),S!=null&&S.length||f&&!vs(f,"audio",s)||m&&!vs(m,"video",s))return;const{CODECS:y,"FRAME-RATE":v,"HDCP-LEVEL":x,"PATHWAY-ID":b,RESOLUTION:R,"VIDEO-RANGE":C}=g,D=`${`${b||"."}-`}${h.bitrate}-${R}-${v}-${y}-${C}-${x}`;if(r[D])if(r[D].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const w=a[D]+=1;h.attrs["PATHWAY-ID"]=new Array(w+1).join(".");const V=new ft(h);r[D]=V,i.push(V)}else r[D].addGroupId("audio",g.AUDIO),r[D].addGroupId("text",g.SUBTITLES);else{const w=new ft(h);r[D]=w,a[D]=1,i.push(w)}}),this.filterAndSortMediaOptions(i,t,o,l,c)}filterAndSortMediaOptions(e,t,s,i,r){let a=[],o=[],l=e;if((s||i)&&r&&(l=l.filter(({videoCodec:f,videoRange:m,width:T,height:E})=>(!!f||!!(T&&E))&&Ko(m))),l.length===0){Promise.resolve().then(()=>{if(this.hls){t.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(t.levels[0].attrs)}`);const f=new Error("no level with compatible codecs found in manifest");this.hls.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:I.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:f,reason:f.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:f}=this.hls.config;a=t.audioTracks.filter(m=>!m.audioCodec||vs(m.audioCodec,"audio",f)),Or(a)}t.subtitles&&(o=t.subtitles,Or(o));const c=l.slice(0);l.sort((f,m)=>{if(f.attrs["HDCP-LEVEL"]!==m.attrs["HDCP-LEVEL"])return(f.attrs["HDCP-LEVEL"]||"")>(m.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&f.height!==m.height)return f.height-m.height;if(f.frameRate!==m.frameRate)return f.frameRate-m.frameRate;if(f.videoRange!==m.videoRange)return ss.indexOf(f.videoRange)-ss.indexOf(m.videoRange);if(f.videoCodec!==m.videoCodec){const T=$i(f.videoCodec),E=$i(m.videoCodec);if(T!==E)return E-T}if(f.uri===m.uri&&f.codecSet!==m.codecSet){const T=es(f.codecSet),E=es(m.codecSet);if(T!==E)return E-T}return f.averageBitrate!==m.averageBitrate?f.averageBitrate-m.averageBitrate:0});let h=c[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==c.length)){for(let f=0;fT&&T===ea.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=E)}break}const d=r&&!i,g={levels:l,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:!d&&a.some(f=>!!f.url)};this.hls.trigger(p.MANIFEST_PARSED,g),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(p.ERROR,{type:B.OTHER_ERROR,details:I.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&a.details&&i&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,l);const c=a.details;if(!c||c.live){const h=this.switchParams(a.uri,i==null?void 0:i.details);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}onError(e,t){t.fatal||!t.context||t.context.type===Y.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===N.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,a=this._levels[i];if(!a){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}i===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(i,t,a.details)):(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const t=this.currentLevelIndex,s=this.currentLevel;if(s&&this.shouldLoadPlaylist(s)){let i=s.uri;if(e)try{i=e.addDirectives(i)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const r=s.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${r?" Pathway "+r:""} ${i}`),this.clearTimer(),this.hls.trigger(p.LEVEL_LOADING,{url:i,level:t,pathwayId:s.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;const s=this._levels.filter((i,r)=>r!==e?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(a=>a.level=-1)),!1));pn(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(p.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function Or(n){const e={};n.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}class Gh{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const t=this.keyUriToKeyInfo[e].loader;t&&t.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,t=I.KEY_LOAD_ERROR,s,i,r){return new Ne({type:B.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:i}=e;for(let r=0;r{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const c=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,c))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((s=o)!=null&&s.decryptdata.key)return r.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((i=o)!=null&&i.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(c=>(r.key=c.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,I.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const i=this.emeController.loadKey(s);if(i)return(e.keyLoadPromise=i.then(r=>(e.mediaKeySessionContext=r,s))).catch(r=>{throw e.keyLoadPromise=null,r})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},c=s.keyLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,g,f,m)=>{const{frag:T,keyInfo:E,url:S}=f;if(!T.decryptdata||E!==this.keyUriToKeyInfo[S])return o(this.createKeyLoadError(T,I.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),m));E.decryptdata.key=T.decryptdata.key=new Uint8Array(d.data),T.keyLoader=null,E.loader=null,a({frag:T,keyInfo:E})},onError:(d,g,f,m)=>{this.resetLoader(g),o(this.createKeyLoadError(t,I.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),f,ue({url:l.url,data:void 0},d)))},onTimeout:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,I.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,I.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(l,h,u)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null),delete this.keyUriToKeyInfo[i],r&&r.destroy()}}function ta(){return self.SourceBuffer||self.WebKitSourceBuffer}function sa(){if(!Tt())return!1;const e=ta();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Kh(){if(!sa())return!1;const n=Tt();return typeof(n==null?void 0:n.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>n.isTypeSupported(bt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(bt(e,"audio"))))}function Vh(){var n;const e=ta();return typeof(e==null||(n=e.prototype)==null?void 0:n.changeType)=="function"}const Hh=250,jt=2,Wh=.1,Yh=.05;class jh{constructor(e,t,s,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=t,this.fragmentTracker=s,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,t){const{config:s,media:i,stalled:r}=this;if(i===null)return;const{currentTime:a,seeking:o}=i,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),r!==null){if(this.stallReported){const T=self.performance.now()-r;A.warn(`playback not stuck anymore @${a}, after ${Math.round(T)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l){this.stalled=null;return}if(i.paused&&!o||i.ended||i.playbackRate===0||!J.getBuffered(i).length){this.nudgeRetry=0;return}const h=J.bufferInfo(i,a,0),u=h.nextStart||0;if(o){const T=h.len>jt,E=!u||t&&t.start<=a||u-a>jt&&!this.fragmentTracker.getPartialFragment(a);if(T||E)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var d;if(!(h.len>0)&&!u)return;const E=Math.max(u,h.start||0)-a,S=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,v=(S==null||(d=S.details)==null?void 0:d.live)?S.details.targetduration*2:jt,x=this.fragmentTracker.getPartialFragment(a);if(E>0&&(E<=v||x)){i.paused||this._trySkipBufferHole(x);return}}const g=self.performance.now();if(r===null){this.stalled=g;return}const f=g-r;if(!o&&f>=Hh&&(this._reportStall(h),!this.media))return;const m=J.bufferInfo(i,a,s.maxBufferHole);this._tryFixBufferStall(m,f)}_tryFixBufferStall(e,t){const{config:s,fragmentTracker:i,media:r}=this;if(r===null)return;const a=r.currentTime,o=i.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>s.maxBufferHole||e.nextStart&&e.nextStart-as.highBufferWatchdogPeriod*1e3&&(A.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:t,media:s,stallReported:i}=this;if(!i&&s){this.stallReported=!0;const r=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${JSON.stringify(e)})`);A.warn(r.message),t.trigger(p.ERROR,{type:B.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len})}}_trySkipBufferHole(e){const{config:t,hls:s,media:i}=this;if(i===null)return 0;const r=i.currentTime,a=J.bufferInfo(i,r,0),o=r0&&a.len<1&&i.readyState<3,h=o-r;if(h>0&&(l||c)){if(h>t.maxBufferHole){const{fragmentTracker:d}=this;let g=!1;if(r===0){const f=d.getAppendedFrag(0,N.MAIN);f&&o1?(i=0,this.bitrateTest=!0):i=s.firstAutoLevel),this.level=s.nextLoadLevel=i,this.loadedmetadata=!1}t>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t),this.state=_.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=_.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case _.WAITING_LEVEL:{const{levels:t,level:s}=this,i=t==null?void 0:t[s],r=i==null?void 0:i.details;if(r&&(!r.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(r))break;this.state=_.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=_.IDLE;break}break}case _.FRAG_LOADING_WAITING_RETRY:{var e;const t=self.performance.now(),s=this.retryDate;if(!s||t>=s||(e=this.media)!=null&&e.seeking){const{levels:i,level:r}=this,a=i==null?void 0:i[r];this.resetStartWhenNotLoaded(a||null),this.state=_.IDLE}}break}this.state===_.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this,{config:r,nextLoadLevel:a}=e;if(t===null||!i&&(this.startFragRequested||!r.startFragPrefetch)||this.altAudio&&this.audioOnly||!(s!=null&&s[a]))return;const o=s[a],l=this.getMainFwdBufferInfo();if(l===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(l,c)){const T={};this.altAudio&&(T.type="video"),this.hls.trigger(p.BUFFER_EOS,T),this.state=_.ENDED;return}e.loadLevel!==a&&e.manualLevel===-1&&this.log(`Adapting to level ${a} from level ${this.level}`),this.level=e.nextLoadLevel=a;const h=o.details;if(!h||this.state===_.WAITING_LEVEL||h.live&&this.levelLastLoaded!==o){this.level=a,this.state=_.WAITING_LEVEL;return}const u=l.len,d=this.getMaxBufferLength(o.maxBitrate);if(u>=d)return;this.backtrackFragment&&this.backtrackFragment.start>l.end&&(this.backtrackFragment=null);const g=this.backtrackFragment?this.backtrackFragment.start:l.end;let f=this.getNextFragment(g,h);if(this.couldBacktrack&&!this.fragPrevious&&f&&f.sn!=="initSegment"&&this.fragmentTracker.getState(f)!==he.OK){var m;const E=((m=this.backtrackFragment)!=null?m:f).sn-h.startSN,S=h.fragments[E-1];S&&f.cc===S.cc&&(f=S,this.fragmentTracker.removeFragment(S))}else this.backtrackFragment&&l.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,g)){if(!f.gap){const E=this.audioOnly&&!this.altAudio?X.AUDIO:X.VIDEO,S=(E===X.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;S&&this.afterBufferFlushed(S,E,N.MAIN)}f=this.getNextFragmentLoopLoading(f,h,l,N.MAIN,d)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,o,g))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);this.fragCurrent=e,i===he.NOT_LOADED||i===he.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,t):this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):(this.startFragRequested=!0,super.loadFragment(e,t,s)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,N.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len{const a=r.audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=s&&i&&!Vh(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==_.IDLE)return;const i=s[t.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state=_.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i}=this,r=t.level,a=t.details,o=a.totalduration;if(!i){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=i[r],c=this.fragCurrent;c&&(this.state===_.FRAG_LOADING||this.state===_.FRAG_LOADING_WAITING_RETRY)&&c.level!==t.level&&c.loader&&this.abortCurrentFrag();let h=0;if(a.live||(s=l.details)!=null&&s.live){var u;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;h=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(p.LEVEL_UPDATED,{details:a,level:r}),this.state===_.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=_.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,h),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:s,part:i,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=a[s.level],l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const c=o.videoCodec,h=l.PTSKnown||!l.live,u=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),g=this.transmuxer=this.transmuxer||new Mn(this.hls,N.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,m=f!==-1,T=new di(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,m),E=this.initPTS[s.cc];g.push(r,u,d,c,s,i,l.totalduration,h,T,E)}onAudioTrackSwitching(e,t){const s=this.altAudio;if(!!!t.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;s&&(r.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),r.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=t.id,i=!!this.hls.audioTracks[s].url;if(i){const r=this.videoBuffer;r&&this.mediaBuffer!==r&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=r)}this.altAudio=i,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,a=!1;for(const o in s){const l=s[o];if(l.id==="main"){if(r=o,i=l,o==="video"){const c=s[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s&&s.type!==N.MAIN)return;if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===_.PARSED&&(this.state=_.IDLE);return}const r=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*r.total/(r.buffering.end-r.loading.first)),s.sn!=="initSegment"&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}onError(e,t){var s;if(t.fatal){this.state=_.ERROR;return}switch(t.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(N.MAIN,t);break;case I.LEVEL_LOAD_ERROR:case I.LEVEL_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===_.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Y.LEVEL&&(this.state=_.IDLE);break;case I.BUFFER_APPEND_ERROR:case I.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===I.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case I.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!J.getBuffered(e).length){const s=this.state!==_.IDLE?this.fragCurrent:null;t.poll(this.lastCurrentTime,s)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=_.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==X.AUDIO||this.audioOnly&&!this.altAudio){const s=(t===X.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(s,t,N.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t0&&(a{const{hls:i}=this;if(!s||this.fragContextChanged(e))return;t.fragmentError=0,this.state=_.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=e.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(p.FRAG_LOADED,s),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const s="main",{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:c,level:h}=o,{video:u,text:d,id3:g,initSegment:f}=r,{details:m}=h,T=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=_.PARSING,f){if(f!=null&&f.tracks){const y=l.initSegment||l;this._bufferInitSegment(h,f.tracks,y,a),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:f.tracks})}const E=f.initPTS,S=f.timescale;O(E)&&(this.initPTS[l.cc]={baseTime:E,timescale:S},i.trigger(p.INIT_PTS_FOUND,{frag:l,id:s,initPTS:E,timescale:S}))}if(u&&m&&l.sn!=="initSegment"){const E=m.fragments[l.sn-1-m.startSN],S=l.sn===m.startSN,y=!E||l.cc>E.cc;if(r.independent!==!1){const{startPTS:v,endPTS:x,startDTS:b,endDTS:R}=u;if(c)c.elementaryStreams[u.type]={startPTS:v,endPTS:x,startDTS:b,endDTS:R};else if(u.firstKeyFrame&&u.independent&&a.id===1&&!y&&(this.couldBacktrack=!0),u.dropped&&u.independent){const C=this.getMainFwdBufferInfo(),k=(C?C.end:this.getLoadPosition())+this.config.maxBufferHole,D=u.firstKeyFramePTS?u.firstKeyFramePTS:v;if(!S&&kjt&&(l.gap=!0);l.setElementaryStreamInfo(u.type,v,x,b,R),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(u,l,c,a,S||y)}else if(S||y)l.gap=!0;else{this.backtrack(l);return}}if(T){const{startPTS:E,endPTS:S,startDTS:y,endDTS:v}=T;c&&(c.elementaryStreams[X.AUDIO]={startPTS:E,endPTS:S,startDTS:y,endDTS:v}),l.setElementaryStreamInfo(X.AUDIO,E,S,y,v),this.bufferFragmentData(T,l,c,a)}if(m&&g!=null&&(t=g.samples)!=null&&t.length){const E={id:s,frag:l,details:m,samples:g.samples};i.trigger(p.FRAG_PARSING_METADATA,E)}if(m&&d){const E={id:s,frag:l,details:m,samples:d.samples};i.trigger(p.FRAG_PARSING_USERDATA,E)}}_bufferInitSegment(e,t,s,i){if(this.state!==_.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&delete t.audio;const{audio:r,video:a,audiovideo:o}=t;if(r){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();this.audioCodecSwitch&&(l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5"),r.metadata.channelCount!==1&&c.indexOf("firefox")===-1&&(l="mp4a.40.5")),l&&l.indexOf("mp4a.40.5")!==-1&&c.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),r.levelCodec=l,r.id="main",this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${r.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(p.BUFFER_CODECS,t),Object.keys(t).forEach(l=>{const h=t[l].initSegment;h!=null&&h.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:l,data:h,frag:s,part:null,chunkMeta:i,parent:s.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,N.MAIN)}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=_.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(J.isBuffered(e,s)?t=this.getAppendedFrag(s):J.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(p.FRAG_CHANGED,{frag:t}),(!i||i.level!==r)&&this.hls.trigger(p.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const t=e.currentTime,s=this.currentFrag;if(s&&O(t)&&O(s.programDateTime)){const i=s.programDateTime+(t-s.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 Ve{static get version(){return"1.5.3"}static isMSESupported(){return sa()}static isSupported(){return Kh()}static getMediaSource(){return Tt()}static get Events(){return p}static get ErrorTypes(){return B}static get ErrorDetails(){return I}static get DefaultConfig(){return Ve.defaultConfig?Ve.defaultConfig:ea}static set DefaultConfig(e){Ve.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new yi,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,$a(e.debug||!1,"Hls instance");const t=this.config=Uh(Ve.DefaultConfig,e);this.userConfig=e,t.progressive&&Bh(t);const{abrController:s,bufferController:i,capLevelController:r,errorController:a,fpsController:o}=t,l=new a(this),c=this.abrController=new s(this),h=this.bufferController=new i(this),u=this.capLevelController=new r(this),d=new o(this),g=new Fo(this),f=new Bo(this),m=t.contentSteeringController,T=m?new m(this):null,E=this.levelController=new $h(this,T),S=new gl(this),y=new Gh(this.config),v=this.streamController=new zh(this,S,y);u.setStreamController(v),d.setStreamController(v);const x=[g,E,v];T&&x.splice(1,0,T),this.networkControllers=x;const b=[c,h,u,d,f,S];this.audioTrackController=this.createController(t.audioTrackController,x);const R=t.audioStreamController;R&&x.push(new R(this,S,y)),this.subtitleTrackController=this.createController(t.subtitleTrackController,x);const C=t.subtitleStreamController;C&&x.push(new C(this,S,y)),this.createController(t.timelineController,b),y.emeController=this.emeController=this.createController(t.emeController,b),this.cmcdController=this.createController(t.cmcdController,b),this.latencyController=this.createController($o,b),this.coreComponents=b,x.push(l);const k=l.onErrorOut;typeof k=="function"&&this.on(p.ERROR,k,l)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(A.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===p.ERROR;this.trigger(p.ERROR,{type:B.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){A.log("destroy"),this.trigger(p.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){A.log("attachMedia"),this._media=e,this.trigger(p.MEDIA_ATTACHING,{media:e})}detachMedia(){A.log("detachMedia"),this.trigger(p.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const t=this.media,s=this.url,i=this.url=ai.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,A.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(p.MANIFEST_LOADING,{url:e})}startLoad(e=-1){A.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){A.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){A.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){A.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){A.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){A.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){A.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){A.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){A.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(A.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Go(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var t;return(t=this.audioTrackController)==null?void 0:t.setAudioOption(e)}setSubtitleOption(e){var t;return(t=this.subtitleTrackController)==null||t.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}Ve.defaultConfig=void 0;function Mr(n,e,t){const s=n.slice();return s[13]=e[t].speaker,s[14]=e[t].text,s[15]=e[t].time,s[17]=t,s}function Xh(n){let e;return{c(){e=me("p"),e.textContent="Erro ao carregar transcrições"},m(t,s){ee(t,e,s)},p:oe,d(t){t&&Z(e)}}}function Qh(n){let e,t=zt(n[1]),s=[];for(let i=0;io.parentNode,S.anchor=o,ee(y,o,v),ee(y,l,v),ee(y,c,v),ee(y,h,v),Ee(h,u),ee(y,g,v),ee(y,f,v),Ee(f,m)},p(y,[v]){n=y,v&1&&t!==(t=n[0].title+"")&&Us(s,t),ya(S,n,v),v&1&&d!==(d=n[0].original_url)&&ie(h,"href",d),v&1&&T!==(T=n[0].audio_url)&&ie(f,"href",T),v&1&&E!==(E=n[0].title)&&ie(f,"download",E)},i:oe,o:oe,d(y){y&&(Z(e),Z(i),Z(r),Z(a),Z(o),Z(l),Z(c),Z(h),Z(g),Z(f)),S.block.d(y),S.token=null,S=null}}}function eu(n,e,t){let{params:s={}}=e,i={},r=[],a={},o=null;async function l(){const T=await fetch(`/debates/${s.slug}.json`);t(0,i=await T.json())}function c(){r.forEach(T=>{a[T.speaker]||t(2,a[T.speaker]=`hsl(${Math.floor(Math.random()*360)}, 70%, 60%)`,a)})}async function h(){const T=await fetch(`/debates/transcriptions/${s.slug}.json`);t(1,r=await T.json()),c()}async function u(){const T=document.getElementById("video"),E=`/debates/media/${s.slug}.m3u8`;if(console.log(E),Ve.isSupported()){const y=new Ve;y.loadSource(E),y.attachMedia(T)}else T.src=E;const S=document.querySelector(".chat-container");T.addEventListener("timeupdate",()=>{if(!S)return;const y=T.currentTime;t(3,o=r.findIndex((b,R)=>Ry)),o===-1&&t(3,o=r.length-1);const v=S.querySelectorAll(".message");v.forEach((b,R)=>{b.style.borderColor=R===o?"black":"",b.style.borderWidth=R===o?"3px":""});const x=v[o];x&&!T.paused&&(S.scrollTop=x.offsetTop-S.offsetTop-20)})}const d=T=>(T===0||r[T].speaker!==r[T-1].speaker&&(g=g==="right"?"left":"right"),g);let g="right";const f=T=>{document.getElementById("video").currentTime=parseFloat(T)};ua(async()=>{await l(),await u()});const m=T=>f(T);return n.$$set=T=>{"params"in T&&t(7,s=T.params)},[i,r,a,o,h,d,f,s,m]}class tu extends us{constructor(e){super(),hs(this,e,eu,Zh,It,{params:7})}}const su={"/debate/:slug":tu,"/":wa};function iu(n){let e,t,s,i;return e=new Da({props:{routes:su}}),{c(){At(e.$$.fragment),t=Ce(),s=me("small"),s.innerHTML='Contribui no GitHub'},m(r,a){ht(e,r,a),ee(r,t,a),ee(r,s,a),i=!0},p:oe,i(r){i||($e(e.$$.fragment,r),i=!0)},o(r){He(e.$$.fragment,r),i=!1},d(r){r&&(Z(t),Z(s)),ut(e,r)}}}class ru extends us{constructor(e){super(),hs(this,e,null,iu,It,{})}}new ru({target:document.body}); diff --git a/index.html b/index.html index 05aa7a8..ebdd134 100644 --- a/index.html +++ b/index.html @@ -4,7 +4,7 @@ Legislativas 2024 - +